<ROOT>
	<SQLUPDATELIST>
		<SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>3938</SQLVERSION><RMTRACKLINK>10996</RMTRACKLINK><REASON></REASON><TABLENAMES>RR_Data_Revenue</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
          WHERE Name = N'PaymentId' 
          AND OBJECT_ID = OBJECT_ID(N'RR_Data_Revenue'))
BEGIN
  ALTER TABLE RR_Data_Revenue
  ADD PaymentId Integer NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3937</SQLVERSION><RMTRACKLINK>IDBOS-12012</RMTRACKLINK><REASON>31/07/2025 
Creating new Table AVET_PaymentMethodMapping
NOTE : these tables don't needs XML and automatic store procedures

Script 0: New Table Creation
AVET_PaymentMethodMapping

Script 1: Fill Default value
AVET_PaymentMethodMapping</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                WHERE TABLE_SCHEMA = 'dbo' 
                  AND TABLE_NAME = 'AVET_PaymentMethodMapping')
BEGIN
	CREATE TABLE AVET_PaymentMethodMapping(
		PaymentMethodMappingId int IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
		PaymentMethodCode nvarchar(20) NOT NULL,
		Adquirent nvarchar(30) NULL,
		ModoCobro int NOT NULL,
		Note nvarchar(300) NULL,
	PRIMARY KEY CLUSTERED 
	(
		PaymentMethodMappingId ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>INSERT INTO AVET_PaymentMethodMapping
(PaymentMethodCode, ModoCobro, Note)
VALUES
('_DEFAULT_', 1, 'Do not remove this. It is the standard fallback if no association is found')</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3936</SQLVERSION><RMTRACKLINK>IDBOS-11885</RMTRACKLINK><REASON>Creating new Table AVET_SeatEnvelopeDetail
NOTE : these tables don't needs XML and automatic store procedures

Script 0: New Table Creation
AVET_SeatEnvelopeDetail</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                WHERE TABLE_SCHEMA = 'dbo' 
                  AND TABLE_NAME = 'AVET_SeatEnvelopeDetail')
BEGIN
	CREATE TABLE AVET_SeatEnvelopeDetail(
		SeatId int NOT NULL,
		EnvelopeId int NOT NULL,
		PerformanceId int NULL,
		CONSTRAINT UQ_SeatId_EnvelopeId UNIQUE (SeatId,PerformanceId)
	)
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3935</SQLVERSION><RMTRACKLINK>IDBOS-11943</RMTRACKLINK><REASON>18/07/2025 
Creating for all the BOS Installations the AVET Tables.
NOTE : these tables don't needs XML and automatic store procedures

Scipt 0 : New Tables Creation
AVET_AvailabilityAndPrice
AVET_BlockArea
AVET_BlockAreaTemplate
AVET_HoldSeat
AVET_LoginSocio
AVET_SaleImage
AVET_SaleInfo
AVET_SeatDetail
AVET_SeasonPassHoldedSeat

Script 1 : New Index Creation
IDX1_AVET_SeatDetail_SeatId_Incl  on AVET_SeatDetail
</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>-- AVET_AvailabilityAndPrice --
IF NOT EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                WHERE TABLE_SCHEMA = 'dbo' 
                  AND TABLE_NAME = 'AVET_AvailabilityAndPrice')
BEGIN
	CREATE TABLE [dbo].[AVET_AvailabilityAndPrice](
		[AvailabilityAndPriceId] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
		[BlockId] [int] NULL,
		[PerformanceId] [int] NULL,
		[MatchId] [int] NULL,
		[SpaceStructureId] [int] NULL,
		[SeatCategoryId] [int] NULL,
		[PriceId] [int] NULL,
		[Price] [float] NULL,
		[Availability] [int] NULL,
		[B2BPriceId] [int] NULL,
		[B2BPrice] [float] NULL,
		[B2BAvailability] [int] NULL,
	PRIMARY KEY CLUSTERED 
	(
		[AvailabilityAndPriceId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]
END


-- AVET_BlockArea --
IF NOT EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                WHERE TABLE_SCHEMA = 'dbo' 
                  AND TABLE_NAME = 'AVET_BlockArea')
BEGIN
	CREATE TABLE [dbo].[AVET_BlockArea](
		[BlockAreaId] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
		[BlockId] [int] NULL,
		[PerformanceId] [int] NULL,
		[MatchId] [int] NULL,
		[SpaceStructureId] [int] NULL,
		[SeatCategoryId] [int] NULL,
		[AreaId] [int] NULL,
		[PriceId] [int] NULL,
		[InitialPrice] [float] NULL,
		[InitialAvailability] [int] NULL,
		[B2BPriceId] [int] NULL,
		[B2BInitialPrice] [float] NULL,
		[B2BInitialAvailability] [int] NULL,
	PRIMARY KEY CLUSTERED 
	(
		[BlockAreaId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]
END


-- AVET_BlockAreaTemplate --
IF NOT EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                WHERE TABLE_SCHEMA = 'dbo' 
                  AND TABLE_NAME = 'AVET_BlockAreaTemplate')
BEGIN
	CREATE TABLE [dbo].[AVET_BlockAreaTemplate](
		[Code] [varchar](max) NULL,
		[Name] [varchar](max) NULL,
		[BlockId] [int] NULL,
		[AreaIds] [varchar](max) NULL
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END


-- AVET_HoldSeat --
IF NOT EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                WHERE TABLE_SCHEMA = 'dbo' 
                  AND TABLE_NAME = 'AVET_HoldSeat')
BEGIN
	CREATE TABLE [dbo].[AVET_HoldSeat](
		[HoldSeatId] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
		[PreHoldDateTime] [datetime] NULL,
		[SeatId] [int] NULL,
		[PerformanceId] [int] NULL,
		[SpaceStructureId] [int] NULL,
	PRIMARY KEY CLUSTERED 
	(
		[HoldSeatId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]
END

-- AVET_LoginSocio --
IF NOT EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                WHERE TABLE_SCHEMA = 'dbo' 
                  AND TABLE_NAME = 'AVET_LoginSocio')
BEGIN
	CREATE TABLE [dbo].[AVET_LoginSocio](
		[IDSocio] [varchar](40) NULL,
		[PIN] [varchar](40) NULL,
		[LastLogin] [datetime] NULL,
		[CollectiveId] [int] NULL,
		[IDPersona] [varchar](40) NULL
	) ON [PRIMARY]
END


-- AVET_SaleImage --
IF NOT EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                WHERE TABLE_SCHEMA = 'dbo' 
                  AND TABLE_NAME = 'AVET_SaleImage')
BEGIN
	CREATE TABLE [dbo].[AVET_SaleImage](
		[Saleid] [int] NULL,
		[Seatid] [int] NULL,
		[Image] [varbinary](max) NULL
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END



-- AVET_SaleInfo --
IF NOT EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                WHERE TABLE_SCHEMA = 'dbo' 
                  AND TABLE_NAME = 'AVET_SaleInfo')
BEGIN
	CREATE TABLE [dbo].[AVET_SaleInfo](
		[SaleInfoId] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
		[SeatId] [int] NULL,
		[SaleId] [int] NULL,
		[Stairs] [varchar](200) NULL,
		[Gate] [varchar](200) NULL,
	PRIMARY KEY CLUSTERED 
	(
		[SaleInfoId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]
END

-- AVET_SeatDetail --
IF NOT EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                WHERE TABLE_SCHEMA = 'dbo' 
                  AND TABLE_NAME = 'AVET_SeatDetail')
BEGIN
	CREATE TABLE [dbo].[AVET_SeatDetail](
		[SeatDetailId] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
		[AforoId] [int] NULL,
		[AreaId] [int] NULL,
		[PosRow] [int] NULL,
		[PosSeat] [int] NULL,
		[Row] [varchar](32) NULL,
		[Seat] [varchar](32) NULL,
		[SeatId] [int] NULL,
		[Vomitorio] [varchar](200) NULL,
		[Gate] [varchar](200) NULL,
	PRIMARY KEY CLUSTERED 
	(
		[SeatDetailId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]
END

-- AVET_SeasonPassHoldedSeat  --
IF NOT EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                WHERE TABLE_SCHEMA = 'dbo' 
                  AND TABLE_NAME = 'AVET_SeasonPassHoldedSeat')
BEGIN
	CREATE TABLE [dbo].AVET_SeasonPassHoldedSeat(
		[SeasonPassHoldedSeatId] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
		[SeatId] [int] NULL,
		[PerformanceId] [int] NULL,
		[SpaceStructureId] [int] NULL,
	PRIMARY KEY CLUSTERED 
	(
		[SeasonPassHoldedSeatId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.indexes
               WHERE NAME='IDX1_AVET_SeatDetail_SeatId_Incl' AND object_id = OBJECT_ID('AVET_SeatDetail'))
BEGIN
	CREATE NONCLUSTERED INDEX [IDX1_AVET_SeatDetail_SeatId_Incl] ON [dbo].[AVET_SeatDetail]
	( [SeatId] ASC ) INCLUDE([Gate])
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>ecandido</ADDEDBY><SQLVERSION>3934</SQLVERSION><RMTRACKLINK>IDBOS-10236</RMTRACKLINK><REASON>Add New Rules for reservation Delete</REASON><TABLENAMES>DATA_AccountFinancial=AccountId
CNF_StatisticalGroup=StatisticalGroupId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
               WHERE Name = N'MaxDaysAfterExpirationOpenTickets' AND
               Object_ID  = Object_ID(N'DATA_AccountFinancial'))
BEGIN
  ALTER TABLE DATA_AccountFinancial ADD MaxDaysAfterExpirationOpenTickets smallint NULL
END

IF NOT EXISTS (SELECT * FROM sys.columns
               WHERE Name = N'DenyDeleteStatisticalGroup' AND
               Object_ID  = Object_ID(N'DATA_AccountFinancial'))
BEGIN
  ALTER TABLE DATA_AccountFinancial ADD DenyDeleteStatisticalGroup smallint NULL
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
               WHERE Name = N'MaxDaysAfterCreationTickets' AND
               Object_ID  = Object_ID(N'CNF_StatisticalGroup'))
BEGIN
  ALTER TABLE CNF_StatisticalGroup ADD MaxDaysAfterCreationTickets smallint NULL
END
</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>nchinea</ADDEDBY><SQLVERSION>3933</SQLVERSION><RMTRACKLINK>FTC-38</RMTRACKLINK><REASON>Ticket Entry Option
CNF_MatrixCellInfo - EntryOptSelReq
ADM_AccessPoint   - EntryOptSelReq
DATA_SaleItem      - EntryOptSelReq</REASON><TABLENAMES>CNF_MatrixCellInfo=MatrixCellInfoId
ADM_AccessPoint=WorkstationId
DATA_SaleItem=SaleItemId</TABLENAMES><SQLSCRIPTLIST><SCRIPT> IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'EntryOptSelReq'
                      AND OBJECT_ID = OBJECT_ID(N'CNF_MatrixCellInfo'))
BEGIN 
   ALTER TABLE dbo.CNF_MatrixCellInfo ADD EntryOptSelReq SMALLINT NOT NULL DEFAULT 0;
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>  IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'EntryOptSelReq'
                      AND OBJECT_ID = OBJECT_ID(N'ADM_AccessPoint'))
BEGIN 
   ALTER TABLE dbo.ADM_AccessPoint ADD EntryOptSelReq SMALLINT; 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>  IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'EntryOptSelReq'
                      AND OBJECT_ID = OBJECT_ID(N'DATA_SaleItem'))
BEGIN 
   ALTER TABLE dbo.DATA_SaleItem ADD EntryOptSelReq SMALLINT; 
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>ecandido</ADDEDBY><SQLVERSION>3932</SQLVERSION><RMTRACKLINK>IDBOS-10236</RMTRACKLINK><REASON>Chage Column Name From "DenyDeleteRrefund" To "DenyDeleteRefund" in Data_AccountFinancial for reservation elete limit</REASON><TABLENAMES>DATA_AccountFinancial=AccountId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
               WHERE Name = N'DenyDeleteRrefund' AND
               Object_ID  = Object_ID(N'DATA_AccountFinancial'))
BEGIN
  EXEC sp_RENAME 'DATA_AccountFinancial.DenyDeleteRrefund', 'DenyDeleteRefund', 'COLUMN'
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3931</SQLVERSION><RMTRACKLINK>IBDOS-11625</RMTRACKLINK><REASON>Script 0 - Renamed NoteAk in AdditionalInfo</REASON><TABLENAMES>DATA_Note=NoteId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
               WHERE Name = N'NoteAk' AND
               Object_ID  = Object_ID(N'DATA_Note'))
BEGIN
  EXEC sp_RENAME 'DATA_Note.NoteAk', 'AdditionalInfo', 'COLUMN'
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dfarisato</ADDEDBY><SQLVERSION>3930</SQLVERSION><RMTRACKLINK>IDBOS-11377</RMTRACKLINK><REASON>Removed Tables Modified (DS)


change fielname from Last_Workstation_log to Last_Workstationid_log</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>select 1</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>ecandido</ADDEDBY><SQLVERSION>3929</SQLVERSION><RMTRACKLINK>IDBOS-10236</RMTRACKLINK><REASON>Add New Rules for reservation Delete</REASON><TABLENAMES>DATA_AccountFinancial=AccountId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
               WHERE Name = N'DenyDeleteProductRedemption' AND
               Object_ID  = Object_ID(N'DATA_AccountFinancial'))
BEGIN
  ALTER TABLE DATA_AccountFinancial ADD DenyDeleteProductRedemption smallint NULL
END

IF NOT EXISTS (SELECT * FROM sys.columns
               WHERE Name = N'DenyDeleteEntitlementRedemption' AND
               Object_ID  = Object_ID(N'DATA_AccountFinancial'))
BEGIN
  ALTER TABLE DATA_AccountFinancial ADD DenyDeleteEntitlementRedemption smallint NULL
END

IF NOT EXISTS (SELECT * FROM sys.columns
               WHERE Name = N'MaxDaysAfterCreationOpenTickets' AND
               Object_ID  = Object_ID(N'DATA_AccountFinancial'))
BEGIN
  ALTER TABLE DATA_AccountFinancial ADD MaxDaysAfterCreationOpenTickets smallint NULL
END

IF NOT EXISTS (SELECT * FROM sys.columns
               WHERE Name = N'DenyDeleteUpgradeDowngrade' AND
               Object_ID  = Object_ID(N'DATA_AccountFinancial'))
BEGIN
  ALTER TABLE DATA_AccountFinancial ADD DenyDeleteUpgradeDowngrade smallint NULL
END

IF NOT EXISTS (SELECT * FROM sys.columns
               WHERE Name = N'DenyDeleteReissue' AND
               Object_ID  = Object_ID(N'DATA_AccountFinancial'))
BEGIN
  ALTER TABLE DATA_AccountFinancial ADD DenyDeleteReissue smallint NULL
END

IF NOT EXISTS (SELECT * FROM sys.columns
               WHERE Name = N'DenyDeleteRrefund' AND
               Object_ID  = Object_ID(N'DATA_AccountFinancial'))
BEGIN
  ALTER TABLE DATA_AccountFinancial ADD DenyDeleteRrefund smallint NULL
END

IF NOT EXISTS (SELECT * FROM sys.columns
               WHERE Name = N'DenyDeleteRenew' AND
               Object_ID  = Object_ID(N'DATA_AccountFinancial'))
BEGIN
  ALTER TABLE DATA_AccountFinancial ADD DenyDeleteRenew smallint NULL
END
</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dfarisato</ADDEDBY><SQLVERSION>3928</SQLVERSION><RMTRACKLINK>IDBOS-11375</RMTRACKLINK><REASON>Modified a little bit the Scripts (DS)

script 0 - Resetted
script 1 - Resetted
script 2 - Resetted
script 3 - CheckRequiredReservationOwner fields added in CNF_DmgCategory as smallint
script 4- CheckRequiredBillingAccount fields added in CNF_DmgCategory as smallint
script 5 - CheckRequiredLoginAccount fields added in CNF_DmgCategory as smallint</REASON><TABLENAMES>CNF_DmgCategory=DmgCategoryId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>SELECT 1
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>SELECT 1</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>SELECT 1</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'CheckRequiredReservationOwner'
                      AND OBJECT_ID = OBJECT_ID(N'CNF_DmgCategory'))
BEGIN 
   ALTER TABLE CNF_DmgCategory 
   ADD CheckRequiredReservationOwner SMALLINT NOT NULL DEFAULT 0
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'CheckRequiredBillingAccount'
                      AND OBJECT_ID = OBJECT_ID(N'CNF_DmgCategory'))
BEGIN 
   ALTER TABLE CNF_DmgCategory 
   ADD CheckRequiredBillingAccount SMALLINT NOT NULL DEFAULT 0
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'CheckRequiredLoginAccount'
                      AND OBJECT_ID = OBJECT_ID(N'CNF_DmgCategory'))
BEGIN 
   ALTER TABLE CNF_DmgCategory 
   ADD CheckRequiredLoginAccount SMALLINT NOT NULL DEFAULT 0
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>nchinea</ADDEDBY><SQLVERSION>3927</SQLVERSION><RMTRACKLINK>IDBOS-11480</RMTRACKLINK><REASON>Realignment familytype 1541 INFOSYS_Service</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>DECLARE @FAM1541 Varchar(50);
DECLARE @FAM1542 Varchar(50);
SELECT @FAM1542= FamilyType FROM CNF_Right
               WHERE FamilyType=1542 
IF @FAM1542 IS NULL 
begin
  SELECT @FAM1541= FamilyType FROM CNF_Right
               WHERE FamilyType=15421
  IF @FAM1541 IS Not NULL 
    update CNF_Right set FamilyType = 1542 where FamilyType = 1541
end    </SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dfarisato</ADDEDBY><SQLVERSION>3926</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>correction script for CNF_DataMaskPrivacyHistory
script 0 -  DROP CONSTRAINT FK_DataMaskPrivacyHistory_DataMaskId
script 1 -  add MaskId field in CNF_DataMaskPrivacyHistory
script 2 - 	add FK MaskId of CNF_DataMaskPrivacyHistory references to MaskId to CNF_Mask 
script 3 - drop the column DataMaskId</REASON><TABLENAMES>CNF_DataMaskPrivacyHistory=datamaskprivacyId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_DataMaskPrivacyHistory_DataMaskId')
BEGIN 
  ALTER TABLE dbo.CNF_DataMaskPrivacyHistory DROP CONSTRAINT FK_DataMaskPrivacyHistory_DataMaskId;
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>-- Check if the table exists before attempting to modify it
IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'MaskId'
                      AND OBJECT_ID = OBJECT_ID(N'CNF_DataMaskPrivacyHistory'))
BEGIN 
   ALTER TABLE dbo.CNF_DataMaskPrivacyHistory ADD MaskId integer;
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_DataMaskPrivacyHistory_MaskId')
BEGIN
	ALTER TABLE [CNF_DataMaskPrivacyHistory]  
	ADD CONSTRAINT [FK_DataMaskPrivacyHistory_MaskId] FOREIGN KEY([MaskId])
	REFERENCES [CNF_Mask] ([MaskId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>-- Check if the table exists before attempting to modify it
IF EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'DataMaskId'
                      AND OBJECT_ID = OBJECT_ID(N'CNF_DataMaskPrivacyHistory'))
BEGIN 
   ALTER TABLE dbo.CNF_DataMaskPrivacyHistory  DROP COLUMN DataMaskId
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>scoluccia</ADDEDBY><SQLVERSION>3925</SQLVERSION><RMTRACKLINK>IDBOS-11401</RMTRACKLINK><REASON>Added the correct records in all promotion taḅes of the new system promotion type based on rolling discount</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT PromotionItemId FROM CNF_PromotionItem WHERE PromotionId in (select PromotionId from CNF_Promotion where PromotionType = 402))
  DELETE CNF_Promotion where PromotionType = 402

IF NOT EXISTS (SELECT PromotionItemId FROM CNF_PromotionItem WHERE PromotionId in (select PromotionId from CNF_Promotion where PromotionType = 403))
  DELETE CNF_Promotion where PromotionType = 403
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT Promotionid from CNF_Promotion where PromotionType = 402) 
BEGIN
  INSERT INTO CNF_Promotion
    ("Description", "Active", "Code", "PromotionType") 
    VALUES ('ROLLING CAPACITY DISCOUNT', 1, 'ROLLINGCAP', 402);

  INSERT INTO CNF_PromotionItem
    ("PromotionId", "Description", "RuleType") 
    VALUES ((SELECT SCOPE_IDENTITY() AS PromotionID), 'Rolling Capacity Discount', 'Advanced');

  INSERT INTO CNF_PromotionItemRule
    (PromotionItemId, AnyProduct, ApplyDiscountToAllItem) 
    VALUES ((SELECT SCOPE_IDENTITY() AS PromotionID), 0, 0);
END

IF NOT EXISTS (SELECT Promotionid from CNF_Promotion where PromotionType = 403) 
BEGIN
  INSERT INTO CNF_Promotion
    ("Description", "Active", "Code", "PromotionType") 
    VALUES ('ROLLING MIXED DISCOUNT', 1, 'ROLLINGMIXED', 403);

  INSERT INTO CNF_PromotionItem
    ("PromotionId", "Description", "RuleType") 
    VALUES ((SELECT SCOPE_IDENTITY() AS PromotionID), 'Rolling Mixed Discount', 'Advanced');

  INSERT INTO CNF_PromotionItemRule
    (PromotionItemId, AnyProduct, ApplyDiscountToAllItem) 
    VALUES ((SELECT SCOPE_IDENTITY() AS PromotionID), 0, 0);
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>scoluccia</ADDEDBY><SQLVERSION>3924</SQLVERSION><RMTRACKLINK>IDBOS-11401</RMTRACKLINK><REASON>Added two new system promotion type based on rolling discount</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT Promotionid from CNF_Promotion where PromotionType = 402) 
  INSERT INTO CNF_Promotion
    ("Description", "Active", "Code", "PromotionType") 
    VALUES ('ROLLING CAPACITY DISCOUNT', 1, 'ROLLINGCAP', 402);

IF NOT EXISTS (SELECT Promotionid from CNF_Promotion where PromotionType = 403) 
  INSERT INTO CNF_Promotion
     ("Description", "Active", "Code", "PromotionType") 
     VALUES ('ROLLING MIXED DISCOUNT', 1, 'ROLLINGMIX', 403);
     </SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dfarisato</ADDEDBY><SQLVERSION>3923</SQLVERSION><RMTRACKLINK>IDBOS-11374</RMTRACKLINK><REASON>Modified a little bit the Scripts (DS)

Script 0 - add new field ResetPrivacyValue in CNF_DATAMASK
Script 1 - add new field NotifyPrivacyPolicy in CNF_DATAMASK</REASON><TABLENAMES>CNF_DATAMASK=datamaskid</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'ResetPrivacyValue'
                      AND OBJECT_ID = OBJECT_ID(N'CNF_DATAMASK'))
BEGIN 
  ALTER TABLE CNF_DATAMASK  
  ADD ResetPrivacyValue SMALLINT NOT NULL DEFAULT 0
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'NotifyPrivacyPolicy'
                      AND OBJECT_ID = OBJECT_ID(N'CNF_DATAMASK'))
BEGIN
  ALTER TABLE CNF_DATAMASK  
  ADD NotifyPrivacyPolicy SMALLINT NOT NULL DEFAULT 0 
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dfarisato</ADDEDBY><SQLVERSION>3922</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>Script 0 - create table CNF_DataMaskPrivacyHistory
Script 1 - Add Foreign Hey FK_DataMaskPrivacyHistory_DataMaskId
Script 2 - Add Foreign Hey FK_DataMaskPrivacyHistory_UserId
Script 3 - Add Foreign Hey FK_DataMaskPrivacyHistory_WorkstationId

Script 4 - create table DATA_AccountPrivacyHistory
Script 5 - Add Foreign Hey FK_AccountPrivacyHistory_AccountId
Script 6 - Add Foreign Hey FK_AccountPrivacyHistory_UserId
Script 7 - Add Foreign Hey FK_AccountPrivacyHistory_WorkstationId
</REASON><TABLENAMES>CNF_DataMaskPrivacyHistory=DataMaskPrivacyId
DATA_AccountPrivacyHistory=AccountPrivacyId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                WHERE TABLE_SCHEMA = 'dbo' 
                  AND TABLE_NAME = 'CNF_DataMaskPrivacyHistory')
BEGIN
CREATE TABLE CNF_DataMaskPrivacyHistory(
	[DataMaskPrivacyId] integer IDENTITY(1,1) NOT NULL,
	[DataMaskId] integer NOT NULL,
	[ObjType] integer not NULL,
	[OperationType] integer NULL,
	[NotifyToAccount] smallint not NULL,
	[ResetAccountValue] smallint not NULL,
	[Value] nvarchar(1000) NULL,
	[Hash] nvarchar(50) not NULL,          
	[NotifyStatus] integer NULL,
	[Last_UserId_Log] integer NULL,
	[Last_WorkstationId_Log] integer NULL,
	[Last_DateTime_Log] datetime NULL,
Primary Key ([DataMaskPrivacyId])
) 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_DataMaskPrivacyHistory_DataMaskId')
BEGIN
	ALTER TABLE [CNF_DataMaskPrivacyHistory]  
	ADD CONSTRAINT [FK_DataMaskPrivacyHistory_DataMaskId] FOREIGN KEY([DataMaskId])
	REFERENCES [CNF_DataMask] ([DataMaskId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_DataMaskPrivacyHistory_UserId')
BEGIN
	ALTER TABLE [CNF_DataMaskPrivacyHistory]  
	ADD CONSTRAINT [FK_DataMaskPrivacyHistory_UserId] FOREIGN KEY([Last_UserId_Log])
	REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_DataMaskPrivacyHistory_WorkstationId')
BEGIN
	ALTER TABLE [CNF_DataMaskPrivacyHistory]  
	ADD CONSTRAINT [FK_DataMaskPrivacyHistory_WorkstationId] FOREIGN KEY([Last_WorkstationId_Log])
	REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                WHERE TABLE_SCHEMA = 'dbo' 
                  AND TABLE_NAME = 'DATA_AccountPrivacyHistory')
BEGIN
CREATE TABLE DATA_AccountPrivacyHistory(
	[AccountPrivacyId] integer IDENTITY(1,1) NOT NULL,
	[AccountId] integer NOT NULL,
	[DataMaskPrivacyId] integer not NULL,
	[ObjType] integer not NULL,
	[OperationType] integer NULL,
	[SystemOrUser] smallint not NULL, 
	[Value] nvarchar(1000) NULL,
	[Hash] nvarchar(50) not NULL,           
	[Last_UserId_Log] integer NULL,
	[Last_WorkstationId_Log] integer NULL,
	[Last_DateTime_Log] datetime NULL,
Primary Key ([AccountPrivacyId])
) 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_AccountPrivacyHistory_AccountId')
BEGIN
	ALTER TABLE [DATA_AccountPrivacyHistory]  
	ADD CONSTRAINT [FK_AccountPrivacyHistory_AccountId] FOREIGN KEY([AccountId])
	REFERENCES [DATA_Account] ([AccountId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_AccountPrivacyHistory_UserId')
BEGIN
	ALTER TABLE [DATA_AccountPrivacyHistory]  
	ADD CONSTRAINT [FK_AccountPrivacyHistory_UserId] FOREIGN KEY([Last_UserId_Log])
	REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_AccountPrivacyHistory_WorkstationId')
BEGIN
	ALTER TABLE [DATA_AccountPrivacyHistory]  
	ADD CONSTRAINT [FK_AccountPrivacyHistory_WorkstationId] FOREIGN KEY([Last_WorkstationId_Log])
	REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>scoluccia</ADDEDBY><SQLVERSION>3921</SQLVERSION><RMTRACKLINK>11305</RMTRACKLINK><REASON>- Add new field ReleaseQuotaOnRefund for account restriction</REASON><TABLENAMES>CNF_ACCOUNTRESTRICTION=AccountRestrictionId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'ReleaseQuotaOnRefund'
                      AND OBJECT_ID = OBJECT_ID(N'CNF_ACCOUNTRESTRICTION'))
BEGIN
  ALTER TABLE CNF_ACCOUNTRESTRICTION
  ADD ReleaseQuotaOnRefund SMALLINT NOT NULL DEFAULT 1;
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>scoluccia</ADDEDBY><SQLVERSION>3920</SQLVERSION><RMTRACKLINK>11355</RMTRACKLINK><REASON>- Add new field CopyPerformanceToAllItems for package</REASON><TABLENAMES>CNF_Promotion=PromotionId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'CopyPerformanceToAllItems'
                      AND OBJECT_ID = OBJECT_ID(N'CNF_PROMOTION'))
BEGIN
  ALTER TABLE CNF_PROMOTION
  ADD CopyPerformanceToAllItems SMALLINT NOT NULL DEFAULT 0;
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>sloporto</ADDEDBY><SQLVERSION>3919</SQLVERSION><RMTRACKLINK>IDBOS-11253</RMTRACKLINK><REASON>Script 0 - DROP INDEX  IDX_SaleItem_ProductTypeSalIdSaleItemId
Script 1 - DROP INDEX  Idx_PromotionValidity_[PromIdValDateType
Script 2 - CREATE INDEX IDX_DATA_SaleItem_ProductType_SalId_SaleItemId
Script 3 - CREATE INDEX  IDX_CNF_PromotionValidity_PromotionId_ValidityDateType
Script 4 - CREATE INDEX IDX_DATA_MagicLink2Ticket_MagicLinkId_Status
</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * 
                FROM sys.indexes 
            WHERE name='IDX_SaleItem_ProductTypeSalIdSaleItemId' AND object_id = OBJECT_ID('DATA_SaleItem')
			)
BEGIN
	DROP INDEX [IDX_SaleItem_ProductTypeSalIdSaleItemId]  ON [dbo].[DATA_SaleItem]
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * 
                FROM sys.indexes 
            WHERE name='Idx_PromotionValidity_[PromIdValDateType' AND object_id = OBJECT_ID('CNF_PromotionValidity')
			)
BEGIN
	DROP INDEX [Idx_PromotionValidity_[PromIdValDateType]  ON [dbo].[CNF_PromotionValidity] 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                FROM sys.indexes 
            WHERE name='IDX_DATA_SaleItem_ProductType_SalId_SaleItemId' AND object_id = OBJECT_ID('DATA_SaleItem')
			)
BEGIN
  CREATE NONCLUSTERED INDEX [IDX_DATA_SaleItem_ProductType_SalId_SaleItemId] ON [dbo].[DATA_SaleItem]
  ( [ProductType] ASC,
    [SaleId] ASC,
    [SaleItemId] ASC
  ) 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                FROM sys.indexes 
            WHERE name='IDX_CNF_PromotionValidity_PromotionId_ValidityDateType' AND object_id = OBJECT_ID('CNF_PromotionValidity')
			)
BEGIN
  CREATE NONCLUSTERED INDEX [IDX_CNF_PromotionValidity_PromotionId_ValidityDateType]
  ON [dbo].[CNF_PromotionValidity] 
  ( [PromotionId],
    [ValidityDateType]
  )
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                FROM sys.indexes 
            WHERE name='IDX_DATA_MagicLink2Ticket_MagicLinkId_Status' AND object_id = OBJECT_ID('DATA_MagicLink2Ticket')
			)
BEGIN
  CREATE NONCLUSTERED INDEX [IDX_DATA_MagicLink2Ticket_MagicLinkId_Status] ON [dbo].[DATA_MagicLink2Ticket]
  ([MagicLinkId] DESC,
   [Status] ASC
  )
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>pdalben</ADDEDBY><SQLVERSION>3918</SQLVERSION><RMTRACKLINK>IDBOS-10630</RMTRACKLINK><REASON>Added fields to CNF_SuggestiveSell2MatrixCell</REASON><TABLENAMES>CNF_SuggestiveSell2MatrixCell=SuggestiveSell2MatrixCellId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
              WHERE Name = N'Quantity'
              AND OBJECT_ID = OBJECT_ID(N'CNF_SuggestiveSell2MatrixCell'))
BEGIN
  ALTER TABLE CNF_SuggestiveSell2MatrixCell
  ADD Quantity INT NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>pdalben</ADDEDBY><SQLVERSION>3917</SQLVERSION><RMTRACKLINK>IDBOS-10630</RMTRACKLINK><REASON>Added fields to CNF_SuggestiveSell</REASON><TABLENAMES>CNF_SuggestiveSell=SuggestiveSellId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
              WHERE Name = N'SuggestiveSellType'
              AND OBJECT_ID = OBJECT_ID(N'CNF_SuggestiveSell'))
BEGIN
  ALTER TABLE CNF_SuggestiveSell
  ADD SuggestiveSellType SMALLINT DEFAULT 0 NOT NULL 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
              WHERE Name = N'ApplyMultipleTime'
              AND OBJECT_ID = OBJECT_ID(N'CNF_SuggestiveSell'))
BEGIN
  ALTER TABLE CNF_SuggestiveSell
  ADD ApplyMultipleTime SMALLINT DEFAULT 0 NOT NULL 
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>nchinea</ADDEDBY><SQLVERSION>3916</SQLVERSION><RMTRACKLINK>IDBOS-10179</RMTRACKLINK><REASON>Patch fo 3915</REASON><TABLENAMES>DATA_Ticket=TicketId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>  Select 1</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>nchinea</ADDEDBY><SQLVERSION>3915</SQLVERSION><RMTRACKLINK>IDBOS-10179</RMTRACKLINK><REASON>Script 0 - Add field Suspend to DATA_TICKET
Script 0 - Add field SuspToDate to DATA_TICKET</REASON><TABLENAMES>DATA_Ticket=TicketId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>     IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'Suspend'
                      AND OBJECT_ID = OBJECT_ID(N'DATA_Ticket'))
BEGIN
  ALTER TABLE DATA_Ticket
  ADD Suspend SmallInt 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'SuspToDate'
                      AND OBJECT_ID = OBJECT_ID(N'DATA_Ticket'))
BEGIN
  ALTER TABLE DATA_Ticket
  ADD SuspToDate DateTime 
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>sloporto</ADDEDBY><SQLVERSION>3914</SQLVERSION><RMTRACKLINK>IDBOS-11053</RMTRACKLINK><REASON>Script 0 - Add field MagicLinkHash to DATA_MagicLink
Script 1- Create index for field MagicLinkHash</REASON><TABLENAMES>DATA_Magiclink=MagicLinkId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'MagicLinkHash'
                      AND OBJECT_ID = OBJECT_ID(N'DATA_MagicLink'))
BEGIN
  ALTER TABLE DATA_MagicLink
  ADD MagicLinkHash VARCHAR(40) NULL 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                FROM sys.indexes 
            WHERE name='IDX_DATA_MagicLink_MagicLinkHash' AND object_id = OBJECT_ID('DATA_MagicLink')
			)
BEGIN
	CREATE NONCLUSTERED INDEX [IDX_DATA_MagicLink_MagicLinkHash]
	ON [dbo].[DATA_MagicLink] ([MagicLinkHash])
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3913</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3912</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3911</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3910</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3909</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3908</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3907</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3906</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3905</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3904</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3903</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3902</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3901</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3900</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3899</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3898</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3897</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3911</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3910</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3909</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3908</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3907</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3906</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3905</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3904</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3903</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3902</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3901</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3900</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3899</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3898</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3897</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3896</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3895</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3894</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3893</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3892</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3891</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3890</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3889</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3888</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3887</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3886</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3885</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3884</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3883</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3882</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3881</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3880</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3879</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3878</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3877</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3876</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3875</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3874</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3873</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3872</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3871</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3870</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3869</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3868</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3867</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3866</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3865</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3864</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3863</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3862</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3861</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3860</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3859</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3858</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3857</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3856</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3855</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3854</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3853</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3852</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3851</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3850</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3849</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3848</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3847</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3846</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3845</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3844</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3843</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3842</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3841</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3840</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3839</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3838</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3837</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3836</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3835</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3834</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3833</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3832</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3831</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3830</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3829</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3828</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3827</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3826</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3825</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3824</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3823</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3822</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3821</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3820</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3819</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3818</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3817</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3816</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3815</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.41.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>pdalben</ADDEDBY><SQLVERSION>3814</SQLVERSION><RMTRACKLINK>IDBOS-10792</RMTRACKLINK><REASON>0 Added CNF_Site.StagingEnvironment
1 Added CNF_Event.TransportType</REASON><TABLENAMES>CNF_Site=SiteId
CNF_Event=EventId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'StagingEnvironment'
                      AND OBJECT_ID = OBJECT_ID(N'CNF_Site'))
BEGIN
  ALTER TABLE CNF_Site
  ADD StagingEnvironment SMALLINT DEFAULT 0 NOT NULL 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'TransportType'
                      AND OBJECT_ID = OBJECT_ID(N'CNF_Event'))
BEGIN
  ALTER TABLE CNF_Event
  ADD TransportType SMALLINT DEFAULT 0 NOT NULL 
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>sloporto</ADDEDBY><SQLVERSION>3813</SQLVERSION><RMTRACKLINK>IDBOS-10587</RMTRACKLINK><REASON>Script 0 = alter table DATA_Magiclink alter MagicLink Type from varchar to text</REASON><TABLENAMES>DATA_Magiclink=MagicLinkId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'MagicLink'
                      AND OBJECT_ID = OBJECT_ID(N'DATA_MagicLink'))
BEGIN
  ALTER TABLE DATA_MagicLink
  ALTER COLUMN MagicLink ntext NOT NULL;
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3812</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3811</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3810</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3809</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3808</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3807</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3806</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3805</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3804</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3803</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3802</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3801</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3800</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3799</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3798</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3797</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3796</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3795</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3794</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3793</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3792</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3791</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3790</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3789</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3788</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3787</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3786</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3785</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3784</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3783</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3782</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3781</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3780</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3779</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3778</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3777</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3776</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3775</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3774</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3773</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3772</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3771</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3770</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3769</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3768</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3767</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3766</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3765</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3764</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3763</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3762</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3761</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3760</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3759</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3758</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3757</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3756</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3755</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3754</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3753</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3752</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3751</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3750</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3749</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3748</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3747</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3746</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3745</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3744</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3743</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3742</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3741</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3740</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3739</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3738</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3737</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3736</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3735</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3734</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3733</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3732</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3731</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3730</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3729</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3728</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3727</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3726</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3725</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3724</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3723</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3722</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3721</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3720</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3719</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3718</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3717</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3716</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3715</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3714</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fpedrazzi</ADDEDBY><SQLVERSION>3713</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.39.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3712</SQLVERSION><RMTRACKLINK>IDBOS-10679</RMTRACKLINK><REASON>CACHEMANAGER - CNF_PriceList management
Script 1 - Adding new Item in SYS_CacheTable
Script 2 - Adding new Trigger on CNF_PriceList</REASON><TABLENAMES>SYS_CacheTable=Tableid</TABLENAMES><SQLSCRIPTLIST><SCRIPT>insert into SYS_CacheTable (TableName, IRN, FunctionCall) VALUES ('CNF_PriceList',1,'CheckPriceListCache')</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>Declare @TABLE VarChar(200)    
Set @TABLE = 'CNF_PriceList'
EXEC('IF OBJECT_ID ('''+@TABLE+'_Cache'', ''TR'') IS NOT NULL DROP TRIGGER '+@TABLE+'_Cache')
EXEC('CREATE TRIGGER [dbo].['+@TABLE+'_Cache] on [dbo].['+@TABLE+'] AFTER INSERT,DELETE,UPDATE 
      AS 
	  BEGIN  
	    Declare @Sql nvarchar(max);	
		SET NOCOUNT ON;	
		set @Sql = '''+@TABLE+''';
		EXEC otn_sp_CACHE_TABLE_update @Sql
	  END')</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>scoluccia</ADDEDBY><SQLVERSION>3711</SQLVERSION><RMTRACKLINK>10524</RMTRACKLINK><REASON>- Add new field DYnamic Price Status
</REASON><TABLENAMES>CNF_Event=EventId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'DynamicPriceStatus'
                      AND OBJECT_ID = OBJECT_ID(N'CNF_EVENT'))
BEGIN
  ALTER TABLE CNF_EVENT
  ADD DynamicPriceStatus SMALLINT NOT NULL DEFAULT 0;
END

</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>sloporto</ADDEDBY><SQLVERSION>3710</SQLVERSION><RMTRACKLINK>IDBOS-10587</RMTRACKLINK><REASON>Script 0 - Add new table DATA_Magiclink
Script 1 - Add Foregn Key FK_DATA_Magiclink_Last_UserId_Log
Script 2 - Add Foreign Key FK_DATA_Magiclink_Last_WorkstationId_Log

Script 3 -  Add new table DATA_MagicLink2Ticket
Script 4 -  Add Foregn Key FK_DATA_MagicLink2Ticket_MagicLinkId
Script 5 -  Add Foregn Key FK_DATA_MagicLink2Ticket_TicketId
Script 6 - Add Foregn Key FK_DATA_Magiclink2Ticket_Last_UserId_Log
Script 7 - Add Foregn Key FK_DATA_Magiclink2Ticket_Last_WorkstationId_Log

Script 8 - Add new table  DATA_MagicLink2Ticket2Phone
Script 9 - Add Foregn Key FK_DATA_MagicLink2Ticket2Phone_MagicLinkToTicketId
Script 10 -  Add Foregn Key FK_DATA_MagicLink2Ticket2Phone_AccountId
Script 11 -  Add Foregn Key FK_DATA_Magiclink2Ticket2Phone_Last_UserId_Log
Script 12 - Add Foregn Key FK_DATA_Magiclink2Ticket2Phone_Last_WorkstationId_Log</REASON><TABLENAMES>DATA_Magiclink=MagicLinkId
DATA_MagicLink2Ticket=MagicLinkToTicketId
DATA_MagicLink2Ticket2Phone=MagicLinkToTicketToPhoneId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT NULL
                 FROM INFORMATION_SCHEMA.TABLES
                WHERE TABLE_SCHEMA = 'dbo'
                  AND TABLE_NAME = 'DATA_Magiclink')
BEGIN
  CREATE TABLE DATA_Magiclink(
		[MagicLinkId] [int] IDENTITY(1,1) NOT NULL,
		[MagicLink] [nvarchar](500) NOT NULL,
		[CreationDateTime] [datetime] NOT NULL,
		[ValidityHours] [int] NULL,
		[RequestAccountAK] [nvarchar](50) NULL,
		[EmailAddress] [nvarchar](500) NULL,
		[AssociationType] [nvarchar](1) NULL,
		[GeneratedBy] [nvarchar](1) NULL,
		[Status] [nvarchar](1) NULL,
    	        [Last_UserId_Log] [int] NULL,
	        [Last_WorkstationId_Log] [int] NULL,
	        [Last_DateTime_Log] [datetime] NULL,
		Primary Key ([MagicLinkId])
	)
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_DATA_Magiclink_Last_UserId_Log')
BEGIN
   ALTER TABLE [DATA_Magiclink]  
   ADD CONSTRAINT FK_DATA_Magiclink_Last_UserId_Log FOREIGN KEY([Last_UserId_Log])
   REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_DATA_Magiclink_Last_WorkstationId_Log')
BEGIN
   ALTER TABLE [DATA_Magiclink]  
   ADD CONSTRAINT [FK_DATA_Magiclink_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log])
   REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT NULL
                 FROM INFORMATION_SCHEMA.TABLES
                WHERE TABLE_SCHEMA = 'dbo'
                  AND TABLE_NAME = 'DATA_MagicLink2Ticket')
BEGIN
  CREATE TABLE DATA_MagicLink2Ticket(
		[MagicLinkToTicketId] [int] IDENTITY(1,1) NOT NULL,
		[MagicLinkId] [int] NOT NULL,
		[TicketId] [int] NOT NULL,
		[Status] [nvarchar](1) NULL,
    	        [Last_UserId_Log] [int] NULL,
	        [Last_WorkstationId_Log] [int] NULL,
	        [Last_DateTime_Log] [datetime] NULL,
		Primary Key ([MagicLinkToTicketId])
	)
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_DATA_MagicLink2Ticket_MagicLinkId')
BEGIN
   ALTER TABLE [DATA_MagicLink2Ticket]  
   ADD CONSTRAINT FK_DATA_MagicLink2Ticket_MagicLinkId FOREIGN KEY([MagicLinkId])
   REFERENCES [DATA_Magiclink] ([MagicLinkId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_DATA_MagicLink2Ticket_TicketId')
BEGIN
   ALTER TABLE [DATA_MagicLink2Ticket]  
   ADD CONSTRAINT FK_DATA_MagicLink2Ticket_TicketId FOREIGN KEY([TicketId])
   REFERENCES [DATA_Ticket] ([TicketId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_DATA_Magiclink2Ticket_Last_UserId_Log')
BEGIN
   ALTER TABLE [DATA_Magiclink2Ticket]  
   ADD CONSTRAINT FK_DATA_Magiclink2Ticket_Last_UserId_Log FOREIGN KEY([Last_UserId_Log])
   REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_DATA_Magiclink2Ticket_Last_WorkstationId_Log')
BEGIN
   ALTER TABLE [DATA_Magiclink2Ticket]  
   ADD CONSTRAINT [FK_DATA_Magiclink2Ticket_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log])
   REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT NULL
                 FROM INFORMATION_SCHEMA.TABLES
                WHERE TABLE_SCHEMA = 'dbo'
                  AND TABLE_NAME = 'DATA_MagicLink2Ticket2Phone')
BEGIN
  CREATE TABLE DATA_MagicLink2Ticket2Phone(
		[MagicLinkToTicketToPhoneId] [int] IDENTITY(1,1) NOT NULL,
		[MagicLinkToTicketId] [int] NOT NULL,
		[PhoneId] [nvarchar](50) NOT NULL,
		[PhoneNameOwner] [nvarchar](500) NULL,
		[PhoneSurnameOwner] [nvarchar](500) NULL,
		[PhoneEmailOwner] [nvarchar](500) NULL, 
		[PhoneMyPassIdOwner] [nvarchar](500) NULL,
		[AccountId] [int] NULL,
    	        [Last_UserId_Log] [int] NULL,
                [Last_WorkstationId_Log] [int] NULL,
	        [Last_DateTime_Log] [datetime] NULL,
		Primary Key ([MagicLinkToTicketToPhoneId])
	)
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_DATA_MagicLink2Ticket2Phone_MagicLinkToTicketId')
BEGIN
   ALTER TABLE [DATA_MagicLink2Ticket2Phone]  
   ADD CONSTRAINT FK_DATA_MagicLink2Ticket2Phone_MagicLinkToTicketId FOREIGN KEY([MagicLinkToTicketId])
   REFERENCES [DATA_Magiclink2Ticket] ([MagicLinkToTicketId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_DATA_MagicLink2Ticket2Phone_AccountId')
BEGIN
   ALTER TABLE [DATA_MagicLink2Ticket2Phone]  
   ADD CONSTRAINT FK_DATA_MagicLink2Ticket2Phone_AccountId FOREIGN KEY([AccountId])
   REFERENCES [DATA_Account] ([AccountId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_DATA_Magiclink2Ticket2Phone_Last_UserId_Log')
BEGIN
   ALTER TABLE [DATA_Magiclink2Ticket2Phone]  
   ADD CONSTRAINT FK_DATA_Magiclink2Ticket2Phone_Last_UserId_Log FOREIGN KEY([Last_UserId_Log])
   REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_DATA_Magiclink2Ticket2Phone_Last_WorkstationId_Log')
BEGIN
   ALTER TABLE [DATA_Magiclink2Ticket2Phone]  
   ADD CONSTRAINT [FK_DATA_Magiclink2Ticket2Phone_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log])
   REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>scoluccia</ADDEDBY><SQLVERSION>3709</SQLVERSION><RMTRACKLINK>IDBOS-10328</RMTRACKLINK><REASON>Added two tables for managing the Dynamic Rules received from th eengine</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT NULL
                 FROM INFORMATION_SCHEMA.TABLES
                WHERE TABLE_SCHEMA = 'dbo'
                  AND TABLE_NAME = 'DP_Rules')
BEGIN
  CREATE TABLE DP_Rules(
		[DPRuleId] [int] IDENTITY(1,1) NOT NULL,
		[FiredRuleId] [int] NOT NULL,
		[FiredDateTime] [datetime] NULL,
    	[Last_UserId_Log] [int] NULL,
	    [Last_WorkstationId_Log] [int] NULL,
	    [Last_DateTime_Log] [datetime] NULL,
		Primary Key ([DPRuleId])
	)
END;

IF NOT EXISTS (SELECT NULL
                 FROM INFORMATION_SCHEMA.TABLES
                WHERE TABLE_SCHEMA = 'dbo'
                  AND TABLE_NAME = 'DP_RulesDetail')
BEGIN
  CREATE TABLE DP_RulesDetail(
		[DPRuleDetailId] [int] IDENTITY(1,1) NOT NULL,
		[DPRuleId] [int] NOT NULL,
        [PriceListID] [nvarchar](50) NOT NULL,
        [EventID] [nvarchar](50) NOT NULL,
        [PriceTableID] [nvarchar](50) NOT NULL,
        [SectorId] [nvarchar](50) NOT NULL,
        [PerformanceID] [nvarchar](50) NOT NULL,
	    [MaxPercHike] [float] NULL,
        [MaxFixedHike] [float] NULL,
     	[Last_UserId_Log] [int] NULL,
	    [Last_WorkstationId_Log] [int] NULL,
	    [Last_DateTime_Log] [datetime] NULL,
		Primary Key ([DPRuleDetailId])
	)

  ALTER TABLE [dbo].DP_RulesDetail  WITH CHECK ADD FOREIGN KEY([DPRuleId])
  REFERENCES [dbo].DP_Rules ([DPRuleId])

END;

</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>pdalben</ADDEDBY><SQLVERSION>3708</SQLVERSION><RMTRACKLINK>IDBOS-8599</RMTRACKLINK><REASON>Changed name of biometric drivers</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>update CNF_Device set CNF_Device.Description = 'Lumidigm Biometric VCOM' 
  from CNF_Device inner join CNF_Driver on CNF_Device.DriverId = CNF_Driver.DriverId
  where CNF_Driver.DriverAk = 'TVenusVCom';

update CNF_Device set CNF_Device.Description = 'Lumidigm Biometric' 
  from CNF_Device inner join CNF_Driver on CNF_Device.DriverId = CNF_Driver.DriverId
  where CNF_Driver.DriverAk = 'TLumiBiometric';

update CNF_Device set CNF_Device.Description = 'Lumidigm Biometric 10x' 
  from CNF_Device inner join CNF_Driver on CNF_Device.DriverId = CNF_Driver.DriverId
  where CNF_Driver.DriverAk = 'TLumiBiometric10x';

update CNF_Driver set Description = 'Lumidigm Biometric 10x'  where DriverAk = 'TLumiBiometric10x';
update CNF_Driver set Description = 'Lumidigm Biometric'      where DriverAk = 'TLumiBiometric';
update CNF_Driver set Description = 'Lumidigm Biometric VCOM' where DriverAk = 'TVenusVCom';</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>scoluccia</ADDEDBY><SQLVERSION>3707</SQLVERSION><RMTRACKLINK>10544</RMTRACKLINK><REASON>Improved the Split SQL function</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT *
           FROM   sys.objects
           WHERE  object_id = OBJECT_ID(N'[dbo].[Split]')
                  AND type IN ( N'FN', N'IF', N'TF', N'FS', N'FT' ))
  DROP FUNCTION [dbo].[Split]
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>CREATE FUNCTION [dbo].[Split]
(
 @String varchar(max)
,@Delimiter char
)
RETURNS @Results table
(
 Ordinal int
,value varchar(max)
)
as
begin

 declare @CompLevel int 
    select @CompLevel = compatibility_level from sys.databases where name = db_name() 
 if @complevel &lt; 130
 begin 
  DECLARE @ll INT = LEN(@String) + 1, @ld INT = LEN(@Delimiter);

  WITH a AS
    (SELECT
         ordinal =1,
         ini = 1,
         fin = COALESCE(NULLIF(CHARINDEX(@Delimiter,  @String, 1), 0), @ll),
         val = SUBSTRING(@String, 1, COALESCE(NULLIF(CHARINDEX(@Delimiter, @String, 1), 0), @ll) - 1)
     UNION ALL
     SELECT
         ordinal +1 ,
         ini = CONVERT(INT, fin) + @ld,
         fin = COALESCE(NULLIF(CHARINDEX(@Delimiter, @String, fin + @ld), 0), @ll),
         val = SUBSTRING(@String, fin + @ld, COALESCE(NULLIF(CHARINDEX(@Delimiter,@String, fin + @ld), 0), @ll)-fin-@ld)
     FROM a
     WHERE fin &lt; @ll ) 
   INSERT  @Results 
   SELECT ordinal, val FROM a WHERE LEN(val) &gt; 0
  OPTION (MAXRECURSION 0);
    end
 else
    insert into @Results     SELECT ROW_NUMBER() OVER (ORDER BY (SELECT 1)),  value   FROM STRING_SPLIT(@String,@Delimiter)

return 
end
</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>3706</SQLVERSION><RMTRACKLINK>IDBOS-4105</RMTRACKLINK><REASON></REASON><TABLENAMES>DATA_InvoiceData=InvoiceDataId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'ErrorMessage'
                      AND OBJECT_ID = OBJECT_ID(N'DATA_InvoiceData'))
BEGIN
  ALTER TABLE DATA_InvoiceData
  ADD ErrorMessage NVarChar(2000) NULL;
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>ecandido</ADDEDBY><SQLVERSION>3705</SQLVERSION><RMTRACKLINK>	IDBOS-10448</RMTRACKLINK><REASON>Add Field "AdvancedPaymentAmount" into DATA_Payment Table used with Advanced Payment Method</REASON><TABLENAMES>DATA_Payment=PaymentId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
               WHERE Name = N'AdvancedPaymentAmount' AND
               OBJECT_ID = OBJECT_ID(N'DATA_Payment'))
BEGIN
  ALTER TABLE DATA_Payment
  ADD AdvancedPaymentAmount Float NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>BEGIN
  DECLARE @AdvPaymentId INT

  SELECT @AdvPaymentId = PaymentMethodId FROM CNF_PaymentMethod WHERE PaymentMethodAk = 'ADVPAY'

  UPDATE
    DATA_Payment
  SET
    AdvancedPaymentAmount = PaymentAmount,
	PaymentAmount = 0,
	CurrencyAmount = 0
  WHERE
    PaymentMethodId = @AdvPaymentId
END
</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3704</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.37.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3703</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.37.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3702</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.37.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3701</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.37.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3700</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.37.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3699</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.37.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3698</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.37.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3697</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.37.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3696</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3695</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3694</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3693</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3692</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3691</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3690</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3689</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3688</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3687</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3686</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3685</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3684</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3683</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3682</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3681</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3680</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3679</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3678</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3677</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3676</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3675</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3674</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3673</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3672</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3671</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3670</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3669</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3668</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.37.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3667</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3666</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.37.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3665</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3664</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3663</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3662</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3661</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3660</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3659</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3658</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3657</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3656</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3655</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3654</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3653</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3652</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3651</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3650</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3649</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3648</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3647</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3646</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3645</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3644</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3643</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3642</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3641</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3640</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3639</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3638</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3637</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3636</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3635</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3634</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3633</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3632</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3631</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3630</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3629</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3628</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3627</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3626</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3625</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3624</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3623</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3622</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3621</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3620</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3619</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3618</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3617</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3616</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3615</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3614</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3613</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3612</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3611</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3610</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.37.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3609</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.37.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3608</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.37.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3607</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.37.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3606</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.37.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3605</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.37.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3604</SQLVERSION><RMTRACKLINK>IDBOS-10123</RMTRACKLINK><REASON>Script 0 - Add new table CNF_Authorization
Script 1 - Add Foregn Key FK_CNF_Authorization_UserId
Script 2 - Add Foreign Key FK_CNF_Authorization_Last_UserId_Log
Script 3 - Add Foreign Key FK_CNF_Authorization_WorkstationId
Script 4 - Add Foreing Key FK_CNF_Authorization_Last_WorkstationId_Log
</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                WHERE TABLE_SCHEMA = 'dbo' 
                  AND TABLE_NAME = 'CNF_Authorization')
BEGIN
CREATE TABLE CNF_Authorization(
	[AuthorizationId] integer IDENTITY(1,1) NOT NULL,
	[ClientId] nvarchar(200) NOT NULL,
        [ClientSecret] nvarchar(max) NOT NULL,
	[UserId] integer NOT NULL,
	[WorkstationId] integer NOT NULL,
	[Last_UserId_Log] integer NULL,
	[Last_WorkstationId_Log] integer NULL,
	[Last_DateTime_Log] datetime NULL,
Primary Key ([AuthorizationId])
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_CNF_Authorization_UserId')
BEGIN
   ALTER TABLE [CNF_Authorization]  
   ADD CONSTRAINT FK_CNF_Authorization_UserId FOREIGN KEY([UserId])
   REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_CNF_Authorization_Last_UserId_Log')
BEGIN
   ALTER TABLE [CNF_Authorization]  
   ADD CONSTRAINT FK_CNF_Authorization_Last_UserId_Log FOREIGN KEY([Last_UserId_Log])
   REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_CNF_Authorization_WorkstationId')
BEGIN
   ALTER TABLE [CNF_Authorization]  
   ADD CONSTRAINT [FK_CNF_Authorization_WorkstationId] FOREIGN KEY([WorkstationId])
   REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_CNF_Authorization_Last_WorkstationId_Log')
BEGIN
   ALTER TABLE [CNF_Authorization]  
   ADD CONSTRAINT [FK_CNF_Authorization_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log])
   REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3603</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.35.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3602</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.35.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3601</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.35.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3600</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.35.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3599</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.35.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3598</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.35.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3597</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.35.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3596</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.35.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3595</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.35.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3594</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.35.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3593</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.35.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3592</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3591</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3590</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3589</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3588</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3587</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3586</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3585</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3584</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3583</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3582</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3581</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3580</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3579</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3578</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3577</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3576</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3575</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3574</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3573</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3572</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3571</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3570</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3569</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3568</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3567</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3566</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3565</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3564</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3563</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3562</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3561</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3560</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3559</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3558</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3557</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3556</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3555</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3554</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3553</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3552</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3551</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3550</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3549</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3548</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3547</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3546</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3545</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3544</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3543</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3542</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3541</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3540</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3539</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3538</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3537</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3536</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3535</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3534</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3533</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3532</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3531</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3530</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3529</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3528</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3527</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3526</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3525</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3524</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3523</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3522</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3521</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3520</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3519</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3518</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3517</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3516</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3515</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3514</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3513</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.35.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3512</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.35.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3511</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.35.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3510</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.35.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3509</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.35.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3508</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.35.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3507</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.35.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3506</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.35.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3505</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.35.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3504</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.35.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3503</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.35.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>3502</SQLVERSION><RMTRACKLINK>IDBOS-9140</RMTRACKLINK><REASON>Added ParentSeatId column to CNF_Seat</REASON><TABLENAMES>CNF_Seat=SeatId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
               WHERE Name = N'ParentSeatId' AND
               OBJECT_ID = OBJECT_ID(N'CNF_Seat'))
BEGIN
  ALTER TABLE CNF_Seat
  ADD ParentSeatId Int NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>ecandido</ADDEDBY><SQLVERSION>3501</SQLVERSION><RMTRACKLINK>IDBOS-4675</RMTRACKLINK><REASON>Change Column MoneyParcPIN int NVARCHAR</REASON><TABLENAMES>DATA_Ticket=TicketId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>DECLARE @tablename sysname = 'DATA_Ticket'
DECLARE @colwithdefault sysname  = 'MoneyCardPIN'
 
DECLARE @name_column_id AS INT
DECLARE @sql nvarchar(255)
 
SELECT @name_column_id = column_id
FROM sys.columns
WHERE object_id = OBJECT_ID(@tablename)
AND name = @colwithdefault
 
-- Remove default constraint from name column
SELECT @sql = 'ALTER TABLE ' + @tablename + '  DROP CONSTRAINT ' + D.name
FROM sys.default_constraints AS D
WHERE D.parent_object_id = OBJECT_ID(@tablename)
AND D.parent_column_id = @name_column_id
 
EXECUTE sp_executesql @sql
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>ALTER TABLE DATA_Ticket
ALTER COLUMN MoneyCardPIN NVarChar(10)</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>ecandido</ADDEDBY><SQLVERSION>3500</SQLVERSION><RMTRACKLINK>IDBOS-4675</RMTRACKLINK><REASON>Storage Generated PIN for Money Card</REASON><TABLENAMES>DATA_Ticket=TicketId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'MoneyCardPIN' AND
                Object_ID  = Object_ID(N'DATA_Ticket'))
BEGIN
  ALTER TABLE DATA_Ticket
  ADD MoneyCardPIN Integer Default 0
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>scoluccia</ADDEDBY><SQLVERSION>3499</SQLVERSION><RMTRACKLINK>IDBOS-8905</RMTRACKLINK><REASON>Script 0 - Add new table DATA_TicketOptions
Script 1 - Add Foregn key FK_DATA_TicketOptions_TicketId
Script 2 - Add Foregn key FK_DATA_TicketOptions_Last_UserId_Log
Script 3 - Add Foregn key FK_DATA_TicketOptions_WorkstationId
</REASON><TABLENAMES>DATA_TicketOptions=TicketOptionsId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                WHERE TABLE_SCHEMA = 'dbo' 
                  AND TABLE_NAME = 'DATA_TicketOptions')
BEGIN
CREATE TABLE DATA_TicketOptions(
	[TicketOptionsId] integer IDENTITY(1,1) NOT NULL,
	[TicketId] integer NOT NULL,
	[OptionType] Integer NOT NULL,
	[OptionValue] nvarchar(200) NOT NULL,
	[Last_UserId_Log] integer NULL,
	[Last_WorkstationId_Log] integer NULL,
	[Last_DateTime_Log] datetime NULL,
Primary Key ([TicketOptionsId])
) 
END	</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_DATA_TicketOptions_TicketId')
BEGIN
   ALTER TABLE [DATA_TicketOptions]  
   ADD CONSTRAINT FK_DATA_TicketOptions_TicketId FOREIGN KEY([TicketId])
   REFERENCES [DATA_Ticket] ([TicketId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_DATA_TicketOptions_Last_UserId_Log')
BEGIN
   ALTER TABLE [DATA_TicketOptions]  
   ADD CONSTRAINT FK_DATA_TicketOptions_Last_UserId_Log FOREIGN KEY([Last_UserId_Log])
   REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_DATA_TicketOptions_WorkstationId')
BEGIN
   ALTER TABLE [DATA_TicketOptions]  
   ADD CONSTRAINT [FK_DATA_TicketOptions_WorkstationId] FOREIGN KEY([Last_WorkstationId_Log])
   REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>ecandido</ADDEDBY><SQLVERSION>3498</SQLVERSION><RMTRACKLINK>IDBOS-7919</RMTRACKLINK><REASON>Add Field CounterType into the table DATA_AptRotationCount to check if the rotations are made in Online or Offline</REASON><TABLENAMES>DATA_AptRotationCount=AptRotationCountId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'CounterType' AND
                Object_ID  = Object_ID(N'DATA_AptRotationCount'))
BEGIN
  ALTER TABLE DATA_AptRotationCount
  ADD CounterType SmallInt Default 0 NOT NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>sloporto</ADDEDBY><SQLVERSION>3497</SQLVERSION><RMTRACKLINK>IDBOS-9013</RMTRACKLINK><REASON>0 - Change column name for AssociationType</REASON><TABLENAMES>DATA_Ticket2Phone=TicketToPhoneId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
               WHERE Name = N'AccessConfigurationId' AND
               Object_ID  = Object_ID(N'DATA_Ticket2Phone'))
BEGIN
  EXEC sp_RENAME 'DATA_Ticket2Phone.AccessConfigurationId', 'AssociationType', 'COLUMN'
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>nchinea</ADDEDBY><SQLVERSION>3496</SQLVERSION><RMTRACKLINK>8574</RMTRACKLINK><REASON>Script 0 - Add DmgCategoryId  &amp; AccountId
Script 1 - Add Foregn key DmgCategoryId  
Script 2 - Add Foregn key AccountId
Script 3 - Add trigger for cache 
Script 4 - Add  record for cache
</REASON><TABLENAMES>CNF_Trigger_Permission=TriggerPermissionId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'DmgCategoryId' AND
                Object_ID  = Object_ID(N'CNF_Trigger_Permission'))
BEGIN
  Alter Table CNF_Trigger_Permission
  Add DmgCategoryId Integer NULL,
	  AccountId Integer NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Trigger_Permission_DmgCategoryId')
BEGIN
  ALTER TABLE CNF_Trigger_Permission
  ADD CONSTRAINT [FK_CNF_Trigger_Permission_DmgCategoryId] FOREIGN KEY([DmgCategoryId]) 
  REFERENCES [CNF_DmgCategory] ([DmgCategoryId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Trigger_Permission_AccountId')
BEGIN
  ALTER TABLE CNF_Trigger_Permission 
  ADD CONSTRAINT [FK_CNF_Trigger_Permission_AccountId] FOREIGN KEY([AccountId]) 
  REFERENCES [DATA_Account] ([AccountId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>Declare @TABLE VarChar(200)     
Set @TABLE = 'CNF_Trigger_Permission'
EXEC('IF OBJECT_ID ('''+@TABLE+'_Cache'', ''TR'') IS NOT NULL DROP TRIGGER '+@TABLE+'_Cache')
EXEC('CREATE TRIGGER [dbo].['+@TABLE+'_Cache] on [dbo].['+@TABLE+'] AFTER INSERT,DELETE,UPDATE 
      AS 
	  BEGIN  
	    Declare @Sql nvarchar(max);	
		SET NOCOUNT ON;	
		set @Sql = '''+@TABLE+''';
		EXEC otn_sp_CACHE_TABLE_update @Sql
	  END')</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>insert into SYS_CacheTable (TableName, IRN, FunctionCall) VALUES ('CNF_Trigger_Permission',1,'CheckTriggerPermission')	  </SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>sloporto</ADDEDBY><SQLVERSION>3495</SQLVERSION><RMTRACKLINK>IDBOS-9013</RMTRACKLINK><REASON>Script 0 - Add new table DATA_Ticket2Phone
Script 1 - Add Foregn key FK_DATA_Ticket2Phone_TicketId
Script 2 - Add Foregn key FK_DATA_Ticket2Phone_AccountId
Script 3 - Add Foregn key FK_DATA_Ticket2Phone_Last_UserId_Log
Script 4 - Add Foregn key FK_DATA_Ticket2Phone_WorkstationId</REASON><TABLENAMES>DATA_Ticket2Phone=TicketToPhoneId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                WHERE TABLE_SCHEMA = 'dbo' 
                  AND TABLE_NAME = 'DATA_Ticket2Phone')
BEGIN
CREATE TABLE DATA_Ticket2Phone(
	[TicketToPhoneId] integer IDENTITY(1,1) NOT NULL,
	[TicketId] integer NOT NULL,
	[PhoneId] nvarchar(50) NULL,
	[AccessConfigurationId] Integer NULL,
	[PhoneNameOwner] nvarchar(500),
        [PhoneSurnameOwner] nvarchar(500),
        [PhoneEmailOwner]  nvarchar(500),
        [PhoneMyPassIdOwner]  nvarchar(500),
	[AccountId] integer NULL,
	[Last_UserId_Log] integer NULL,
	[Last_WorkstationId_Log] integer NULL,
	[Last_DateTime_Log] datetime NULL,
Primary Key ([TicketToPhoneId])
) 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_DATA_Ticket2Phone_TicketId')
BEGIN
   ALTER TABLE [DATA_Ticket2Phone]  
   ADD CONSTRAINT [FK_DATA_Ticket2Phone_TicketId] FOREIGN KEY([TicketId])
   REFERENCES [DATA_Ticket] ([TicketId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_DATA_Ticket2Phone_AccountId')
BEGIN
   ALTER TABLE [DATA_Ticket2Phone]  
   ADD CONSTRAINT [FK_DATA_Ticket2Phone_AccountId] FOREIGN KEY([AccountId])
   REFERENCES [DATA_Account] ([AccountId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_DATA_Ticket2Phone_Last_UserId_Log')
BEGIN
   ALTER TABLE [DATA_Ticket2Phone]  
   ADD CONSTRAINT [FK_DATA_Ticket2Phone_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log])
   REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_DATA_Ticket2Phone_WorkstationId')
BEGIN
   ALTER TABLE [DATA_Ticket2Phone]  
   ADD CONSTRAINT [FK_DATA_Ticket2Phone_WorkstationId] FOREIGN KEY([Last_WorkstationId_Log])
   REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>scoluccia</ADDEDBY><SQLVERSION>3494</SQLVERSION><RMTRACKLINK>9333</RMTRACKLINK><REASON>
- Modified CNF_PROMOTION
  added field NotCombinableWithDynamicOffer</REASON><TABLENAMES>CNF_Promotion=PromotionId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'NotCombinableWithDynamicOffer' AND
                Object_ID  = Object_ID(N'CNF_Promotion'))
BEGIN
  ALTER TABLE CNF_Promotion
  ADD NotCombinableWithDynamicOffer smallint DEFAULT 0 NOT NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>pdalben</ADDEDBY><SQLVERSION>3493</SQLVERSION><RMTRACKLINK>IDBOS-8337</RMTRACKLINK><REASON>Add fields ApprovalStatus, RequestId and RequestDateTime to STOCK_Movement</REASON><TABLENAMES>STOCK_Movement=MovementId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
               WHERE Name = N'ApprovalStatus' AND
               Object_ID  = Object_ID(N'STOCK_Movement'))
BEGIN
  ALTER TABLE STOCK_Movement
  ADD ApprovalStatus smallint DEFAULT 1 NOT NULL
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
               WHERE Name = N'RequestId' AND
               Object_ID  = Object_ID(N'STOCK_Movement'))
BEGIN
  ALTER TABLE STOCK_Movement
  ADD RequestId nvarchar(32) NULL
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
               WHERE Name = N'RequestDateTime' AND
               Object_ID  = Object_ID(N'STOCK_Movement'))
BEGIN
  ALTER TABLE STOCK_Movement
  ADD RequestDateTime datetime NULL
END
</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3492</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.33.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3491</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.33.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3490</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.33.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3489</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.33.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3488</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.33.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3487</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.33.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3486</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3485</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3484</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3483</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3482</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3481</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3480</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3479</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3478</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3477</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3476</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3475</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3474</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3473</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3472</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3471</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3470</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3469</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3468</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3467</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3466</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3465</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3464</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3463</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3462</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3461</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3460</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3459</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3458</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3457</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3456</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3455</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3454</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3453</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3452</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3451</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3450</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3449</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3448</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3447</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3446</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3445</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3444</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3443</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3442</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3441</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3440</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3439</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3438</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3437</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3436</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3435</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3434</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3433</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3432</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3431</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3430</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3429</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3428</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3427</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3426</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3425</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3424</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3423</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3422</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3421</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3420</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3419</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3418</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3417</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3416</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3415</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3414</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3413</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3412</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3411</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3410</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3409</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3408</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3407</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3406</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3405</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3404</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3403</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3402</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3401</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3400</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3399</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3398</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3397</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3396</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.33.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3395</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.33.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3394</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.33.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bos-compiler</ADDEDBY><SQLVERSION>3393</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.33.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>3392</SQLVERSION><RMTRACKLINK>IDBOS-9335</RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                FROM sys.indexes 
            WHERE name='IDX_rr_data_revenue_fcalcdate_usageID' AND object_id = OBJECT_ID('RR_DATA_Revenue')
			)
BEGIN
	CREATE NONCLUSTERED INDEX [IDX_rr_data_revenue_fcalcdate_usageID]
	ON [dbo].[RR_DATA_Revenue] ([FCalcDate],[UsageId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                FROM sys.indexes 
            WHERE name='IDX_RR_DATA_Revenue_AccountID_TransactionID_Date' AND object_id = OBJECT_ID('RR_DATA_Revenue')
			)
BEGIN
	CREATE NONCLUSTERED INDEX [IDX_RR_DATA_Revenue_AccountID_TransactionID_Date]
	ON [dbo].[RR_DATA_Revenue] ([COAAccountId],[TransactionId],[FCalcDate])
	INCLUDE ([SaleId],[SaleItemId],[MatrixCellId],[TicketId],[SiteId],[OperatingAreaId],[WorkstationId],[UserGroupId],[UserId],[Quantity],[UnitAmount],[GrossAmount],[NetAmount],[RevenueAmount],[RRDays],[MatrixSheetId],[AttributeIDs])
END </SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                FROM sys.indexes 
            WHERE name='IDX_RR_Data_Revenue_Trigger_Type' AND object_id = OBJECT_ID('RR_DATA_Revenue')
			)
BEGIN
	CREATE NONCLUSTERED INDEX [IDX_RR_Data_Revenue_Trigger_Type]
	ON [dbo].[RR_DATA_Revenue] ([RRCalcTypeTrigger],[AccountingType])
	INCLUDE ([COAAccountId],[SaleItemId],[TicketId],[NetAmount],[RevenueAmount])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                FROM sys.indexes 
            WHERE name='IDX_DATA_TicketUsage_UsageType_Date_Validate' AND object_id = OBJECT_ID('DATA_TicketUsage')
			)
BEGIN
	CREATE NONCLUSTERED INDEX [IDX_DATA_TicketUsage_UsageType_Date_Validate]
	ON [dbo].[DATA_TicketUsage] ([UsageType],[FUsageDate],[ValidateResult])
	INCLUDE ([TicketId],[GateId],[UsageDate])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                FROM sys.indexes 
            WHERE name='IDX_RR_DATA_Revenue_AccountID_Fcalcdate' AND object_id = OBJECT_ID('RR_DATA_Revenue')
			)
BEGIN
	CREATE NONCLUSTERED INDEX [IDX_RR_DATA_Revenue_AccountID_Fcalcdate]
	ON [dbo].[RR_DATA_Revenue] ([COAAccountId],[FCalcDate])
	INCLUDE ([RevenueRecognitionRuleId],[RRCalcTypeWhere],[RRCalcTypeMethod],[COAAccountConfigId],[COAAccountType],[TransactionId],[SaleId],[RRCalcTypeTrigger],[RRPercentage],[RRDays])
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>3391</SQLVERSION><RMTRACKLINK>IDBOS-8452</RMTRACKLINK><REASON>Addiing Indexes to help with the run of COA.</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                FROM sys.indexes 
            WHERE name='IDX_RR_DATA_Revenue_COAAccountid_RuleID' AND object_id = OBJECT_ID('RR_DATA_Revenue')
			)
BEGIN
			CREATE NONCLUSTERED INDEX [IDX_RR_DATA_Revenue_COAAccountid_RuleID]
			ON [dbo].[RR_DATA_Revenue] ([COAAccountId],[RevenueRecognitionRuleId])
			INCLUDE ([COAAccountType],[SaleItemId],[MatrixCellId],[TicketId],[GrossAmount],[NetAmount],[RevenueAmount],[AccountingType])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                FROM sys.indexes 
            WHERE name='IDX_DATA_SaleItem_ItemTicketId' AND object_id = OBJECT_ID('DATA_SaleItem')
			)
BEGIN
	CREATE NONCLUSTERED INDEX [IDX_DATA_SaleItem_ItemTicketId]
	ON [dbo].[DATA_SaleItem] ([ItemTicketId])
	INCLUDE ([SaleId],[Position],[TotalAmount])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                FROM sys.indexes 
            WHERE name='IDX_DATA_SaleItem_TicketId_Includes' AND object_id = OBJECT_ID('DATA_SaleItem')
			)
BEGIN
	CREATE NONCLUSTERED INDEX [IDX_DATA_SaleItem_TicketId_Includes]
	ON [dbo].[DATA_SaleItem] ([TicketId])
	INCLUDE ([SaleId],[Position],[TotalAmount])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                FROM sys.indexes 
            WHERE name='IDX_DATA_Ticket_PrintDateTime' AND object_id = OBJECT_ID('DATA_Ticket')
			)
BEGIN
	CREATE NONCLUSTERED INDEX [IDX_DATA_Ticket_PrintDateTime]
	ON [dbo].[DATA_Ticket] ([PrintDateTime])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                FROM sys.indexes 
            WHERE name='IDX_RR_DATA_Revenue_coaaccountid_Fcalcdate' AND object_id = OBJECT_ID('RR_DATA_Revenue')
			)
BEGIN
	CREATE NONCLUSTERED INDEX [IDX_RR_DATA_Revenue_coaaccountid_Fcalcdate]
	ON [dbo].[RR_DATA_Revenue] ([COAAccountId],[FCalcDate])
	INCLUDE ([TransactionId],[SaleId],[SiteId],[OperatingAreaId],[WorkstationId],[UserGroupId],[UserId],[RevenueAmount],[AccountingType],[SaleItemRuleID])

END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                FROM sys.indexes 
            WHERE name='IDX_RR_DATA_Revenue_coaaccountid_Fcalcdate_Includes' AND object_id = OBJECT_ID('RR_DATA_Revenue')
			)
BEGIN
	CREATE NONCLUSTERED INDEX [IDX_RR_DATA_Revenue_coaaccountid_Fcalcdate_Includes]
	ON [dbo].[RR_DATA_Revenue] ([COAAccountId],[FCalcDate])
	INCLUDE ([RevenueRecognitionRuleId],[RRCalcTypeWhere],[RRCalcTypeMethod],[COAAccountConfigId],[TransactionId],[RevenueAmount],[RRCalcTypeTrigger],[RRPercentage],[RRDays],[AccountingType])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                FROM sys.indexes 
            WHERE name='IDX_RR_DATA_Revenue_coaaccountid_Fcalcdate_AllIncludes' AND object_id = OBJECT_ID('RR_DATA_Revenue')
			)           
BEGIN
select 'HERE'
	CREATE NONCLUSTERED INDEX [IDX_RR_DATA_Revenue_coaaccountid_Fcalcdate_AllIncludes]
	ON [dbo].[RR_DATA_Revenue] ([COAAccountId],[FCalcDate])
	INCLUDE ([RevenueRecognitionRuleId],[RRCalcTypeWhere],[RRCalcTypeMethod],[COAAccountConfigId],[TransactionId],[SaleId],[SaleItemId],[RevenueAmount],[RRCalcTypeTrigger],[RRPercentage],[RRDays],[AccountingType],[SaleItemTaxId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                FROM sys.indexes 
            WHERE name='IDX_RR_DATA_Revenue_Account_Date_Amount' AND object_id = OBJECT_ID('RR_DATA_Revenue')
			)
BEGIN
	CREATE NONCLUSTERED INDEX [IDX_RR_DATA_Revenue_Account_Date_Amount]
	ON [dbo].[RR_DATA_Revenue] ([COAAccountId],[FCalcDate],[RevenueAmount])
	INCLUDE ([RRCalcTypeWhere],[RRCalcTypeMethod],[COAAccountConfigId],[TransactionId],[SaleId],[SaleItemId],[MatrixCellId],[TicketId],[SiteId],[OperatingAreaId],[WorkstationId],[UserGroupId],[UserId],[RRCalcTypeTrigger],[RRPercentage],[RRDays],[MatrixSheetId],[AttributeIDs],[SaleItemTaxId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                FROM sys.indexes 
            WHERE name= 'IDX_rr_data_revenue_ticketid' AND object_id = OBJECT_ID('RR_DATA_Revenue')
			)
BEGIN
	CREATE NONCLUSTERED INDEX [IDX_rr_data_revenue_ticketid] ON [dbo].[RR_DATA_Revenue]
	(
		[TicketId] ASC
	)WITH (STATISTICS_NORECOMPUTE = OFF, DROP_EXISTING = OFF, ONLINE = OFF) ON [PRIMARY]
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                FROM sys.indexes 
            WHERE name= 'IDX_RR_data_revenue_ticketID_TID' AND object_id = OBJECT_ID('RR_DATA_Revenue')
			)
BEGIN
	CREATE NONCLUSTERED INDEX [IDX_RR_data_revenue_ticketID_TID] ON [dbo].[RR_DATA_Revenue]
	(
		[TicketId] ASC
	)
	INCLUDE([TransactionId]) WITH (STATISTICS_NORECOMPUTE = OFF, DROP_EXISTING = OFF, ONLINE = OFF) ON [PRIMARY]
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                FROM sys.indexes 
            WHERE name= 'IDX_RR_Data_revenue_SI_TI_DATE' AND object_id = OBJECT_ID('RR_DATA_Revenue')
			)
BEGIN
	CREATE NONCLUSTERED INDEX [IDX_RR_Data_revenue_SI_TI_DATE] ON [dbo].[RR_DATA_Revenue]
	(
		[SaleItemId] ASC,
		[TicketId] ASC,
		[RRCalcTypeTrigger] ASC,
		[AccountingType] ASC,
		[COAAccountId] ASC
	)WITH (STATISTICS_NORECOMPUTE = OFF, DROP_EXISTING = OFF, ONLINE = OFF) ON [PRIMARY]
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                FROM sys.indexes 
            WHERE name= 'IDX_RR_DATA_REV_TransactionID_COAACCOUNTID' AND object_id = OBJECT_ID('RR_DATA_Revenue')
			)
BEGIN
	CREATE NONCLUSTERED INDEX [IDX_RR_DATA_REV_TransactionID_COAACCOUNTID] ON [dbo].[RR_DATA_Revenue]
	(
		[TransactionId] ASC
	)
	INCLUDE([COAAccountId]) WITH (STATISTICS_NORECOMPUTE = OFF, DROP_EXISTING = OFF, ONLINE = OFF) ON [PRIMARY]
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                FROM sys.indexes 
            WHERE name= 'IDX_RR_DATA_Revenue_MatrixcellID_Includes' AND object_id = OBJECT_ID('RR_DATA_Revenue')
			)
BEGIN
	CREATE NONCLUSTERED INDEX [IDX_RR_DATA_Revenue_MatrixcellID_Includes] ON [dbo].[RR_DATA_Revenue]
	(
		[MatrixCellId] ASC
	)
	INCLUDE([SaleId],[SaleItemId],[TicketId],[SiteId],[OperatingAreaId],[WorkstationId],[UserGroupId],[UserId],[Quantity],[GrossAmount],[NetAmount],[MatrixSheetId],[AttributeIDs]) WITH (STATISTICS_NORECOMPUTE = OFF, DROP_EXISTING = OFF, ONLINE = OFF) ON [PRIMARY]
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                FROM sys.indexes 
            WHERE name= 'IDX_RR_DATA_Revenue_TransactionID_COAAccountid' AND object_id = OBJECT_ID('RR_DATA_Revenue')
			)
BEGIN
	CREATE NONCLUSTERED INDEX [IDX_RR_DATA_Revenue_TransactionID_COAAccountid] ON [dbo].[RR_DATA_Revenue]
	(
		[TransactionId] ASC
	)
	INCLUDE([COAAccountId]) WITH (STATISTICS_NORECOMPUTE = OFF, DROP_EXISTING = OFF, ONLINE = OFF) ON [PRIMARY]
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>scoluccia</ADDEDBY><SQLVERSION>3390</SQLVERSION><RMTRACKLINK>7620</RMTRACKLINK><REASON>These fields are generated for the coupon, at the moment it is used only to manage the quota coupon 
Comment:
- Modified DATA_SaleCoupon
  added field CouponGuid
- Modified CNF_Promotion_Quota
  added field InUse
- Modified SYS_LockQty
  added field ExtendedKey
- dropped primary key
- recreate primary key based on Context, [Key], Who, ExtendedKey  </REASON><TABLENAMES>CNF_Promotion_Quota=PromotionQuotaId
DATA_SaleCoupon=SaleCouponId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'CouponGuid' AND
                Object_ID  = Object_ID(N'DATA_SaleCoupon'))
BEGIN
  ALTER TABLE DATA_SaleCoupon
  ADD CouponGuid varChar(38) NULL
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'ExtendedKey' AND
                Object_ID  = Object_ID(N'SYS_LockQty'))
BEGIN
  ALTER TABLE SYS_LockQty
  ADD ExtendedKey varChar(40) DEFAULT N'' NOT NULL
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'InUse' AND
                Object_ID  = Object_ID(N'CNF_Promotion_Quota'))
BEGIN
  ALTER TABLE CNF_Promotion_Quota
  ADD InUse Int NULL
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.indexes
               WHERE NAME='IDX_DATA_SYS_LockQty_ExtendedKey' AND object_id = OBJECT_ID('SYS_LockQty'))
BEGIN
  CREATE NONCLUSTERED INDEX IDX_DATA_SYS_LockQty_ExtendedKey ON SYS_LockQty
  (
    ExtendedKey ASC
  )
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>DECLARE @PKName Varchar(50);
SELECT @PKName= name FROM sys.indexes
               WHERE object_id = OBJECT_ID('SYS_LockQty') and is_primary_key = 1 
IF @PKName IS NOT NULL 
  EXEC ('ALTER TABLE SYS_LockQty DROP CONSTRAINT ' + @PKName)
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>ALTER TABLE SYS_LockQty
   ADD CONSTRAINT PK_SYS_LockQty PRIMARY KEY (Context, [Key], Who, ExtendedKey);
</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>scoluccia</ADDEDBY><SQLVERSION>3389</SQLVERSION><RMTRACKLINK>8896</RMTRACKLINK><REASON>- Modified CNF_PROMOTION
  added field NotCombinableRollingDiscount</REASON><TABLENAMES>CNF_Promotion=PromotionId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'NotCombinableRollingDiscount' AND
                Object_ID  = Object_ID(N'CNF_Promotion'))
BEGIN
  ALTER TABLE CNF_Promotion
  ADD NotCombinableRollingDiscount smallint DEFAULT 0 NOT NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>scoluccia</ADDEDBY><SQLVERSION>3388</SQLVERSION><RMTRACKLINK>8896</RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>Paul Chen</ADDEDBY><SQLVERSION>3387</SQLVERSION><RMTRACKLINK>IDBOS-8750</RMTRACKLINK><REASON>Add Field COAnoDiscount(Boolean) to CNF_Promotion</REASON><TABLENAMES>CNF_Promotion=PromotionId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'COAnoDiscount' AND
                Object_ID  = Object_ID(N'CNF_Promotion'))
BEGIN
  ALTER TABLE CNF_Promotion
  ADD COAnoDiscount Smallint
END
</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>3386</SQLVERSION><RMTRACKLINK>IDBOS-8072</RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'TimePeriod' AND
                Object_ID  = Object_ID(N'RR_DATA_Revenue'))
BEGIN
  ALTER TABLE RR_DATA_Revenue
  ADD TimePeriod Smallint Default 0 NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Forecasted' AND
                Object_ID  = Object_ID(N'RR_DATA_Revenue'))
BEGIN
  ALTER TABLE RR_DATA_Revenue
  ADD Forecasted Smallint Default 0 NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'OOBflag' AND
                Object_ID  = Object_ID(N'RR_DATA_Revenue'))
BEGIN
  ALTER TABLE RR_DATA_Revenue
  ADD OOBflag Smallint Default 0 NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>ecandido</ADDEDBY><SQLVERSION>3385</SQLVERSION><RMTRACKLINK>IDBOS-9117</RMTRACKLINK><REASON>Change value for the right SaveRotationTimeout from minutes to seconds</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>Update
  DATA_Right
Set
  StrValue = StrValue * 60
Where
  RightId = (Select RightId From CNF_Right Where RightAK = 'SaveRotationTimeout')</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>sloporto</ADDEDBY><SQLVERSION>3384</SQLVERSION><RMTRACKLINK>IDBOS-8509</RMTRACKLINK><REASON>Added in Case Studio Default value for Field HideFeeInAmount (Boolean)  - No script needed.</REASON><TABLENAMES>CNF_PaymentMethod=PaymentMethodId</TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>sloporto</ADDEDBY><SQLVERSION>3383</SQLVERSION><RMTRACKLINK>IDBOS-8509</RMTRACKLINK><REASON>Scropt 0 - Add new column HideFeeInAmount in CNF_PaymentMethod</REASON><TABLENAMES>CNF_PaymentMethod=PaymentMethodId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'HideFeeInAmount' AND
                Object_ID  = Object_ID(N'CNF_PaymentMethod'))
BEGIN
  ALTER TABLE CNF_PaymentMethod
  ADD HideFeeInAmount Smallint Default 0 NOT NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3382</SQLVERSION><RMTRACKLINK>IDBOS-8634</RMTRACKLINK><REASON>0) Added new column IsVivaDotComEvent
1) Added New Table DATA_VivaDotComSync
2) Added Foreign Key FK_DATA_VivaDotComSync_Last_UserId_Log
3) Added Foreign Key FK_DATA_VivaDotComSync_Last_UserId_Log
</REASON><TABLENAMES>CNF_Event=EventId
DATA_VivaDotComSync=SyncId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'IsVivaDotComEvent' AND
                Object_ID  = Object_ID(N'CNF_Event'))
BEGIN
  ALTER TABLE CNF_Event
  ADD IsVivaDotComEvent Smallint Default 0 NOT NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                WHERE TABLE_SCHEMA = 'dbo' 
                  AND TABLE_NAME = 'DATA_VivaDotComSync')
BEGIN
CREATE TABLE DATA_VivaDotComSync(
	[SyncId] integer IDENTITY(1,1) NOT NULL,
	[EntityId] integer NOT NULL,
	[EntityTable] smallint NOT NULL,
        [AdditionalInfo] NVarChar(4000) NULL,
	[Last_UserId_Log] integer NULL,
	[Last_WorkstationId_Log] integer NULL,
	[Last_DateTime_Log] datetime NULL,
Primary Key ([SyncId])
) 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_DATA_VivaDotComSync_Last_UserId_Log')
BEGIN
   ALTER TABLE [DATA_VivaDotComSync]  
   ADD CONSTRAINT [FK_DATA_VivaDotComSync_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log])
   REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_DATA_VivaDotComSync_WorkstationId')
BEGIN
   ALTER TABLE [DATA_VivaDotComSync]  
   ADD CONSTRAINT [FK_DATA_VivaDotComSync_WorkstationId] FOREIGN KEY([Last_WorkstationId_Log])
   REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>ecandido</ADDEDBY><SQLVERSION>3381</SQLVERSION><RMTRACKLINK>IDBOS-7750</RMTRACKLINK><REASON>Add New Driver Typ and New Payment Method into the tables used just for the advanced payment

Add Value into the table CNF_LedgerAccount for the new payment method  Advanced Payment</REASON><TABLENAMES>CNF_Driver=DriverId
CNF_PaymentMethod=PaymentMethodId
CNF_LedgerAccount=LedgerAccountId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>BEGIN
  DECLARE @Today DATETIME
  DECLARE @SystemId INT
  DECLARE @DriverId INT

  IF NOT EXISTS (SELECT 1 FROM CNF_Driver WHERE DriverAk = 'TAdvPayment')
  BEGIN
    SELECT TOP 1 @SystemId = SystemId FROM CNF_System;
	SET @Today = GETDATE();

	EXECUTE otn_sp_ui_CNF_Driver_insert
      @DriverId OUTPUT,
      @SystemId,
      'TAdvPayment',
      7,
      19,
      4,
      'System Payment Method',
      519,
      NULL,
      0,
      1,
      1,
      @Today
  END ELSE
    SELECT @DriverId = DriverId FROM CNF_Driver WHERE DriverAk = 'TAdvPayment'

  IF NOT EXISTS ( SELECT 1 FROM CNF_PaymentMethod WHERE PaymentMethodAk = 'ADVPAY' )
  BEGIN
    INSERT INTO CNF_PaymentMethod (
	  DriverId,
      PaymentMethodAK,
      Code,
	  Description,
      PriorityOrder,
      Enabled,
	  ReservationOnly,
	  AllowGiftAid,
	  Last_UserId_Log,
      Last_WorkstationId_Log,
      Last_DateTime_Log)
	VALUES (
	  @DriverId,
	  'ADVPAY',
	  'Advanced Payment',
	  'Advanced Payment',
	  0,
	  0,
	  0,
	  0,
	  1,
	  1,
	  @Today);
  END
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>BEGIN
  DECLARE @Today DATETIME
  DECLARE @SystemAccountId INT

  SELECT @SystemAccountId = PaymentMethodId FROM CNF_PaymentMethod WHERE CODE = 'Advanced Payment';
  SET @Today = GETDATE();

  IF @SystemAccountId &gt; 0
  BEGIN
    IF NOT EXISTS(SELECT TOP 1 * FROM CNF_LedgerAccount WHERE SystemAccountId = @SystemAccountId)
      INSERT INTO CNF_LedgerAccount (
	    LedgerAccountAK,
        ParentAccountId,
        AccountType,
        AccountName,
        SystemAccountTable,
        SystemAccountId,
        InheritSystemAccountName,
	Last_UserId_Log,
	Last_WorkstationId_Log,
	Last_DateTime_Log)
      VALUES (
        'LEDGERADVANCEDPAYMENT',
        2,
        6,
        'Advanced Payment',
        153,
        @SystemAccountId,
        1,
	1,
	1,
	@Today)
  END
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>sloporto</ADDEDBY><SQLVERSION>3380</SQLVERSION><RMTRACKLINK>IDBOS-8327</RMTRACKLINK><REASON>Script 0 = Add Table CNF_Trigger_Permission
Script 1 = Add Foreign Hey FK_Trigger_Permission_TriggerId
Script 2 = Add Foreign Hey FK_Trigger_Permission_SiteId
Script 3 = Add Foreign Hey FK_Trigger_Permission_OperatingAreaId
Script 4 = Add Foreign Hey FK_Trigger_Permission_WorkstationId
Script 5 = Add Foreign Hey FK_Trigger_Permission_UserGroupId
Script 6 = Add Foreign Hey FK_Trigger_Permission_UserId
Script 7 = Add Foreign Hey FK_CNF_Trigger_Permission_Last_UserId_Log
Script 8 = Add Foreign Hey FK_CNF_Trigger_Last_WorkstationId_Log
Script 9 = Populate CNF_Trigger_Permission adding all Site allow for each trigger</REASON><TABLENAMES>CNF_Trigger_Permission=TriggerPermissionId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                WHERE TABLE_SCHEMA = 'dbo' 
                  AND TABLE_NAME = 'CNF_Trigger_Permission')
BEGIN
CREATE TABLE CNF_Trigger_Permission(
	[TriggerPermissionId] integer IDENTITY(1,1) NOT NULL,
	[TriggerId] integer NOT NULL,
	[SiteId] integer NULL,
	[OperatingAreaId] integer NULL,
	[WorkstationId] integer NULL,
	[UserGroupId] integer NULL,
	[UserId] integer NULL,
	[Allow] smallint NULL,
	[Last_UserId_Log] integer NULL,
	[Last_WorkstationId_Log] integer NULL,
	[Last_DateTime_Log] datetime NULL,
Primary Key ([TriggerPermissionId])
) 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_Trigger_Permission_TriggerId')
BEGIN
	ALTER TABLE [CNF_Trigger_Permission]  
	ADD CONSTRAINT [FK_Trigger_Permission_TriggerId] FOREIGN KEY([TriggerId])
	REFERENCES [CNF_Trigger] ([TriggerId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_Trigger_Permission_SiteId')
BEGIN
	ALTER TABLE [CNF_Trigger_Permission]  
	ADD CONSTRAINT [FK_Trigger_Permission_SiteId] FOREIGN KEY([SiteId])
	REFERENCES [CNF_Site] ([SiteId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_Trigger_Permission_OperatingAreaId')
BEGIN
	ALTER TABLE [CNF_Trigger_Permission]  
	ADD CONSTRAINT [FK_Trigger_Permission_OperatingAreaId] FOREIGN KEY([OperatingAreaId])
	REFERENCES [CNF_OperatingArea] ([OperatingAreaId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_Trigger_Permission_WorkstationId')
BEGIN
	ALTER TABLE [CNF_Trigger_Permission]  
	ADD CONSTRAINT [FK_Trigger_Permission_WorkstationId] FOREIGN KEY([WorkstationId])
	REFERENCES [CNF_Workstation] ([WorkstationId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_Trigger_Permission_UserGroupId')
BEGIN
	ALTER TABLE [CNF_Trigger_Permission]  
	ADD CONSTRAINT [FK_Trigger_Permission_UserGroupId] FOREIGN KEY([UserGroupId])
	REFERENCES [CNF_UserGroup] ([UserGroupId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_Trigger_Permission_UserId')
BEGIN
	ALTER TABLE [CNF_Trigger_Permission]  
	ADD CONSTRAINT [FK_Trigger_Permission_UserId] FOREIGN KEY([UserId])
	REFERENCES [CNF_User] ([UserId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_CNF_Trigger_Permission_Last_UserId_Log')
BEGIN
	ALTER TABLE [CNF_Trigger_Permission]  
	ADD CONSTRAINT [FK_CNF_Trigger_Permission_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log])
	REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_CNF_Trigger_Last_WorkstationId_Log')
BEGIN
	ALTER TABLE [CNF_Trigger_Permission]  
	ADD CONSTRAINT [FK_CNF_Trigger_Permission_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log])
	REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>INSERT INTO CNF_Trigger_permission 
(TriggerId, SiteId, Allow) 
SELECT T.TriggerId, SiteId, 1 FROM 
	CNF_Site S WITH(NOLOCK), CNF_trigger T WITH(NOLOCK)</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>nchinea</ADDEDBY><SQLVERSION>3379</SQLVERSION><RMTRACKLINK>IDBOS-7520</RMTRACKLINK><REASON>Add field  BestSeatType on table
0) CNF_SpaceStructure
1) CNF_Event
2) CNF_Performance</REASON><TABLENAMES>CNF_SpaceStructure=SpaceStructureId
CNF_Event=EventId
CNF_Performance=PerformanceId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'BestSeatType' AND
                Object_ID  = Object_ID(N'CNF_SpaceStructure'))
BEGIN
  ALTER TABLE CNF_SpaceStructure
  ADD BestSeatType Integer 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'BestSeatType' AND
                Object_ID  = Object_ID(N'CNF_Event'))
BEGIN
  ALTER TABLE CNF_Event
  ADD BestSeatType Integer 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'BestSeatType' AND
                Object_ID  = Object_ID(N'CNF_Performance'))
BEGIN
  ALTER TABLE CNF_Performance
  ADD BestSeatType Integer 
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>nchinea</ADDEDBY><SQLVERSION>3378</SQLVERSION><RMTRACKLINK>IDBOS-7831</RMTRACKLINK><REASON>Create table for store info coming from outside to work with job
Script 0 : Drop table if exist Table
Script 1 : Create Table</REASON><TABLENAMES>DATA_SchedulerProcess=SchedulerProcessId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>   IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES
           WHERE TABLE_SCHEMA = 'dbo'
           AND TABLE_NAME = 'DATA_SchedulerProcess')
  DROP TABLE DATA_SchedulerProcess
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>  IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES
               WHERE TABLE_SCHEMA = 'dbo'
               AND TABLE_NAME = 'DATA_SchedulerProcess')
  CREATE TABLE DATA_SchedulerProcess
   (
      SchedulerProcessId int IDENTITY(1,1) NOT NULL,
      JsonData varchar(MAX) NOT NULL,
      Code varchar(50) NOT NULL,    
      JobState  int NULL,
      SchedulerId int NULL,
      WorkstationId int NULL,
      DriverId int NULL,
      Last_DateTime_Log  datetime
    PRIMARY KEY (SchedulerProcessId ASC) 
  )</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3377</SQLVERSION><RMTRACKLINK>IDBOS-8197</RMTRACKLINK><REASON>0) Create Table CNF_DataMaskMultiUnique
1) Add Foreign Key on field Last_UserId_Log
2) Add Foreign Key on field WorkstationId_Log</REASON><TABLENAMES>CNF_DataMaskMultiUnique=DataMaskMultiUniqueId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>  IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES
               WHERE TABLE_SCHEMA = 'dbo'
               AND TABLE_NAME = 'CNF_DataMaskMultiUnique')
  CREATE TABLE CNF_DataMaskMultiUnique
   (
      DataMaskMultiUniqueId int IDENTITY(1,1) NOT NULL,
      ObjType  [smallint] NOT NULL,
      DmgCategories  [nvarchar](200) NOT NULL,
      Enabled smallint NOT NULL,
      Last_UserId_Log int NOT NULL,
      Last_WorkstationId_Log int NOT NULL,
      Last_DateTime_Log datetime NULL
      PRIMARY KEY (DataMaskMultiUniqueId ASC) 
      ,UNIQUE (ObjType)
  )</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DataMaskMultiUnique_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_DataMaskMultiUnique
  ADD  CONSTRAINT FK_CNF_DataMaskMultiUnique_Last_UserId_Log FOREIGN KEY([Last_UserId_Log])
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DataMaskMultiUnique_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_DataMaskMultiUnique
  ADD  CONSTRAINT FK_CNF_DataMaskMultiUnique_Last_WorkstationId_Log FOREIGN KEY([Last_WorkstationId_Log])
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>scoluccia</ADDEDBY><SQLVERSION>3376</SQLVERSION><RMTRACKLINK>IDBOS-7817</RMTRACKLINK><REASON>set field  ExternalID from NVarchar 20 to NVarchar 32</REASON><TABLENAMES>CNF_Performance=PerformanceId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'ExternalID' AND
                Object_ID  = Object_ID(N'CNF_Performance'))
BEGIN
  ALTER TABLE CNF_Performance 
  ALTER COLUMN ExternalID nvarchar(32)
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>scoluccia</ADDEDBY><SQLVERSION>3375</SQLVERSION><RMTRACKLINK>IDBOS-7084</RMTRACKLINK><REASON>Adding fields
	[ChangePerfPeriodEnabled] Smallint Default 0 NULL,
	[ChangePerfPeriodType] Smallint Default 0 NULL,
	[ChangePerfPeriodByDateFrom] U_Date NULL,
	[ChangePerfPeriodByDateTo] U_Date NULL,
	[ChangePerfPeriodByHours] Smallint NULL,
	[ChangePerfByNumbersEnabled] Smallint Default 0 NULL,
	[ChangePerfByNumbers] Smallint NULL,</REASON><TABLENAMES>CNF_MatrixCellInfo=MatrixCellInfoId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'ChangePerfPeriodEnabled' AND
                Object_ID  = Object_ID(N'CNF_MatrixCellInfo'))
BEGIN
  ALTER TABLE CNF_MatrixCellInfo 
  ADD ChangePerfPeriodEnabled SmallInt Default 0 NULL
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'ChangePerfPeriodType' AND
                Object_ID  = Object_ID(N'CNF_MatrixCellInfo'))
BEGIN
  ALTER TABLE CNF_MatrixCellInfo 
  ADD ChangePerfPeriodType SmallInt Default 0 NULL
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'ChangePerfPeriodByDateFrom' AND
                Object_ID  = Object_ID(N'CNF_MatrixCellInfo'))
BEGIN
  ALTER TABLE CNF_MatrixCellInfo 
  ADD ChangePerfPeriodByDateFrom Datetime NULL
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'ChangePerfPeriodByDateTo' AND
                Object_ID  = Object_ID(N'CNF_MatrixCellInfo'))
BEGIN
  ALTER TABLE CNF_MatrixCellInfo 
  ADD ChangePerfPeriodByDateTo Datetime NULL
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'ChangePerfPeriodByHours' AND
                Object_ID  = Object_ID(N'CNF_MatrixCellInfo'))
BEGIN
  ALTER TABLE CNF_MatrixCellInfo 
  ADD ChangePerfPeriodByHours Smallint NULL
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'ChangePerfByNumbersEnabled' AND
                Object_ID  = Object_ID(N'CNF_MatrixCellInfo'))
BEGIN
  ALTER TABLE CNF_MatrixCellInfo 
  ADD ChangePerfByNumbersEnabled SmallInt Default 0 NULL
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'ChangePerfByNumbers' AND
                Object_ID  = Object_ID(N'CNF_MatrixCellInfo'))
BEGIN
  ALTER TABLE CNF_MatrixCellInfo 
  ADD ChangePerfByNumbers Smallint NULL
END
</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>ffucarino</ADDEDBY><SQLVERSION>3374</SQLVERSION><RMTRACKLINK>IDBOS-8231</RMTRACKLINK><REASON>Drop table CNF_Capacity for not use

0= delete fkey FK_CNF_Capacity_Last_UserId_Log
1= delete fkey FK_CNF_Capacity_Last_WorkstationId_Log
2=Drop Table CNF_Capacity
3=delete sp_ui_CNF_Capacity_delete
4=delete sp_ui_CNF_Capacity_update
5=delete sp_ui_CNF_Capacity_insert</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
            WHERE TABLE_NAME = N'CNF_Capacity'
              AND CONSTRAINT_NAME = N'FK_CNF_Capacity_Last_UserId_Log')          
BEGIN
  ALTER TABLE [CNF_Capacity]
  DROP CONSTRAINT  FK_CNF_Capacity_Last_UserId_Log
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
            WHERE TABLE_NAME = N'CNF_Capacity'
              AND CONSTRAINT_NAME = N'FK_CNF_Capacity_Last_WorkstationId_Log')          
BEGIN
  ALTER TABLE [CNF_Capacity]
  DROP CONSTRAINT  FK_CNF_Capacity_Last_WorkstationId_Log
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT> IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES
           WHERE TABLE_SCHEMA = 'dbo'
           AND TABLE_NAME = 'CNF_Capacity')
  DROP TABLE CNF_Capacity</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT * 
          FROM sys.procedures
          WHERE name = 'sp_ui_CNF_Capacity_delete')
BEGIN
  DROP PROCEDURE sp_ui_CNF_Capacity_delete
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT * 
          FROM sys.procedures
          WHERE name = 'sp_ui_CNF_Capacity_update')
BEGIN
  DROP PROCEDURE sp_ui_CNF_Capacity_update
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT * 
          FROM sys.procedures
          WHERE name = 'sp_ui_CNF_Capacity_insert')
BEGIN
  DROP PROCEDURE sp_ui_CNF_Capacity_insert
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>ecandido</ADDEDBY><SQLVERSION>3373</SQLVERSION><RMTRACKLINK>IDBOS-7974</RMTRACKLINK><REASON>Create New table to save the MediaIdentifier returned with error "Ticket Not In Memory"

Script 0 : Create Table
Script 1 :  Create References on Table
Script 2 : Create Indexes on Table
</REASON><TABLENAMES>DATA_MediaIdentifierNotRecognized=MediaIdentifierNotRecognizedID</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES
               WHERE TABLE_SCHEMA = 'dbo'
               AND TABLE_NAME = 'DATA_MediaIdentifierNotRecognized')
  CREATE TABLE DATA_MediaIdentifierNotRecognized
  (
    MediaIdentifierNotRecognizedID int IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
    MediaIdentifier varchar(400) NOT NULL,
    GateId int NULL,
    WorkstationId int NULL,
    AccessConfigurationId Int NULL,
    UsageDate datetime NOT NULL,
    ValidateResult smallint NOT NULL,
    ValidationType smallint NOT NULL,
    UserId int NULL,
    PRIMARY KEY CLUSTERED
    (
       MediaIdentifierNotRecognizedID ASC
    )
  )</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS 
               WHERE CONSTRAINT_NAME ='FK_DATA_MediaIdentifierNotRecognized_GateId')
BEGIN
  ALTER TABLE DATA_MediaIdentifierNotRecognized WITH CHECK ADD CONSTRAINT FK_DATA_MediaIdentifierNotRecognized_GateId FOREIGN KEY(GateId)
  REFERENCES ADM_Gate (GateId)
END

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS 
               WHERE CONSTRAINT_NAME ='FK_DATA_MediaIdentifierNotRecognized_UserId')
BEGIN
  ALTER TABLE DATA_MediaIdentifierNotRecognized WITH CHECK ADD CONSTRAINT FK_DATA_MediaIdentifierNotRecognized_UserId FOREIGN KEY(UserId)
  REFERENCES CNF_User (UserId)
END

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS 
               WHERE CONSTRAINT_NAME ='FK_DATA_MediaIdentifierNotRecognized_WksId')
BEGIN
  ALTER TABLE DATA_MediaIdentifierNotRecognized WITH CHECK ADD CONSTRAINT FK_DATA_MediaIdentifierNotRecognized_WksId FOREIGN KEY(WorkstationId)
  REFERENCES CNF_Workstation (WorkstationId)
END

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS 
               WHERE CONSTRAINT_NAME ='FK_DATA_MediaIdentifierNotRecognized_AccConfId')
BEGIN
  ALTER TABLE DATA_MediaIdentifierNotRecognized WITH CHECK ADD CONSTRAINT FK_DATA_MediaIdentifierNotRecognized_AccConfId FOREIGN KEY(AccessConfigurationId)
  REFERENCES ADM_AccessConfiguration (AccessConfigurationId)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.indexes
               WHERE NAME='IDX_DATA_MediaIdentifierNotRecognized_GateId' AND object_id = OBJECT_ID('DATA_MediaIdentifierNotRecognized'))
BEGIN
  CREATE NONCLUSTERED INDEX IDX_DATA_MediaIdentifierNotRecognized_GateId ON DATA_MediaIdentifierNotRecognized
  (
    GateId ASC
  )
END

IF NOT EXISTS (SELECT * FROM sys.indexes
               WHERE NAME='IDX_DATA_MediaIdentifierNotRecognized_MediaIdentifier' AND object_id = OBJECT_ID('DATA_MediaIdentifierNotRecognized'))
BEGIN
  CREATE NONCLUSTERED INDEX IDX_DATA_MediaIdentifierNotRecognized_MediaIdentifier ON DATA_MediaIdentifierNotRecognized
  (
    MediaIdentifier ASC
  )
END

IF NOT EXISTS (SELECT * FROM sys.indexes
               WHERE NAME='IDX_DATA_MediaIdentifierNotRecognized_UsageDate' AND object_id = OBJECT_ID('DATA_MediaIdentifierNotRecognized'))
BEGIN
  CREATE NONCLUSTERED INDEX IDX_DATA_MediaIdentifierNotRecognized_UsageDate ON DATA_MediaIdentifierNotRecognized
  (
    UsageDate ASC
  )
END

IF NOT EXISTS (SELECT * FROM sys.indexes
               WHERE NAME='IDX_DATA_MediaIdentifierNotRecognized_WksId' AND object_id = OBJECT_ID('DATA_MediaIdentifierNotRecognized'))
BEGIN
  CREATE NONCLUSTERED INDEX IDX_DATA_MediaIdentifierNotRecognized_WksId ON DATA_MediaIdentifierNotRecognized
  (
    WorkstationId ASC
  )
END

IF NOT EXISTS (SELECT * FROM sys.indexes
               WHERE NAME='IDX_DATA_MediaIdentifierNotRecognized_AccConfId' AND object_id = OBJECT_ID('DATA_MediaIdentifierNotRecognized'))
BEGIN
  CREATE NONCLUSTERED INDEX IDX_DATA_MediaIdentifierNotRecognized_AccConfId ON DATA_MediaIdentifierNotRecognized
  (
    AccessConfigurationId ASC
  )
END
</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>3372</SQLVERSION><RMTRACKLINK>IDBOS-7806</RMTRACKLINK><REASON>Added 2 columns to RR_DATA_Revenue: JournalEntryByAccount,
LinkedJournalAccountId</REASON><TABLENAMES>RR_DATA_Revenue=RevenueRecognitionDataId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
               WHERE Name = N'JournalEntryByAccount' AND
               OBJECT_ID = OBJECT_ID(N'RR_DATA_Revenue'))
BEGIN
  ALTER TABLE RR_DATA_Revenue
  ADD JournalEntryByAccount smallint NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
               WHERE Name = N'LinkedJournalAccountId' AND
               OBJECT_ID = OBJECT_ID(N'RR_DATA_Revenue'))
BEGIN
  ALTER TABLE RR_DATA_Revenue
  ADD LinkedJournalAccountId smallint NULL
END
               </SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
           WHERE Name = N'COAAccountConfigID' AND
           OBJECT_ID = OBJECT_ID(N'RR_DATA_Revenue'))
BEGIN
  ALTER TABLE RR_DATA_Revenue
  ALTER COLUMN COAAccountConfigID int NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>pdalben</ADDEDBY><SQLVERSION>3371</SQLVERSION><RMTRACKLINK>IDBOS-7821</RMTRACKLINK><REASON>Added OncePerDay to CNF_Scheduller</REASON><TABLENAMES>CNF_Scheduler=SchedulerId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'OncePerDay' AND
                Object_ID  = Object_ID(N'CNF_Scheduler'))
BEGIN
  ALTER TABLE CNF_Scheduler
  ADD OncePerDay SmallInt Default 0 NOT NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3370</SQLVERSION><RMTRACKLINK>IDBOS-7789</RMTRACKLINK><REASON>1) Deleted from DATA_DMGDATA the Account records for ObjType 550 --&gt; ConfirmPassword
</REASON><TABLENAMES>DATA_DmgData=DmgDataId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>DELETE 
  DATA_DmgData
WHERE
  DmgType = 1 AND ObjType = 550</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>sloporto</ADDEDBY><SQLVERSION>3369</SQLVERSION><RMTRACKLINK>IDBOS-7447</RMTRACKLINK><REASON>Script 0 - Drop Indexes IX_DATA_WaitList_Subscriptions_DateTime and  IX_DATA_WaitList_Subscriptions_Subscriber
Script 0 - Create Field WaitListSubscriptionType
Script 1 - Create Field WaitListSubscriptionEventID
Script 2 - Create Field WaitListSubscriptionNumberOfPerformances
Script 3 - Create Field WaitListSubscriptionPriceTableID
Script 4 - Set Field WaitListSubscriptionPerformanceAK as NULL
Script 5 - Create Index IDX_WaitListSubscription_DateTime</REASON><TABLENAMES>DATA_WaitList_Subscriptions=WaitListSubscriptionID</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT name FROM sysindexes WHERE name = 'IX_DATA_WaitList_Subscriptions_DateTime')
 drop index [IX_DATA_WaitList_Subscriptions_DateTime] on [DATA_WaitList_Subscriptions] ;

IF EXISTS (SELECT name FROM sysindexes WHERE name = 'IX_DATA_WaitList_Subscriptions_Subscriber')
 drop index [IX_DATA_WaitList_Subscriptions_Subscriber] on [DATA_WaitList_Subscriptions] ;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'WaitListSubscriptionType' AND
                Object_ID  = Object_ID(N'DATA_WaitList_Subscriptions'))
BEGIN
  ALTER TABLE DATA_WaitList_Subscriptions 
  ADD WaitListSubscriptionType SmallInt Default 0 NOT NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'WaitListSubscriptionEventID' AND
                Object_ID  = Object_ID(N'DATA_WaitList_Subscriptions'))
BEGIN
  ALTER TABLE DATA_WaitList_Subscriptions 
  ADD WaitListSubscriptionEventID Integer Default 0 NOT NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'WaitListSubscriptionNumberOfPerformances' AND
                Object_ID  = Object_ID(N'DATA_WaitList_Subscriptions'))
BEGIN
  ALTER TABLE DATA_WaitList_Subscriptions 
  ADD WaitListSubscriptionNumberOfPerformances Integer Default 0 NOT NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'WaitListSubscriptionPriceTableID' AND
                Object_ID  = Object_ID(N'DATA_WaitList_Subscriptions'))
BEGIN
  ALTER TABLE DATA_WaitList_Subscriptions 
  ADD WaitListSubscriptionPriceTableID Integer Default 0 NOT NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'WaitListSubscriptionPerformanceAK' AND
                Object_ID  = Object_ID(N'DATA_WaitList_Subscriptions'))
BEGIN
  ALTER TABLE DATA_WaitList_Subscriptions 
  ALTER COLUMN WaitListSubscriptionPerformanceAK nvarchar(100) NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT name FROM sysindexes WHERE name = 'IDX_WaitListSubscription_DateTime')
BEGIN
  CREATE NONCLUSTERED INDEX [IDX_WaitListSubscription_DateTime] ON [dbo].[DATA_WaitList_Subscriptions]
  (
	[WaitListSubscriptionDateTime] ASC
  )
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>pchen</ADDEDBY><SQLVERSION>3368</SQLVERSION><RMTRACKLINK>IDBOS-4473</RMTRACKLINK><REASON>Add field FileManager to CNF_Mask</REASON><TABLENAMES>CNF_Mask=MaskId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'FileManager' AND
                Object_ID  = Object_ID(N'CNF_Mask'))
BEGIN
  ALTER TABLE CNF_Mask 
  ADD FileManager smallint
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>sloporto</ADDEDBY><SQLVERSION>3367</SQLVERSION><RMTRACKLINK>IDBOS-6937</RMTRACKLINK><REASON>Script 0 - Added field  SendingPostponedTicket to CNF_Event
Script 1 - Added field  TicketDelay to CNF_Event</REASON><TABLENAMES>CNF_Event=EventId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'SendingPostponedTicket' AND
                Object_ID  = Object_ID(N'CNF_Event'))
BEGIN
  ALTER TABLE CNF_Event 
  ADD SendingPostponedTicket SmallInt Default 0 NOT NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'TicketDelay' AND
                Object_ID  = Object_ID(N'CNF_Event'))
BEGIN
  ALTER TABLE CNF_Event 
  ADD TicketDelay SmallInt Default 0 NOT NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3366</SQLVERSION><RMTRACKLINK>IDBOS-7651</RMTRACKLINK><REASON>1) Add Column Last_UserId_Log
2) Add Column Last_WorkstationId_Log
3) Add Column Last_DateTime_Log
4) Creating Foreign Key for column Last_UserId_Log
5) Creating Foreign Key for column Last_WorkstationId_Log</REASON><TABLENAMES>ADM_AccessPoint=WorkstationId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'ADM_AccessPoint'))
BEGIN
  ALTER TABLE ADM_AccessPoint
  ADD Last_UserId_Log Integer null
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_WorkstationId_Log' AND
                Object_ID  = Object_ID(N'ADM_AccessPoint'))
BEGIN
  ALTER TABLE ADM_AccessPoint
  ADD Last_WorkstationId_Log Integer null
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_DateTime_Log' AND
                Object_ID  = Object_ID(N'ADM_AccessPoint'))
BEGIN
  ALTER TABLE ADM_AccessPoint
  ADD Last_DateTime_Log DateTime null
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_ADM_AccessPoint_UserId')
BEGIN
  ALTER TABLE ADM_AccessPoint
  ADD CONSTRAINT [FK_ADM_AccessPoint_UserId] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_ADM_AccessPoint_WorkstationId')
BEGIN
  ALTER TABLE ADM_AccessPoint
  ADD CONSTRAINT [FK_ADM_AccessPoint_WorkstationId] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dchen</ADDEDBY><SQLVERSION>3365</SQLVERSION><RMTRACKLINK>IDBOS-6933</RMTRACKLINK><REASON>Opera Hospitality Integration Plaform 
======================================
* Resizing fields.
* Creating fields.</REASON><TABLENAMES>DATA_PaymentHotel=PaymentHotelId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT * FROM sys.columns
  WHERE Name = N'RawRequest'
  AND OBJECT_ID = OBJECT_ID(N'DATA_PaymentHotel'))
BEGIN
  ALTER TABLE DATA_PaymentHotel
  ALTER COLUMN RawRequest varchar(max)
END

IF EXISTS(SELECT * FROM sys.columns
  WHERE Name = N'RawAnswer'
  AND OBJECT_ID = OBJECT_ID(N'DATA_PaymentHotel'))
BEGIN
  ALTER TABLE DATA_PaymentHotel
  ALTER COLUMN RawAnswer varchar(max)
END

IF EXISTS(SELECT * FROM sys.columns
  WHERE Name = N'RoomNumber'
  AND OBJECT_ID = OBJECT_ID(N'DATA_PaymentHotel'))
BEGIN
  ALTER TABLE DATA_PaymentHotel
  ALTER COLUMN RoomNumber varchar(10)
END

IF EXISTS(SELECT * FROM sys.columns
  WHERE Name = N'GuestLastName'
  AND OBJECT_ID = OBJECT_ID(N'DATA_PaymentHotel'))
BEGIN
  ALTER TABLE DATA_PaymentHotel
  ALTER COLUMN GuestLastName varchar(100)
END        

IF EXISTS(SELECT * FROM sys.columns
  WHERE Name = N'HotelReservationId'
  AND OBJECT_ID = OBJECT_ID(N'DATA_PaymentHotel'))
BEGIN
  ALTER TABLE DATA_PaymentHotel
  ALTER COLUMN HotelReservationId varchar(20)
END        </SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
  WHERE Name = N'UseParams'
  AND OBJECT_ID = OBJECT_ID(N'DATA_PaymentHotel'))
BEGIN
  ALTER TABLE DATA_PaymentHotel
  ADD UseParams smallint
END

IF NOT EXISTS(SELECT * FROM sys.columns
  WHERE Name = N'isJSON'
  AND OBJECT_ID = OBJECT_ID(N'DATA_PaymentHotel'))
BEGIN
  ALTER TABLE DATA_PaymentHotel
  ADD isJSON smallint
END  </SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dchen</ADDEDBY><SQLVERSION>3364</SQLVERSION><RMTRACKLINK>IDBOS-6933</RMTRACKLINK><REASON>CNF_AccessToken -&gt; AccessToken resizing to max</REASON><TABLENAMES>CNF_AccessToken=AccessToken</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT * FROM sys.columns
  WHERE Name = N'AccessToken'
  AND OBJECT_ID = OBJECT_ID(N'CNF_AccessToken'))
BEGIN
  ALTER TABLE CNF_AccessToken
  ALTER COLUMN AccessToken varchar(max)
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>scoluccia</ADDEDBY><SQLVERSION>3363</SQLVERSION><RMTRACKLINK>IDBOS-5823</RMTRACKLINK><REASON>Quota Capping Restriction based on Visit(performance)Date 
Add field    VisitPerfDate and  PerformanceId 
0)Add VisitPerfDate CNF_Promotion2Account
1)Add  PerformanceId  in DATA_Promotion2Account
2)Add VisitPerfDate in DATA_Promotion2Account</REASON><TABLENAMES>CNF_Promotion2Account=Promotion2AccountId
DATA_Promotion2Account=Promotion2AccountId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
  WHERE Name = 'VisitPerfDate'
  AND OBJECT_ID = OBJECT_ID('CNF_Promotion2Account'))
BEGIN
  ALTER TABLE CNF_Promotion2Account ADD
  VisitPerfDate smallint NOT NULL CONSTRAINT DF_CNF_Promotion2Account_VisitPerfDate DEFAULT 0
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
  WHERE Name = 'PerformanceId'
  AND OBJECT_ID = OBJECT_ID('DATA_Promotion2Account'))
BEGIN
  ALTER TABLE DATA_Promotion2Account 
  ADD PerformanceId integer
END </SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
  WHERE Name = 'VisitPerfDate'
  AND OBJECT_ID = OBJECT_ID('DATA_Promotion2Account'))
BEGIN
  ALTER TABLE DATA_Promotion2Account ADD
  VisitPerfDate smallint NOT NULL CONSTRAINT DF_DATA_Promotion2Account_VisitPerfDate DEFAULT 0
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>pchen</ADDEDBY><SQLVERSION>3362</SQLVERSION><RMTRACKLINK>IDBOS-7499</RMTRACKLINK><REASON>Add field ExternalCode2 to DATA_Account
</REASON><TABLENAMES>DATA_Account=AccountId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'ExternalCode2' AND
                Object_ID  = Object_ID(N'DATA_Account'))
BEGIN
  ALTER TABLE DATA_Account 
  ADD ExternalCode2 varchar(200)
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>3361</SQLVERSION><RMTRACKLINK>IDBOS-6732</RMTRACKLINK><REASON>Adding Code and Name columns to CNF_CalendarShortcut</REASON><TABLENAMES>CNF_CalendarShortcut=CalendarShortcutId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                  WHERE Name = N'Code' AND
                  OBJECT_ID = OBJECT_ID(N'CNF_CalendarShortcut'))
BEGIN
  ALTER TABLE CNF_CalendarShortcut
  ADD Code NVarchar(30) NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                  WHERE Name = N'Name' AND
                  OBJECT_ID = OBJECT_ID(N'CNF_CalendarShortcut'))
BEGIN
  ALTER TABLE CNF_CalendarShortcut
  ADD Name NVarchar(50) NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>pchen</ADDEDBY><SQLVERSION>3360</SQLVERSION><RMTRACKLINK>IDBOS-7441</RMTRACKLINK><REASON>Add field ExternalReferenceId to DATA_SaleItem2Account</REASON><TABLENAMES>DATA_SaleItem2Account=SaleItem2AccountId
</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'ExternalReferenceId' AND
                Object_ID  = Object_ID(N'DATA_SaleItem2Account'))
BEGIN
  ALTER TABLE DATA_SaleItem2Account 
  ADD ExternalReferenceId varchar(400)
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>3359</SQLVERSION><RMTRACKLINK>IDBOS-6732</RMTRACKLINK><REASON></REASON><TABLENAMES>CNF_CalendarShortcut=CalendarShortcutId
CNF_CalendarShortcutItem=CalendarShortcutItemId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT *
                FROM INFORMATION_SCHEMA.TABLES
                                WHERE TABLE_SCHEMA = 'dbo'
                                AND TABLE_NAME = 'CNF_CalendarShortcutItem')
BEGIN
  Create table [CNF_CalendarShortcutItem]
  (
                [CalendarShortcutItemId] Integer Identity(1,1) NOT NULL,
                [CalendarShortcutId] Integer NOT NULL,
                [Name] NVarchar(30) NULL,
                [SortOrder] Integer NULL,
                [FromDate] DateTime NULL,
                [ToDate] DateTime NULL,
                [Last_UserId_Log] Integer NULL,
                [Last_WorkstationId_Log] Integer NULL,
                [Last_DateTime_Log] DateTime NULL,
        Primary Key ([CalendarShortcutItemId])
  )
END           </SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT * FROM sys.columns
              WHERE Name = N'FromDate' AND
			  OBJECT_ID = OBJECT_ID(N'CNF_CalendarShortcut')) AND EXISTS(SELECT * FROM sys.columns
              WHERE Name = N'ToDate' AND
			  OBJECT_ID = OBJECT_ID(N'CNF_CalendarShortcut'))
BEGIN
DECLARE @sqltext VARCHAR(MAX);

SET @sqltext =

  'CREATE TABLE #Temp(CalendarId int, FromDate DateTime, ToDate DateTime, Name NVarchar(50), Last_UserId_Log int, Last_WorkstationId_Log int, Last_DateTime_Log DateTime) '+
  'INSERT INTO #Temp(CalendarId, FromDate, ToDate, Name, Last_UserId_Log, Last_WorkstationId_Log, Last_DateTime_Log) '+
  'SELECT CalendarId, FromDate, ToDate, Description, Last_UserId_Log, Last_WorkstationId_Log, Last_DateTime_Log '+
  'FROM CNF_CalendarShortcut '+
  'CREATE TABLE #Temp2(CalendarShortcutId int, CalendarId int, Descr Varchar(10)) '+
  'INSERT INTO #Temp2(CalendarShortcutId, CalendarId, Descr) '+
  'SELECT Min(CalendarShortcutId), CalendarId, ''DEFAULT'' '+
  'FROM CNF_CalendarShortcut '+
  'GROUP BY CalendarId '+
  'DELETE FROM CNF_CalendarShortcut '+
  'INSERT INTO CNF_CalendarShortcut(CalendarId, Description) '+
  'SELECT CalendarId, Descr '+
  'FROM #Temp2 '+
  'INSERT INTO CNF_CalendarShortcutItem(CalendarShortcutId, FromDate, ToDate, Name, Last_UserId_Log, Last_WorkstationId_Log, Last_DateTime_Log) '+
  'SELECT CS.CalendarShortcutId, #Temp.FromDate, #Temp.ToDate, #Temp.Name, #Temp.Last_UserId_Log, #Temp.Last_WorkstationId_Log, #Temp.Last_DateTime_Log '+
  'FROM #Temp '+
  'INNER JOIN CNF_CalendarShortcut CS WITH (NOLOCK) ON CS.CalendarId = #Temp.CalendarId '+
  'DELETE #Temp '+
  'DELETE #Temp2';

EXEC (@sqltext);

END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT * FROM sys.columns
              WHERE Name = N'FromDate' AND
			              OBJECT_ID = OBJECT_ID(N'CNF_CalendarShortcut'))
BEGIN
  ALTER TABLE CNF_CalendarShortcut
  DROP COLUMN FromDate
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT * FROM sys.columns
              WHERE Name = N'ToDate' AND
			              OBJECT_ID = OBJECT_ID(N'CNF_CalendarShortcut'))
BEGIN
  ALTER TABLE CNF_CalendarShortcut
  DROP COLUMN ToDate
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT * FROM sys.columns
              WHERE Name = N'SortOrder' AND
			              OBJECT_ID = OBJECT_ID(N'CNF_CalendarShortcut'))
BEGIN
  ALTER TABLE CNF_CalendarShortcut
  DROP COLUMN SortOrder
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>ecandido</ADDEDBY><SQLVERSION>3358</SQLVERSION><RMTRACKLINK>IDBOS-7387</RMTRACKLINK><REASON>Add field to enable using Gift AId</REASON><TABLENAMES>CNF_System=SystemId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>if not exists (select
                 column_name
               from
                 INFORMATION_SCHEMA.columns
               where
                 table_name = 'CNF_System' and
                 column_name = 'GiftAidEnabled')
  alter table CNF_System add GiftAidEnabled smallint</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>pchen</ADDEDBY><SQLVERSION>3357</SQLVERSION><RMTRACKLINK>IDBOS-6864</RMTRACKLINK><REASON>Alter size of field AdditionalCode to 20</REASON><TABLENAMES>CNF_MatrixCell=MatrixCellId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT * FROM sys.columns
  WHERE Name = N'AdditionalCode'
  AND OBJECT_ID = OBJECT_ID(N'CNF_MatrixCell'))
BEGIN
  ALTER TABLE CNF_MatrixCell 
  ALTER COLUMN AdditionalCode nvarchar(20)
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>3356</SQLVERSION><RMTRACKLINK>IDBOS-7196</RMTRACKLINK><REASON></REASON><TABLENAMES>DATA_SaleItem=SaleItemId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
              WHERE Name = N'ExternalReferenceId' AND
              OBJECT_ID = OBJECT_ID(N'DATA_SaleItem'))
BEGIN
  ALTER TABLE DATA_SaleItem
  ADD ExternalReferenceId NVarchar(400) NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>3355</SQLVERSION><RMTRACKLINK>6771</RMTRACKLINK><REASON></REASON><TABLENAMES>RR_Data_revenue=RevenueRecognitionDataID
RR_CNF_RevenueRecognitionRule=RevenueRecognitionRuleID</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
              WHERE Name = N'Encoded' AND
			  OBJECT_ID = OBJECT_ID(N'RR_Data_revenue'))
BEGIN
  ALTER TABLE RR_Data_revenue
  ADD Encoded [smallint] NULL 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
              WHERE Name = N'UsageTime' AND
			  OBJECT_ID = OBJECT_ID(N'RR_CNF_RevenueRecognitionRule'))
BEGIN
  ALTER TABLE RR_CNF_RevenueRecognitionRule
  ADD UsageTime [smallint] NULL 
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>scoluccia</ADDEDBY><SQLVERSION>3354</SQLVERSION><RMTRACKLINK>IDBOS-7038</RMTRACKLINK><REASON>Comment:
0) Create Table CNF_UpSellCategory
1) Add Foreign Key on field ParentId
2) Add Foreign Key on field DmgCategoryId
3) Add Foreign Key on field Last_UserId_Log
4) Add Foreign Key on field WorkstationId_Log
5) Add Constraint Key on field Enabled
___________________________________________________________________
6) Create Table CNF_UpSellCategoryValidity
7) Add Foreign Key on field UpSellId
8) Add Foreign Key on field UpSellCategoryId
9) Add Foreign Key on field Last_UserId_Log
10) Add Foreign Key on field WorkstationId_Log</REASON><TABLENAMES>CNF_UpSellCategory=UpSellCategoryId
CNF_UpSellCategoryValidity=UpSellCatValidityId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND TABLE_NAME = 'CNF_UpSellCategory')
BEGIN
  CREATE TABLE CNF_UpSellCategory
  (
	[UpSellCategoryId] [int] IDENTITY(1,1) NOT NULL,
	[UpSellCategoryCode] [varchar](10) NOT NULL,
	[UpSellCategoryDescription] [nvarchar](100) NULL,
	[ParentId] [int] NULL,
	[Position] [int] NOT NULL,
	[Level] [int] NOT NULL,
	[ActivationType] [int] NULL,
	[RecursiveName] [nvarchar](200) NULL,
	[RecursiveDesc] [nvarchar](200) NULL,
	[Enabled] [smallint] NOT NULL,
	[UpSellCategoryAK] [varchar](32) NOT NULL,
	[DmgCategoryId] [int] NULL,
	[Last_UserId_Log] [int] NULL,
	[Last_WorkstationId_Log] [int] NULL,
	[Last_DateTime_Log] [datetime] NULL,
    PRIMARY KEY (UpSellCategoryId)
  )
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_UpSellCategory_ParentId')
BEGIN
  ALTER TABLE CNF_UpSellCategory
  ADD  CONSTRAINT FK_CNF_UpSellCategory_ParentId FOREIGN KEY(ParentId)
  REFERENCES [CNF_UpSellCategory] ([UpSellCategoryId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_UpSellCategory_DmgCategoryId')
BEGIN
  ALTER TABLE CNF_UpSellCategory
  ADD  CONSTRAINT FK_CNF_UpSellCategory_DmgCategoryId FOREIGN KEY(DmgCategoryId)
  REFERENCES [CNF_DmgCategory] ([DmgCategoryId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_UpSellCategory_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_UpSellCategory
  ADD  CONSTRAINT FK_CNF_UpSellCategory_Last_UserId_Log FOREIGN KEY([Last_UserId_Log])
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_UpSellCategory_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_UpSellCategory
  ADD  CONSTRAINT FK_CNF_UpSellCategory_Last_WorkstationId_Log FOREIGN KEY([Last_WorkstationId_Log])
  REFERENCES [CNF_Workstation] ([WorkstationId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.objects WHERE type = 'D' AND name = 'CNF_UPSELL_CAT_ENABLED_DEF_VALUE')
BEGIN
  ALTER TABLE CNF_UpSellCategory
  ADD  CONSTRAINT [CNF_UPSELL_CAT_ENABLED_DEF_VALUE]  DEFAULT ((1)) FOR [Enabled]
END  </SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND TABLE_NAME = 'CNF_UpSellCategoryValidity')
BEGIN
  CREATE TABLE CNF_UpSellCategoryValidity
  (
	[UpSellCatValidityId] [int] IDENTITY(1,1) NOT NULL,
	[UpSellCategoryId] [int] NOT NULL,
	[UpSellId] [int] NULL,
	[Last_UserId_Log] [int] NULL,
	[Last_WorkstationId_Log] [int] NULL,
	[Last_DateTime_Log] [datetime] NULL,
    PRIMARY KEY (UpSellCatValidityId)
  )
END  
	</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_UpSellCategoryVal_UpSellId')
BEGIN
  ALTER TABLE CNF_UpSellCategoryValidity
  ADD  CONSTRAINT FK_CNF_UpSellCategoryVal_UpSellId FOREIGN KEY(UpSellId)
  REFERENCES [CNF_UpSell] ([UpSellId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_UpSellCategoryVal_UpSellCatId')
BEGIN
  ALTER TABLE CNF_UpSellCategoryValidity
  ADD  CONSTRAINT FK_CNF_UpSellCategoryVal_UpSellCatId FOREIGN KEY(UpSellCategoryId)
  REFERENCES [CNF_UpSellCategory] ([UpSellCategoryId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_UpSellCategoryVal_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_UpSellCategoryValidity
  ADD  CONSTRAINT FK_CNF_UpSellCategoryVal_Last_UserId_Log FOREIGN KEY([Last_UserId_Log])
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_UpSellCategoryVal_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_UpSellCategoryValidity
  ADD  CONSTRAINT FK_CNF_UpSellCategoryVal_Last_WorkstationId_Log FOREIGN KEY([Last_WorkstationId_Log])
  REFERENCES [CNF_Workstation] ([WorkstationId])
END
</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>nchinea</ADDEDBY><SQLVERSION>3353</SQLVERSION><RMTRACKLINK>IDBOS-7023</RMTRACKLINK><REASON>0 create table</REASON><TABLENAMES>SYS_APTStatus=AptStatusId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT *
                FROM INFORMATION_SCHEMA.TABLES
				WHERE TABLE_SCHEMA = 'dbo'
				AND TABLE_NAME = 'SYS_APTStatus')
BEGIN
  Create table [SYS_APTStatus]
  (
		[AptStatusId] Integer Identity(1,1) NOT NULL,
		[SessionId] nVarChar(64) NOT NULL,
		[WorkstationId] Integer NOT NULL,
		[AccessPointId] Integer NOT NULL,
		[TDVName] nVarChar(200) NOT NULL,
		[TDVNumber] Integer NOT NULL,
		[TDVType] Integer NOT NULL,
		[LastPing] DateTime NOT NULL,    
	Primary Key ([AptStatusId])
   )
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>pdalben</ADDEDBY><SQLVERSION>3352</SQLVERSION><RMTRACKLINK>IDBOS-7100</RMTRACKLINK><REASON>Empty script</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>pdalben</ADDEDBY><SQLVERSION>3351</SQLVERSION><RMTRACKLINK>IDBOS-7100</RMTRACKLINK><REASON>DATA_DeviceOperations added new fields
-  DATA_DeviceOperations.OperationCardInput  
-  DATA_DeviceOperations.OperationCardOutput
-  DATA_DeviceOperations.OperationNote
</REASON><TABLENAMES>DATA_DeviceOperations=DevOpId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
WHERE Name = N'OperationNote' AND OBJECT_ID = OBJECT_ID(N'DATA_DeviceOperations'))
BEGIN
  ALTER TABLE DATA_DeviceOperations ADD OperationNote Nvarchar(3000) NULL
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
WHERE Name = N'OperationCardInput' AND OBJECT_ID = OBJECT_ID(N'DATA_DeviceOperations'))
BEGIN
  ALTER TABLE DATA_DeviceOperations ADD OperationCardInput Nvarchar(max) NULL
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
WHERE Name = N'OperationCardOutput' AND OBJECT_ID = OBJECT_ID(N'DATA_DeviceOperations'))
BEGIN
  ALTER TABLE DATA_DeviceOperations ADD OperationCardOutput Nvarchar(max) NULL
END
</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>nchinea</ADDEDBY><SQLVERSION>3350</SQLVERSION><RMTRACKLINK>IDBOS-5436</RMTRACKLINK><REASON>Script to create table SP and entry for cache
0 - Create main table
1 - Create Sp 
2 - Create entry
3 - Create trigger</REASON><TABLENAMES>SYS_CacheTable=Tableid</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND TABLE_NAME = 'SYS_CacheTable')
BEGIN
  CREATE TABLE SYS_CacheTable(
	TABLEID int IDENTITY(1,1) NOT NULL,
	TableName varchar(100) NOT NULL,
	IRN int NULL,
	DateTimeModify datetime NULL,
	DateTimeCheck datetime NULL,
	FunctionCall varchar(100) NULL
  PRIMARY KEY (TABLEID) 
  )
END </SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>CREATE PROCEDURE [dbo].[otn_sp_CACHE_TABLE_update] 
	@Param nvarchar(50)
AS
BEGIN
	SET NOCOUNT ON;
	UPDATE SYS_CacheTable SET DateTimeModify=GETDATE(), IRN = IRN + 1 WHERE TableName =@Param; 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>delete from SYS_CacheTable
insert into SYS_CacheTable (TableName, IRN, FunctionCall) VALUES ('CNF_PROMOTION',1,'CheckPromotion')
insert into SYS_CacheTable (TableName, IRN, FunctionCall) VALUES ('CNF_MATRIXSHEET',1,'CheckMatrixCellCache')
insert into SYS_CacheTable (TableName, IRN, FunctionCall) VALUES ('CNF_Envelope_Permission',1,'CheckEnvelopePermissionCache')
insert into SYS_CacheTable (TableName, IRN, FunctionCall) VALUES ('CNF_Event_Permission',1,'CheckEventPermissionCache')
insert into SYS_CacheTable (TableName, IRN, FunctionCall) VALUES ('CNF_Attribute_SaleValidity',1,'CheckMatrixCellPermissionCache')
insert into SYS_CacheTable (TableName, IRN, FunctionCall) VALUES ('CNF_MatrixSheet_SaleValidity',1,'CheckMatrixCellPermissionCache')
insert into SYS_CacheTable (TableName, IRN, FunctionCall) VALUES ('CNF_MatrixCellPermission',1,'CheckMatrixCellPermissionCache')
insert into SYS_CacheTable (TableName, IRN, FunctionCall) VALUES ('CNF_PromotionItem',1,'CheckPromotion')
insert into SYS_CacheTable (TableName, IRN, FunctionCall) VALUES ('CNF_PromotionItemRule',1,'CheckPromotion')
insert into SYS_CacheTable (TableName, IRN, FunctionCall) VALUES ('CNF_PromotionProduct',1,'CheckPromotion')
insert into SYS_CacheTable (TableName, IRN, FunctionCall) VALUES ('CNF_PromotionProductCategory',1,'CheckPromotion')
insert into SYS_CacheTable (TableName, IRN, FunctionCall) VALUES ('CNF_PromotionValidity',1,'CheckPromotion')
insert into SYS_CacheTable (TableName, IRN, FunctionCall) VALUES ('CNF_PromotionEvent',1,'CheckPromotion')
insert into SYS_CacheTable (TableName, IRN, FunctionCall) VALUES ('CNF_PromotionPermission',1,'CheckPromotionPermissionCache')
insert into SYS_CacheTable (TableName, IRN, FunctionCall) VALUES ('CNF_SeatCategory_Permission',1,'CheckSeatCategoryPermissionCache')
insert into SYS_CacheTable (TableName, IRN, FunctionCall) VALUES ('CNF_DocTemplate_Permission',1,'CheckDocTemplatePermissionCache')
insert into SYS_CacheTable (TableName, IRN, FunctionCall) VALUES ('CNF_DmgCategory_Permission',1,'CheckDmgCategoryPermissionCache')
insert into SYS_CacheTable (TableName, IRN, FunctionCall) VALUES ('CNF_DmgCategory',1,'CheckDmgCategoryPermissionCache')
insert into SYS_CacheTable (TableName, IRN, FunctionCall) VALUES ('CNF_Attribute',1,'CheckMatrixCellCache')
insert into SYS_CacheTable (TableName, IRN, FunctionCall) VALUES ('CNF_AttributeTemplate',1,'CheckMatrixCellCache')
insert into SYS_CacheTable (TableName, IRN, FunctionCall) VALUES ('CNF_AttributeSet',1,'CheckMatrixCellCache')
insert into SYS_CacheTable (TableName, IRN, FunctionCall) VALUES ('CNF_MatrixCell',1,'CheckMatrixCellCache')
insert into SYS_CacheTable (TableName, IRN, FunctionCall) VALUES ('CNF_MatrixCellInfo',1,'CheckMatrixCellCache')
insert into SYS_CacheTable (TableName, IRN, FunctionCall) VALUES ('CNF_ProductValidity',1,'CheckMatrixCellCache')
insert into SYS_CacheTable (TableName, IRN, FunctionCall) VALUES ('CNF_ProductValidity2Event',1,'CheckMatrixCellCache')
insert into SYS_CacheTable (TableName, IRN, FunctionCall) VALUES ('CNF_Multilanguage',1,'CheckMultilanguageCache')
insert into SYS_CacheTable (TableName, IRN, FunctionCall) VALUES ('DATA_Right',1,'CheckRightCache')
insert into SYS_CacheTable (TableName, IRN, FunctionCall) VALUES ('CNF_DocTemplate',1,'CheckReportBuilderCache')
insert into SYS_CacheTable (TableName, IRN, FunctionCall) VALUES ('CNF_TicketPackageGroupPermission',1,'CheckTicketPackageGroupPermissionCache')
insert into SYS_CacheTable (TableName, IRN, FunctionCall) VALUES ('CNF_Delivery_Permission',1,'CheckDeliveryPermissionCache')
insert into SYS_CacheTable (TableName, IRN, FunctionCall) VALUES ('CNF_ShopCartValidation_Permission',1,'CheckShopCartValidationPermissionCache')
insert into SYS_CacheTable (TableName, IRN, FunctionCall) VALUES ('CNF_TravelTime', 1,'CheckTravelMatrixCache')
insert into SYS_CacheTable (TableName, IRN, FunctionCall) VALUES ('CNF_TravelMatrix', 1,'CheckTravelMatrixCache')
insert into SYS_CacheTable (TableName, IRN, FunctionCall) VALUES ('CNF_Performance_Permission',1,'CheckPerformancePermissionCache')
insert into SYS_CacheTable (TableName, IRN, FunctionCall) VALUES ('CNF_SuggestiveSell_Permission',1,'CheckSuggestiveSellPermissionCache')
insert into SYS_CacheTable (TableName, IRN, FunctionCall) VALUES ('CNF_UpSell_Permission',1,'CheckUpSellPermissionCache')
insert into SYS_CacheTable (TableName, IRN, FunctionCall) VALUES ('CNF_Site_LoginPermission',1,'CheckUserLogInPermissionCache')</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>Declare @TABLE VarChar(200)     
Set @TABLE = 'CNF_Site_LoginPermission'
EXEC('IF OBJECT_ID ('''+@TABLE+'_Cache'', ''TR'') IS NOT NULL DROP TRIGGER '+@TABLE+'_Cache')
EXEC('CREATE TRIGGER [dbo].['+@TABLE+'_Cache] on [dbo].['+@TABLE+'] AFTER INSERT,DELETE,UPDATE 
      AS 
	  BEGIN  
	    Declare @Sql nvarchar(max);	
		SET NOCOUNT ON;	
		set @Sql = '''+@TABLE+''';
		EXEC otn_sp_CACHE_TABLE_update @Sql
	  END')

Set @TABLE = 'CNF_Envelope_Permission'
EXEC('IF OBJECT_ID ('''+@TABLE+'_Cache'', ''TR'') IS NOT NULL DROP TRIGGER '+@TABLE+'_Cache')
EXEC('CREATE TRIGGER [dbo].['+@TABLE+'_Cache] on [dbo].['+@TABLE+'] AFTER INSERT,DELETE,UPDATE 
      AS 
	  BEGIN  
	    Declare @Sql nvarchar(max);	
		SET NOCOUNT ON;	
		set @Sql = '''+@TABLE+''';
		EXEC otn_sp_CACHE_TABLE_update @Sql
	  END')

Set @TABLE = 'CNF_Event_Permission'
EXEC('IF OBJECT_ID ('''+@TABLE+'_Cache'', ''TR'') IS NOT NULL DROP TRIGGER '+@TABLE+'_Cache')
EXEC('CREATE TRIGGER [dbo].['+@TABLE+'_Cache] on [dbo].['+@TABLE+'] AFTER INSERT,DELETE,UPDATE 
      AS 
	  BEGIN  
	    Declare @Sql nvarchar(max);	
		SET NOCOUNT ON;	
		set @Sql = '''+@TABLE+''';
		EXEC otn_sp_CACHE_TABLE_update @Sql
	  END')

Set @TABLE = 'CNF_Attribute_SaleValidity'
EXEC('IF OBJECT_ID ('''+@TABLE+'_Cache'', ''TR'') IS NOT NULL DROP TRIGGER '+@TABLE+'_Cache')
EXEC('CREATE TRIGGER [dbo].['+@TABLE+'_Cache] on [dbo].['+@TABLE+'] AFTER INSERT,DELETE,UPDATE 
      AS 
	  BEGIN  
	    Declare @Sql nvarchar(max);	
		SET NOCOUNT ON;	
		set @Sql = '''+@TABLE+''';
		EXEC otn_sp_CACHE_TABLE_update @Sql
	  END')

Set @TABLE = 'CNF_MatrixSheet_SaleValidity'
EXEC('IF OBJECT_ID ('''+@TABLE+'_Cache'', ''TR'') IS NOT NULL DROP TRIGGER '+@TABLE+'_Cache')
EXEC('CREATE TRIGGER [dbo].['+@TABLE+'_Cache] on [dbo].['+@TABLE+'] AFTER INSERT,DELETE,UPDATE 
      AS 
	  BEGIN  
	    Declare @Sql nvarchar(max);	
		SET NOCOUNT ON;	
		set @Sql = '''+@TABLE+''';
		EXEC otn_sp_CACHE_TABLE_update @Sql
	  END')

Set @TABLE = 'CNF_MatrixCellPermission'
EXEC('IF OBJECT_ID ('''+@TABLE+'_Cache'', ''TR'') IS NOT NULL DROP TRIGGER '+@TABLE+'_Cache')
EXEC('CREATE TRIGGER [dbo].['+@TABLE+'_Cache] on [dbo].['+@TABLE+'] AFTER INSERT,DELETE,UPDATE 
      AS 
	  BEGIN  
	    Declare @Sql nvarchar(max);	
		SET NOCOUNT ON;	
		set @Sql = '''+@TABLE+''';
		EXEC otn_sp_CACHE_TABLE_update @Sql
	  END')

Set @TABLE = 'CNF_Promotion'
EXEC('IF OBJECT_ID ('''+@TABLE+'_Cache'', ''TR'') IS NOT NULL DROP TRIGGER '+@TABLE+'_Cache')
EXEC('CREATE TRIGGER [dbo].['+@TABLE+'_Cache] on [dbo].['+@TABLE+'] AFTER INSERT,DELETE,UPDATE 
      AS 
	  BEGIN  
	    Declare @Sql nvarchar(max);	
		SET NOCOUNT ON;	
		set @Sql = '''+@TABLE+''';
		EXEC otn_sp_CACHE_TABLE_update @Sql
	  END')

Set @TABLE = 'CNF_PromotionItem'
EXEC('IF OBJECT_ID ('''+@TABLE+'_Cache'', ''TR'') IS NOT NULL DROP TRIGGER '+@TABLE+'_Cache')
EXEC('CREATE TRIGGER [dbo].['+@TABLE+'_Cache] on [dbo].['+@TABLE+'] AFTER INSERT,DELETE,UPDATE 
      AS 
	  BEGIN  
	    Declare @Sql nvarchar(max);	
		SET NOCOUNT ON;	
		set @Sql = '''+@TABLE+''';
		EXEC otn_sp_CACHE_TABLE_update @Sql
	  END')

Set @TABLE = 'CNF_PromotionItemRule'
EXEC('IF OBJECT_ID ('''+@TABLE+'_Cache'', ''TR'') IS NOT NULL DROP TRIGGER '+@TABLE+'_Cache')
EXEC('CREATE TRIGGER [dbo].['+@TABLE+'_Cache] on [dbo].['+@TABLE+'] AFTER INSERT,DELETE,UPDATE 
      AS 
	  BEGIN  
	    Declare @Sql nvarchar(max);	
		SET NOCOUNT ON;	
		set @Sql = '''+@TABLE+''';
		EXEC otn_sp_CACHE_TABLE_update @Sql
	  END')

Set @TABLE = 'CNF_PromotionProduct'
EXEC('IF OBJECT_ID ('''+@TABLE+'_Cache'', ''TR'') IS NOT NULL DROP TRIGGER '+@TABLE+'_Cache')
EXEC('CREATE TRIGGER [dbo].['+@TABLE+'_Cache] on [dbo].['+@TABLE+'] AFTER INSERT,DELETE,UPDATE 
      AS 
	  BEGIN  
	    Declare @Sql nvarchar(max);	
		SET NOCOUNT ON;	
		set @Sql = '''+@TABLE+''';
		EXEC otn_sp_CACHE_TABLE_update @Sql
	  END')

Set @TABLE = 'CNF_PromotionProductCategory'
EXEC('IF OBJECT_ID ('''+@TABLE+'_Cache'', ''TR'') IS NOT NULL DROP TRIGGER '+@TABLE+'_Cache')
EXEC('CREATE TRIGGER [dbo].['+@TABLE+'_Cache] on [dbo].['+@TABLE+'] AFTER INSERT,DELETE,UPDATE 
      AS 
	  BEGIN  
	    Declare @Sql nvarchar(max);	
		SET NOCOUNT ON;	
		set @Sql = '''+@TABLE+''';
		EXEC otn_sp_CACHE_TABLE_update @Sql
	  END')

Set @TABLE = 'CNF_PromotionValidity'
EXEC('IF OBJECT_ID ('''+@TABLE+'_Cache'', ''TR'') IS NOT NULL DROP TRIGGER '+@TABLE+'_Cache')
EXEC('CREATE TRIGGER [dbo].['+@TABLE+'_Cache] on [dbo].['+@TABLE+'] AFTER INSERT,DELETE,UPDATE 
      AS 
	  BEGIN  
	    Declare @Sql nvarchar(max);	
		SET NOCOUNT ON;	
		set @Sql = '''+@TABLE+''';
		EXEC otn_sp_CACHE_TABLE_update @Sql
	  END')

Set @TABLE = 'CNF_PromotionEvent'
EXEC('IF OBJECT_ID ('''+@TABLE+'_Cache'', ''TR'') IS NOT NULL DROP TRIGGER '+@TABLE+'_Cache')
EXEC('CREATE TRIGGER [dbo].['+@TABLE+'_Cache] on [dbo].['+@TABLE+'] AFTER INSERT,DELETE,UPDATE 
      AS 
	  BEGIN  
	    Declare @Sql nvarchar(max);	
		SET NOCOUNT ON;	
		set @Sql = '''+@TABLE+''';
		EXEC otn_sp_CACHE_TABLE_update @Sql
	  END')

Set @TABLE = 'CNF_PromotionPermission'
EXEC('IF OBJECT_ID ('''+@TABLE+'_Cache'', ''TR'') IS NOT NULL DROP TRIGGER '+@TABLE+'_Cache')
EXEC('CREATE TRIGGER [dbo].['+@TABLE+'_Cache] on [dbo].['+@TABLE+'] AFTER INSERT,DELETE,UPDATE 
      AS 
	  BEGIN  
	    Declare @Sql nvarchar(max);	
		SET NOCOUNT ON;	
		set @Sql = '''+@TABLE+''';
		EXEC otn_sp_CACHE_TABLE_update @Sql
	  END')

Set @TABLE = 'CNF_SeatCategory_Permission'
EXEC('IF OBJECT_ID ('''+@TABLE+'_Cache'', ''TR'') IS NOT NULL DROP TRIGGER '+@TABLE+'_Cache')
EXEC('CREATE TRIGGER [dbo].['+@TABLE+'_Cache] on [dbo].['+@TABLE+'] AFTER INSERT,DELETE,UPDATE 
      AS 
	  BEGIN  
	    Declare @Sql nvarchar(max);	
		SET NOCOUNT ON;	
		set @Sql = '''+@TABLE+''';
		EXEC otn_sp_CACHE_TABLE_update @Sql
	  END')

Set @TABLE = 'CNF_DocTemplate_Permission'
EXEC('IF OBJECT_ID ('''+@TABLE+'_Cache'', ''TR'') IS NOT NULL DROP TRIGGER '+@TABLE+'_Cache')
EXEC('CREATE TRIGGER [dbo].['+@TABLE+'_Cache] on [dbo].['+@TABLE+'] AFTER INSERT,DELETE,UPDATE 
      AS 
	  BEGIN  
	    Declare @Sql nvarchar(max);	
		SET NOCOUNT ON;	
		set @Sql = '''+@TABLE+''';
		EXEC otn_sp_CACHE_TABLE_update @Sql
	  END')

Set @TABLE = 'CNF_DmgCategory_Permission'
EXEC('IF OBJECT_ID ('''+@TABLE+'_Cache'', ''TR'') IS NOT NULL DROP TRIGGER '+@TABLE+'_Cache')
EXEC('CREATE TRIGGER [dbo].['+@TABLE+'_Cache] on [dbo].['+@TABLE+'] AFTER INSERT,DELETE,UPDATE 
      AS 
	  BEGIN  
	    Declare @Sql nvarchar(max);	
		SET NOCOUNT ON;	
		set @Sql = '''+@TABLE+''';
		EXEC otn_sp_CACHE_TABLE_update @Sql
	  END')

Set @TABLE = 'CNF_DmgCategory'
EXEC('IF OBJECT_ID ('''+@TABLE+'_Cache'', ''TR'') IS NOT NULL DROP TRIGGER '+@TABLE+'_Cache')
EXEC('CREATE TRIGGER [dbo].['+@TABLE+'_Cache] on [dbo].['+@TABLE+'] AFTER INSERT,DELETE,UPDATE 
      AS 
	  BEGIN  
	    Declare @Sql nvarchar(max);	
		SET NOCOUNT ON;	
		set @Sql = '''+@TABLE+''';
		EXEC otn_sp_CACHE_TABLE_update @Sql
	  END')

Set @TABLE = 'CNF_Attribute'
EXEC('IF OBJECT_ID ('''+@TABLE+'_Cache'', ''TR'') IS NOT NULL DROP TRIGGER '+@TABLE+'_Cache')
EXEC('CREATE TRIGGER [dbo].['+@TABLE+'_Cache] on [dbo].['+@TABLE+'] AFTER INSERT,DELETE,UPDATE 
      AS 
	  BEGIN  
	    Declare @Sql nvarchar(max);	
		SET NOCOUNT ON;	
		set @Sql = '''+@TABLE+''';
		EXEC otn_sp_CACHE_TABLE_update @Sql
	  END')

Set @TABLE = 'CNF_AttributeTemplate'
EXEC('IF OBJECT_ID ('''+@TABLE+'_Cache'', ''TR'') IS NOT NULL DROP TRIGGER '+@TABLE+'_Cache')
EXEC('CREATE TRIGGER [dbo].['+@TABLE+'_Cache] on [dbo].['+@TABLE+'] AFTER INSERT,DELETE,UPDATE 
      AS 
	  BEGIN  
	    Declare @Sql nvarchar(max);	
		SET NOCOUNT ON;	
		set @Sql = '''+@TABLE+''';
		EXEC otn_sp_CACHE_TABLE_update @Sql
	  END')

Set @TABLE = 'CNF_AttributeSet'
EXEC('IF OBJECT_ID ('''+@TABLE+'_Cache'', ''TR'') IS NOT NULL DROP TRIGGER '+@TABLE+'_Cache')
EXEC('CREATE TRIGGER [dbo].['+@TABLE+'_Cache] on [dbo].['+@TABLE+'] AFTER INSERT,DELETE,UPDATE 
      AS 
	  BEGIN  
	    Declare @Sql nvarchar(max);	
		SET NOCOUNT ON;	
		set @Sql = '''+@TABLE+''';
		EXEC otn_sp_CACHE_TABLE_update @Sql
	  END')

Set @TABLE = 'CNF_MatrixSheet'
EXEC('IF OBJECT_ID ('''+@TABLE+'_Cache'', ''TR'') IS NOT NULL DROP TRIGGER '+@TABLE+'_Cache')
EXEC('CREATE TRIGGER [dbo].['+@TABLE+'_Cache] on [dbo].['+@TABLE+'] AFTER INSERT,DELETE,UPDATE 
      AS 
	  BEGIN  
	    Declare @Sql nvarchar(max);	
		SET NOCOUNT ON;	
		set @Sql = '''+@TABLE+''';
		EXEC otn_sp_CACHE_TABLE_update @Sql
	  END')

Set @TABLE = 'CNF_MatrixCell'
EXEC('IF OBJECT_ID ('''+@TABLE+'_Cache'', ''TR'') IS NOT NULL DROP TRIGGER '+@TABLE+'_Cache')
EXEC('CREATE TRIGGER [dbo].['+@TABLE+'_Cache] on [dbo].['+@TABLE+'] AFTER INSERT,DELETE,UPDATE 
      AS 
	  BEGIN  
	    Declare @Sql nvarchar(max);	
		SET NOCOUNT ON;	
		set @Sql = '''+@TABLE+''';
		EXEC otn_sp_CACHE_TABLE_update @Sql
	  END')

Set @TABLE = 'CNF_UpSell_Permission'
EXEC('IF OBJECT_ID ('''+@TABLE+'_Cache'', ''TR'') IS NOT NULL DROP TRIGGER '+@TABLE+'_Cache')
EXEC('CREATE TRIGGER [dbo].['+@TABLE+'_Cache] on [dbo].['+@TABLE+'] AFTER INSERT,DELETE,UPDATE 
      AS 
	  BEGIN  
	    Declare @Sql nvarchar(max);	
		SET NOCOUNT ON;	
		set @Sql = '''+@TABLE+''';
		EXEC otn_sp_CACHE_TABLE_update @Sql
	  END')
     
Set @TABLE = 'CNF_Performance_Permission'
EXEC('IF OBJECT_ID ('''+@TABLE+'_Cache'', ''TR'') IS NOT NULL DROP TRIGGER '+@TABLE+'_Cache')
EXEC('CREATE TRIGGER [dbo].['+@TABLE+'_Cache] on [dbo].['+@TABLE+'] AFTER INSERT,DELETE,UPDATE 
      AS 
	  BEGIN  
	    Declare @Sql nvarchar(max);	
		SET NOCOUNT ON;	
		set @Sql = '''+@TABLE+''';
		EXEC otn_sp_CACHE_TABLE_update @Sql
	  END')     
    
Set @TABLE = 'CNF_MatrixCellInfo'
EXEC('IF OBJECT_ID ('''+@TABLE+'_Cache'', ''TR'') IS NOT NULL DROP TRIGGER '+@TABLE+'_Cache')
EXEC('CREATE TRIGGER [dbo].['+@TABLE+'_Cache] on [dbo].['+@TABLE+'] AFTER INSERT,DELETE,UPDATE 
      AS 
	  BEGIN  
	    Declare @Sql nvarchar(max);	
		SET NOCOUNT ON;	
		set @Sql = '''+@TABLE+''';
		EXEC otn_sp_CACHE_TABLE_update @Sql
	  END')     

Set @TABLE = 'CNF_ProductValidity'
EXEC('IF OBJECT_ID ('''+@TABLE+'_Cache'', ''TR'') IS NOT NULL DROP TRIGGER '+@TABLE+'_Cache')
EXEC('CREATE TRIGGER [dbo].['+@TABLE+'_Cache] on [dbo].['+@TABLE+'] AFTER INSERT,DELETE,UPDATE 
      AS 
	  BEGIN  
	    Declare @Sql nvarchar(max);	
		SET NOCOUNT ON;	
		set @Sql = '''+@TABLE+''';
		EXEC otn_sp_CACHE_TABLE_update @Sql
	  END')


Set @TABLE = 'CNF_ProductValidity2Event'
EXEC('IF OBJECT_ID ('''+@TABLE+'_Cache'', ''TR'') IS NOT NULL DROP TRIGGER '+@TABLE+'_Cache')
EXEC('CREATE TRIGGER [dbo].['+@TABLE+'_Cache] on [dbo].['+@TABLE+'] AFTER INSERT,DELETE,UPDATE 
      AS 
	  BEGIN  
	    Declare @Sql nvarchar(max);	
		SET NOCOUNT ON;	
		set @Sql = '''+@TABLE+''';
		EXEC otn_sp_CACHE_TABLE_update @Sql
	  END')
     
Set @TABLE = 'CNF_Multilanguage'
EXEC('IF OBJECT_ID ('''+@TABLE+'_Cache'', ''TR'') IS NOT NULL DROP TRIGGER '+@TABLE+'_Cache')
EXEC('CREATE TRIGGER [dbo].['+@TABLE+'_Cache] on [dbo].['+@TABLE+'] AFTER INSERT,DELETE,UPDATE 
      AS 
	  BEGIN  
	    Declare @Sql nvarchar(max);	
		SET NOCOUNT ON;	
		set @Sql = '''+@TABLE+''';
		EXEC otn_sp_CACHE_TABLE_update @Sql
	  END')  
     

Set @TABLE = 'DATA_Right'
EXEC('IF OBJECT_ID ('''+@TABLE+'_Cache'', ''TR'') IS NOT NULL DROP TRIGGER '+@TABLE+'_Cache')
EXEC('CREATE TRIGGER [dbo].['+@TABLE+'_Cache] on [dbo].['+@TABLE+'] AFTER INSERT,DELETE,UPDATE 
      AS 
	  BEGIN  
	    Declare @Sql nvarchar(max);	
		SET NOCOUNT ON;	
		set @Sql = '''+@TABLE+''';
		EXEC otn_sp_CACHE_TABLE_update @Sql
	  END')

Set @TABLE = 'CNF_DocTemplate'
EXEC('IF OBJECT_ID ('''+@TABLE+'_Cache'', ''TR'') IS NOT NULL DROP TRIGGER '+@TABLE+'_Cache')
EXEC('CREATE TRIGGER [dbo].['+@TABLE+'_Cache] on [dbo].['+@TABLE+'] AFTER INSERT,DELETE,UPDATE 
      AS 
	  BEGIN  
	    Declare @Sql nvarchar(max);	
		SET NOCOUNT ON;	
		set @Sql = '''+@TABLE+''';
		EXEC otn_sp_CACHE_TABLE_update @Sql
	  END')
     
Set @TABLE = 'CNF_TicketPackageGroupPermission'
EXEC('IF OBJECT_ID ('''+@TABLE+'_Cache'', ''TR'') IS NOT NULL DROP TRIGGER '+@TABLE+'_Cache')
EXEC('CREATE TRIGGER [dbo].['+@TABLE+'_Cache] on [dbo].['+@TABLE+'] AFTER INSERT,DELETE,UPDATE 
      AS 
	  BEGIN  
	    Declare @Sql nvarchar(max);	
		SET NOCOUNT ON;	
		set @Sql = '''+@TABLE+''';
		EXEC otn_sp_CACHE_TABLE_update @Sql
	  END')  
	  
Set @TABLE = 'CNF_Delivery_Permission'
EXEC('IF OBJECT_ID ('''+@TABLE+'_Cache'', ''TR'') IS NOT NULL DROP TRIGGER '+@TABLE+'_Cache')
EXEC('CREATE TRIGGER [dbo].['+@TABLE+'_Cache] on [dbo].['+@TABLE+'] AFTER INSERT,DELETE,UPDATE 
      AS 
	  BEGIN  
	    Declare @Sql nvarchar(max);	
		SET NOCOUNT ON;	
		set @Sql = '''+@TABLE+''';
		EXEC otn_sp_CACHE_TABLE_update @Sql
	  END')

Set @TABLE = 'CNF_ShopCartValidation_Permission'
EXEC('IF OBJECT_ID ('''+@TABLE+'_Cache'', ''TR'') IS NOT NULL DROP TRIGGER '+@TABLE+'_Cache')
EXEC('CREATE TRIGGER [dbo].['+@TABLE+'_Cache] on [dbo].['+@TABLE+'] AFTER INSERT,DELETE,UPDATE 
      AS 
	  BEGIN  
	    Declare @Sql nvarchar(max);	
		SET NOCOUNT ON;	
		set @Sql = '''+@TABLE+''';
		EXEC otn_sp_CACHE_TABLE_update @Sql
	  END')
     
Set @TABLE = 'CNF_TravelTime'
EXEC('IF OBJECT_ID ('''+@TABLE+'_Cache'', ''TR'') IS NOT NULL DROP TRIGGER '+@TABLE+'_Cache')
EXEC('CREATE TRIGGER [dbo].['+@TABLE+'_Cache] on [dbo].['+@TABLE+'] AFTER INSERT,DELETE,UPDATE 
      AS 
	  BEGIN  
	    Declare @Sql nvarchar(max);	
		SET NOCOUNT ON;	
		set @Sql = '''+@TABLE+''';
		EXEC otn_sp_CACHE_TABLE_update @Sql
	  END')  	  
	  
Set @TABLE = 'CNF_TravelMatrix'
EXEC('IF OBJECT_ID ('''+@TABLE+'_Cache'', ''TR'') IS NOT NULL DROP TRIGGER '+@TABLE+'_Cache')
EXEC('CREATE TRIGGER [dbo].['+@TABLE+'_Cache] on [dbo].['+@TABLE+'] AFTER INSERT,DELETE,UPDATE 
      AS 
	  BEGIN  
	    Declare @Sql nvarchar(max);	
		SET NOCOUNT ON;	
		set @Sql = '''+@TABLE+''';
		EXEC otn_sp_CACHE_TABLE_update @Sql
	  END')
    
Set @TABLE = 'CNF_SuggestiveSell_Permission'
EXEC('IF OBJECT_ID ('''+@TABLE+'_Cache'', ''TR'') IS NOT NULL DROP TRIGGER '+@TABLE+'_Cache')
EXEC('CREATE TRIGGER [dbo].['+@TABLE+'_Cache] on [dbo].['+@TABLE+'] AFTER INSERT,DELETE,UPDATE 
      AS 
	  BEGIN  
	    Declare @Sql nvarchar(max);	
		SET NOCOUNT ON;	
		set @Sql = '''+@TABLE+''';
		EXEC otn_sp_CACHE_TABLE_update @Sql
	  END')  	  </SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>sloporto</ADDEDBY><SQLVERSION>3349</SQLVERSION><RMTRACKLINK>IDBOS-6637</RMTRACKLINK><REASON>Script 0= Changed  CNF_MatrixCellInfo.QuickUpgradeIds from nvarchar(1000) to nvarchar(MAX) 
Script 1 = fixed MatrixCell with QuickUpgradeIds great than 1000</REASON><TABLENAMES>CNF_MatrixCellInfo=MatrixCellInfoId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT * FROM sys.columns
  WHERE Name = N'QuickUpgradeIds'
  AND OBJECT_ID = OBJECT_ID(N'CNF_MatrixCellInfo'))
BEGIN
  ALTER TABLE CNF_MAtrixCellInfo 
  ALTER COLUMN QuickUpgradeIds nvarchar(max)
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>UPDATE CNF_MatrixCellInfo set QuickUpgradeIds = 
	STUFF((SELECT ',' + CAST(t.QuickUpgradeMatrixCellId as VARCHAR(MAX))
               FROM CNF_MatrixCell_QuickUpgrade t
			   WHERE t.MatrixCellId = CNF_MatrixCellInfo.MatrixCellId
               FOR XML PATH ('')
              ), 1, 1, '')
WHERE CNF_MatrixCellInfo.MatrixCellId in 
(SELECT I.MatrixCellId FROM
CNF_MatrixCellInfo I INNER JOIN 
(SELECT MatrixCellId, 	stuff((SELECT ',' + cast(t.QuickUpgradeMatrixCellId AS VARCHAR(max))
               FROM CNF_MatrixCell_QuickUpgrade t
			   WHERE t.MatrixCellId = e.MatrixCellId
               FOR XML path ('')
              ), 1, 1, '') QuickUpgradeIds
FROM 
	CNF_MatrixCell_QuickUpgrade e
GROUP BY 
	MatrixCellId) T on I.MatrixCellId = T.MatrixCellId
WHERE
	I.QuickUpgradeIds &lt;&gt; T.QuickUpgradeIds and LEN(I.QuickUpgradeIds) &gt;= 1000
)</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>3348</SQLVERSION><RMTRACKLINK>IDBOSS-6640</RMTRACKLINK><REASON></REASON><TABLENAMES>CNF_Calendar=CalendarId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT * FROM sys.columns
  WHERE Name = N'DefaultMonth'
  AND OBJECT_ID = OBJECT_ID(N'CNF_Calendar'))
BEGIN
  ALTER TABLE CNF_Calendar
  DROP COLUMN DefaultMonth
END </SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>sloporto</ADDEDBY><SQLVERSION>3347</SQLVERSION><RMTRACKLINK>IDBOS-6458</RMTRACKLINK><REASON>Script 0 - Create Filed DmgCategoryId as Foreign key of CNF_DmgCategory</REASON><TABLENAMES>CNF_Attribute=AttributeId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
  WHERE Name = N'DmgCategoryId'
  AND OBJECT_ID = OBJECT_ID(N'CNF_Attribute'))
BEGIN
  ALTER TABLE CNF_Attribute ADD DmgCategoryId int NULL;
  ALTER TABLE CNF_Attribute WITH CHECK ADD FOREIGN KEY(DmgCategoryId)  REFERENCES CNF_DmgCategory (DmgCategoryId);
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>sloporto</ADDEDBY><SQLVERSION>3346</SQLVERSION><RMTRACKLINK>IDBOS-6456</RMTRACKLINK><REASON>script 0 -&gt; Add Field HasCalendar boolean not null default 0
Script 1 -&gt; Add Field CalendarEventId integer
Script 2 -&gt; Add Field EventIdList nvarchar(200)
Script 3 -&gt; Add Field AttributeTemplateId integer</REASON><TABLENAMES>CNF_StatisticalGroup=StatisticalGroupId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
  WHERE Name = N'HasCalendar'
  AND OBJECT_ID = OBJECT_ID(N'CNF_StatisticalGroup'))
BEGIN
  ALTER TABLE CNF_StatisticalGroup
  ADD HasCalendar smallint DEFAULT 0 NOT NULL
END </SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
  WHERE Name = N'CalendarEventId'
  AND OBJECT_ID = OBJECT_ID(N'CNF_StatisticalGroup'))
BEGIN
  ALTER TABLE CNF_StatisticalGroup
  ADD CalendarEventId int NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
  WHERE Name = N'EventIdList'
  AND OBJECT_ID = OBJECT_ID(N'CNF_StatisticalGroup'))
BEGIN
  ALTER TABLE CNF_StatisticalGroup
  ADD EventIdList nvarchar(200) NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
  WHERE Name = N'AttributeTemplateId'
  AND OBJECT_ID = OBJECT_ID(N'CNF_StatisticalGroup'))
BEGIN
  ALTER TABLE CNF_StatisticalGroup
  ADD AttributeTemplateId int NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>3345</SQLVERSION><RMTRACKLINK>IDBOS-6567</RMTRACKLINK><REASON></REASON><TABLENAMES>CNF_Calendar=CalendarId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT * FROM sys.columns
  WHERE Name = N'DontIncludeLastDay'
  AND OBJECT_ID = OBJECT_ID(N'CNF_Calendar'))
BEGIN
  ALTER TABLE CNF_Calendar
  DROP COLUMN DontIncludeLastDay 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT * FROM sys.columns
  WHERE Name = N'LastDayEndTime'
  AND OBJECT_ID = OBJECT_ID(N'CNF_Calendar'))
BEGIN
  ALTER TABLE CNF_Calendar
  DROP COLUMN LastDayEndTime 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
  WHERE Name = N'DontIncludeLastDay'
  AND OBJECT_ID = OBJECT_ID(N'CNF_Calendar'))
BEGIN
  ALTER TABLE CNF_Calendar
  ADD DontIncludeLastDay Smallint NULL
END </SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
  WHERE Name = N'LastDayEndTime'
  AND OBJECT_ID = OBJECT_ID(N'CNF_Calendar'))
BEGIN
  ALTER TABLE CNF_Calendar
  ADD LastDayEndTime Datetime NULL
END </SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>3344</SQLVERSION><RMTRACKLINK>IDBOS-6567</RMTRACKLINK><REASON></REASON><TABLENAMES>CNF_Calendar=CalendarId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
  WHERE Name = N'DontIncludeLastDay'
  AND OBJECT_ID = OBJECT_ID(N'CNF_Calendar'))
BEGIN
  ALTER TABLE CNF_Calendar
  ADD DontIncludeLastDay Datetime NULL
END </SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
  WHERE Name = N'LastDayEndTime'
  AND OBJECT_ID = OBJECT_ID(N'CNF_Calendar'))
BEGIN
  ALTER TABLE CNF_Calendar
  ADD LastDayEndTime Datetime NULL
END </SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>nchinea</ADDEDBY><SQLVERSION>3343</SQLVERSION><RMTRACKLINK>IDBOS-6244</RMTRACKLINK><REASON>0 - Delete Table DATA_PaymentExternalDetail
1 - Ricreate table
2 - Create FK index</REASON><TABLENAMES>DATA_PaymentExternalDetail=PaymentExternalDetailId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT * 
              FROM INFORMATION_SCHEMA.TABLES
              WHERE TABLE_SCHEMA = 'dbo'
              AND TABLE_NAME = 'DATA_PaymentExternalDetail')
BEGIN
  DROP TABLE DATA_PaymentExternalDetail
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * 
              FROM INFORMATION_SCHEMA.TABLES
              WHERE TABLE_SCHEMA = 'dbo'
              AND TABLE_NAME = 'DATA_PaymentExternalDetail')
BEGIN
CREATE TABLE [DATA_PaymentExternalDetail](
	[PaymentExternalDetailId] int IDENTITY(1,1) NOT NULL,
	[PaymentId] int NOT NULL,
	[DetailType] int NOT NULL,
	[EntityType] int NOT NULL,
	[EntityId] nvarchar(200) NULL,
	[Code] nvarchar(200) NULL,
	[UnitAmount] float NOT NULL,
	[Quantity] int NOT NULL,
	[TotalAmount] float NOT NULL,
	[Description1] nvarchar(200) NULL,
	[Description2] nvarchar(200) NULL,
	[ExtraInfo_xml] nvarchar(max) NULL,
	[NetAmountUnit] float NULL,
	[NetAmountTotal] float NULL,
	[ServiceInfo] nvarchar(200) NULL,
	[MatrixCellId] int NULL,
  Primary Key ([PaymentExternalDetailId])
) 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT * 
              FROM INFORMATION_SCHEMA.TABLES
              WHERE TABLE_SCHEMA = 'dbo'
              AND TABLE_NAME = 'DATA_PaymentExternalDetail')
BEGIN
	ALTER TABLE DATA_PaymentExternalDetail WITH CHECK ADD FOREIGN KEY(PaymentId)
	REFERENCES DATA_Payment (PaymentId)
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>sloporto</ADDEDBY><SQLVERSION>3342</SQLVERSION><RMTRACKLINK>IDBOS-6460</RMTRACKLINK><REASON>Script 0 - Add Field PrimaryEventId
Script 1- Add Field PrimaryEventTimeSpan</REASON><TABLENAMES>CNF_Event=EventId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
  WHERE Name = N'PrimaryEventId'
  AND OBJECT_ID = OBJECT_ID(N'CNF_Event'))
BEGIN
  ALTER TABLE CNF_Event
  ADD PrimaryEventId int NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
  WHERE Name = N'PrimaryEventTimeSpan'
  AND OBJECT_ID = OBJECT_ID(N'CNF_Event'))
BEGIN
  ALTER TABLE CNF_Event
  ADD PrimaryEventTimeSpan int NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dchen</ADDEDBY><SQLVERSION>3341</SQLVERSION><RMTRACKLINK>IDBOS-4466</RMTRACKLINK><REASON>IDBOS-4466 - SOW: Access Control Override 
==============================================================
1) Re - Create New Table
2) Insert Initial Value</REASON><TABLENAMES>CNF_ValidateOverrideWhitelist=ValidateWhitelistID</TABLENAMES><SQLSCRIPTLIST><SCRIPT>DELETE FROM CNF_RIGHT WHERE RIGHTAK LIKE '%ValidateOverride%' 

IF EXISTS (SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND TABLE_NAME = 'CNF_ValidateOverrideWhitelist')
BEGIN
  DROP TABLE CNF_ValidateOverrideWhitelist
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND TABLE_NAME = 'CNF_ValidateOverrideWhitelist')
BEGIN
  CREATE TABLE CNF_ValidateOverrideWhitelist
  (
	ValidateWhitelistID int IDENTITY(1,1) NOT NULL,
	ValidateResult int NOT NULL,
        ValidateDescription NVarChar(100)
    PRIMARY KEY (ValidateWhitelistID)
  )
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>scoluccia</ADDEDBY><SQLVERSION>3340</SQLVERSION><RMTRACKLINK>IDBOS-5537</RMTRACKLINK><REASON>- Added the Column "ShopCartValidationType" to the Table CNF_ShopCartValidation
- Added some records for CNF_ShopCartValidation configuration to the Table SYS_CacheTable
- Added some triggers for cache management</REASON><TABLENAMES>CNF_ShopCartValidation=ShopCartValidationID</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
          WHERE Name = N'ShopCartValidationType' 
          AND OBJECT_ID = OBJECT_ID(N'CNF_ShopCartValidation'))
BEGIN
  ALTER TABLE CNF_ShopCartValidation
  ADD [ShopCartValidationType] smallint DEFAULT 1 NOT NULL
END

</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>3339</SQLVERSION><RMTRACKLINK>IDBOS-6244-45</RMTRACKLINK><REASON>0=Create table
1=Create foreign key</REASON><TABLENAMES>DATA_PaymentExternalDetail=PaymentExternalDetailId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * 
              FROM INFORMATION_SCHEMA.TABLES
              WHERE TABLE_SCHEMA = 'dbo'
              AND TABLE_NAME = 'DATA_PaymentExternalDetail')
BEGIN
  Create table [DATA_PaymentExternalDetail]
  (
	[PaymentExternalDetailId] Integer NOT NULL,
	[PaymentId] Integer NOT NULL,
	[DetailType] Integer NOT NULL,
	[EntityType] Integer NOT NULL,
	[EntityId] Nvarchar(10) NULL,
	[Code] Nvarchar(10) NULL,
	[UnitAmount] Float NOT NULL,
	[Quantity] Integer NOT NULL,
	[TotalAmount] Float NOT NULL,
	[Description1] Nvarchar(200) NULL,
	[Description2] Nvarchar(200) NULL,
	[ExtraInfo_xml] Nvarchar(max) NULL,
	[MatrixCellId] Integer NULL,
	[ServiceInfo] Nvarchar(200) NULL,
	[NetAmountUnit] Float NULL,
	[NetAmountTotal] Float NULL,
  Primary Key ([PaymentExternalDetailId])
) 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT * 
              FROM INFORMATION_SCHEMA.TABLES
              WHERE TABLE_SCHEMA = 'dbo'
              AND TABLE_NAME = 'DATA_PaymentExternalDetail')
BEGIN
	ALTER TABLE DATA_PaymentExternalDetail WITH CHECK ADD FOREIGN KEY(PaymentId)
	REFERENCES DATA_Payment (PaymentId)
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>3338</SQLVERSION><RMTRACKLINK>IDBOS-6412</RMTRACKLINK><REASON>Re-doing patch 3336</REASON><TABLENAMES>CNF_Calendar=CalendarId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
  WHERE Name = N'DefaultMonth'
  AND OBJECT_ID = OBJECT_ID(N'CNF_Calendar'))
BEGIN
  ALTER TABLE CNF_Calendar
  ADD DefaultMonth Smallint NULL
END </SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>nchinea</ADDEDBY><SQLVERSION>3337</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>Dummy</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>3336</SQLVERSION><RMTRACKLINK>IDBOS-6412</RMTRACKLINK><REASON></REASON><TABLENAMES>CNF_Calendar=CalendarId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
  WHERE Name = N'DateRange'
  AND OBJECT_ID = OBJECT_ID(N'CNF_Calendar'))
BEGIN
  ALTER TABLE CNF_Calendar
  ADD DefaultMonth Smallint NULL
END </SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>nchinea</ADDEDBY><SQLVERSION>3335</SQLVERSION><RMTRACKLINK>IDBOS-6244-45</RMTRACKLINK><REASON>Dummy... see 3339</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>3334</SQLVERSION><RMTRACKLINK>IDBOS-6040</RMTRACKLINK><REASON></REASON><TABLENAMES>CNF_DatePrice=DatePriceId
CNF_Calendar=CalendarId
CNF_MatrixCellInfo=MatrixCellInfoId
CNF_CalendarShortcut=CalendarShortcutId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * 
              FROM INFORMATION_SCHEMA.TABLES
              WHERE TABLE_SCHEMA = 'dbo'
              AND TABLE_SCHEMA = 'CNF_DatePrice')
BEGIN
	Create table [CNF_DatePrice]
	(
		[DatePriceId] Integer Identity(1,1) NOT NULL,
		[MatrixCellId] Integer NOT NULL,
		[CalendarId] Integer NOT NULL,
		[Price] Float NULL,
		[Date] Datetime NULL,
		[Last_UserId_Log] Integer NULL,
		[Last_WorkstationId_Log] Integer NULL,
		[Last_DateTime_Log] Datetime NULL,
	Primary Key ([DatePriceId])
	) 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
  WHERE Name = N'ConfigurePriceByDate'
  AND OBJECT_ID = OBJECT_ID(N'CNF_Calendar'))
BEGIN
  ALTER TABLE CNF_Calendar
  ADD ConfigurePriceByDate Smallint NULL
END </SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
  WHERE Name = N'CalendarId'
  AND OBJECT_ID = OBJECT_ID(N'CNF_MatrixCellInfo'))
BEGIN
  ALTER TABLE CNF_MatrixCellInfo
  ADD CalendarId Smallint NULL
END </SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * 
              FROM INFORMATION_SCHEMA.TABLES
              WHERE TABLE_SCHEMA = 'dbo'
              AND TABLE_SCHEMA = 'CNF_CalendarShortcut')
BEGIN
  Create table CNF_CalendarShortcut
	(
		[CalendarShortcutId] Integer Identity(1,1) NOT NULL,
		[CalendarId] Integer NOT NULL,
		[Description] Nvarchar(50) NULL,
		[FromDate] Datetime NULL,
		[ToDate] Datetime NULL,
		[SortOrder] Integer NULL,
		[Last_UserId_Log] Integer NULL,
		[Last_WorkstationId_Log] Integer NULL,
		[Last_DateTime_Log] Datetime NULL,
	Primary Key ([CalendarShortcutId])
	) 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
  WHERE Name = N'DateRange'
  AND OBJECT_ID = OBJECT_ID(N'CNF_Calendar'))
BEGIN
  ALTER TABLE CNF_Calendar
  ADD DateRange Smallint NULL
END </SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>pchen</ADDEDBY><SQLVERSION>3333</SQLVERSION><RMTRACKLINK>IDBOS-6041</RMTRACKLINK><REASON>New field on CNF_Promotion: CheckByDateRange
New field on CNF_PromotionItemRule: MinDayRange, MaxDayRange</REASON><TABLENAMES>CNF_Promotion=PromotionId
CNF_PromotionItemRule=PromotionItemRuleId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
  WHERE Name = N'CheckByDateRange'
  AND OBJECT_ID = OBJECT_ID(N'CNF_Promotion'))
BEGIN
  ALTER TABLE CNF_Promotion
  ADD CheckByDateRange smallint NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
  WHERE Name = N'MinDayRange'
  AND OBJECT_ID = OBJECT_ID(N'CNF_PromotionItemRule'))
BEGIN
  ALTER TABLE CNF_PromotionItemRule
  ADD MinDayRange int NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
  WHERE Name = N'MaxDayRange'
  AND OBJECT_ID = OBJECT_ID(N'CNF_PromotionItemRule'))
BEGIN
  ALTER TABLE CNF_PromotionItemRule
  ADD MaxDayRange int NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>sloporto</ADDEDBY><SQLVERSION>3332</SQLVERSION><RMTRACKLINK>IDBOS-6246</RMTRACKLINK><REASON>Script 0= Changed  CNF_MatrixCellInfo.QuickRenewIds from nvarchar(1000) to nvarchar(MAX) 
Script 1 = fixed MatrixCell with QuickRenewIds great than 1000</REASON><TABLENAMES>CNF_MatrixCellInfo=MatrixCellInfoId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT * FROM sys.columns
  WHERE Name = N'QuickRenewIds'
  AND OBJECT_ID = OBJECT_ID(N'CNF_MatrixCellInfo'))
BEGIN
  ALTER TABLE CNF_MAtrixCellInfo 
  ALTER COLUMN QuickRenewIds nvarchar(max)
END </SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>UPDATE CNF_MatrixCellInfo set QuickRenewIds = 
	STUFF((SELECT ',' + CAST(t.RenewMatrixCellId AS VARCHAR(MAX))
               FROM CNF_MatrixCell_Renew t
			   WHERE t.MatrixCellId = CNF_MatrixCellInfo.MatrixCellId
               FOR XML PATH ('')
              ), 1, 1, '')
WHERE CNF_MatrixCellInfo.MatrixCellId in 
(SELECT I.MatrixCellId FROM
CNF_MatrixCellInfo I INNER JOIN 
(SELECT MatrixCellId, 	stuff((SELECT ',' + cast(t.RenewMatrixCellId AS VARCHAR(max))
               FROM CNF_MatrixCell_Renew t
			   WHERE t.MatrixCellId = e.MatrixCellId
               FOR XML path ('')
              ), 1, 1, '') RenewIds
FROM 
	CNF_MatrixCell_Renew e
GROUP BY 
	MatrixCellId) T on I.MatrixCellId = T.MatrixCellId
WHERE
	I.QuickRenewIds &lt;&gt; T.RenewIds and LEN(I.QuickRenewIds) &gt;= 1000
)</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3331</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>Added some Index on these tables ( discovered during EICMA Fair )
CNF_Workstation
SIAE_SiaeLog
DATA_AptRotationCount</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
    FROM sys.indexes 
    WHERE name='IX_CNF_Workstation_Enabled_IPAddress' AND object_id = OBJECT_ID('CNF_Workstation')
)
BEGIN
    CREATE INDEX [IX_CNF_Workstation_Enabled_IPAddress] on [CNF_Workstation] ([Enabled],[IPAddress]) INCLUDE ([WorkstationId], [WorkstationAK], [ConnectionPort])
END;

IF NOT EXISTS (SELECT * 
    FROM sys.indexes 
    WHERE name='IX_SIAE_SiaeLog_Operazione_Sigillo' AND object_id = OBJECT_ID('SIAE_SiaeLog')
)
BEGIN
    CREATE INDEX [IX_SIAE_SiaeLog_Operazione_Sigillo] on [SIAE_SiaeLog] ([Operazione], [Sigillo])
END;

IF NOT EXISTS (SELECT * 
    FROM sys.indexes 
    WHERE name='IX_DATA_AptRotationCount_WorkstationId_SaveDateTime' AND object_id = OBJECT_ID('DATA_AptRotationCount')
)
BEGIN
    CREATE INDEX [IX_DATA_AptRotationCount_WorkstationId_SaveDateTime] on [DATA_AptRotationCount] ([WorkstationId],[SaveDateTime]) INCLUDE ([ControlledEntriesCount], [ControlledExitsCount], [FreeEntriesCount], [FreeExitsCount])
END;</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>ecandido</ADDEDBY><SQLVERSION>3330</SQLVERSION><RMTRACKLINK>IDBOS-5705</RMTRACKLINK><REASON>Create Field  TipsCOAAccountID related to the Chart of Account</REASON><TABLENAMES>CNF_PaymentMethod=PaymentMethodID</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'TipsCOAAccountID' AND
                Object_ID  = Object_ID(N'CNF_PaymentMethod'))
BEGIN
	Alter Table CNF_PaymentMethod
	Add TipsCOAAccountID Integer NULL
END
</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>3329</SQLVERSION><RMTRACKLINK>92684</RMTRACKLINK><REASON></REASON><TABLENAMES>DATA_Account=AccountId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
              WHERE Name = N'CardNames'
              AND OBJECT_ID = OBJECT_ID(N'DATA_Account'))
BEGIN
  ALTER TABLE DATA_Account
  ADD CardNames NVarChar(400) NULL;
END  </SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>3328</SQLVERSION><RMTRACKLINK>6170</RMTRACKLINK><REASON>COA - Add the ability to assign a site to an account.</REASON><TABLENAMES>COA_CNF_Account=COAAccountID</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
		WHERE Name = N'SiteID'
		  AND OBJECT_ID = OBJECT_ID(N'COA_CNF_Account'))
BEGIN
  ALTER TABLE COA_CNF_Account
  ADD SiteID Integer NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>pchen</ADDEDBY><SQLVERSION>3327</SQLVERSION><RMTRACKLINK>IDBOS-4940</RMTRACKLINK><REASON>Add DecryptAccountCard field in CNF_System</REASON><TABLENAMES>CNF_System=SystemId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'DecryptAccountCard' 
                      AND OBJECT_ID = OBJECT_ID(N'CNF_System'))
BEGIN
  ALTER TABLE CNF_System 
  ADD DecryptAccountCard SmallInt NULL;     
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>3326</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>New field for CNF_Performance: CancellationDateTime</REASON><TABLENAMES>CNF_Performance=PerformanceId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'CancellationDateTime' 
                      AND OBJECT_ID = OBJECT_ID(N'CNF_Performance'))
BEGIN
  ALTER TABLE CNF_Performance 
  ADD CancellationDateTime DateTime NULL;     
END 
</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>3325</SQLVERSION><RMTRACKLINK>IDBOS-4467</RMTRACKLINK><REASON>New field on CNF_PaymentMethod: ToBeConfirmed
New field on DATA_Payment: ConfirmationStatus</REASON><TABLENAMES>CNF_PaymentMethod=PaymentMethodId
DATA_Payment=PaymentId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'ToBeConfirmed'
                      AND OBJECT_ID = OBJECT_ID(N'ToBeConfirmed'))
BEGIN
  ALTER TABLE CNF_PaymentMethod
  ADD ToBeConfirmed SmallInt NULL;
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'ConfirmationStatus'
                      AND OBJECT_ID = OBJECT_ID(N'DATA_Payment'))
BEGIN
  ALTER TABLE DATA_Payment
  ADD ConfirmationStatus SmallInt NULL;
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>pchen</ADDEDBY><SQLVERSION>3324</SQLVERSION><RMTRACKLINK>IDBOS-4469</RMTRACKLINK><REASON>New column UpgradePeriodByPerformance in CNF_MatrixCellInfo</REASON><TABLENAMES>CNF_MatrixCellInfo=MatrixCellInfoId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'UpgradePeriodByPerformance' 
                      AND OBJECT_ID = OBJECT_ID(N'CNF_MatrixCellInfo'))
BEGIN
  ALTER TABLE CNF_MatrixCellInfo 
  ADD UpgradePeriodByPerformance SmallInt NULL;     
END </SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>pchen</ADDEDBY><SQLVERSION>3323</SQLVERSION><RMTRACKLINK>IDBOS-4468</RMTRACKLINK><REASON>0) Create Table DATA_CashDrawerSession
1) Add Foreign Key on field UserId
2) Add Foreign Key on field WorkstationId</REASON><TABLENAMES>DATA_CashDrawerSession=SessionId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND TABLE_NAME = 'DATA_CashDrawerSession')
BEGIN
  CREATE TABLE DATA_CashDrawerSession
  (
    SessionId int IDENTITY(1,1) NOT NULL,
    UserId int NOT NULL,    
    WorkstationId int NOT NULL,
    DeviceId int NOT NULL,
    StartAmount float NULL,   
    Status SmallInt NULL,
    Last_DateTime_Log datetime NULL
    PRIMARY KEY (SessionId)
  )
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_CashDrawerSession_UserId')
BEGIN
  ALTER TABLE DATA_CashDrawerSession
  ADD  CONSTRAINT FK_DATA_CashDrawerSession_UserId FOREIGN KEY(UserId)
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_CashDrawerSession_WorkstationId')
BEGIN
  ALTER TABLE DATA_CashDrawerSession
  ADD  CONSTRAINT FK_DATA_CashDrawerSession_WorkstationId FOREIGN KEY(WorkstationId)
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>sloporto</ADDEDBY><SQLVERSION>3322</SQLVERSION><RMTRACKLINK>IDBOS-3041</RMTRACKLINK><REASON>Add PDFTemplateId Field in CNF_PaymentMethod</REASON><TABLENAMES>CNF_PaymentMethod=PaymentMethodId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'PDFTemplateId' 
                      AND OBJECT_ID = OBJECT_ID(N'CNF_PaymentMethod'))
BEGIN
  ALTER TABLE CNF_PaymentMethod 
  ADD PDFTemplateId int NULL;     
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>3321</SQLVERSION><RMTRACKLINK>IDBOS-5375</RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
          WHERE Name = N'SaleItemRuleID' 
          AND OBJECT_ID = OBJECT_ID(N'RR_Data_Revenue'))
BEGIN
  ALTER TABLE RR_Data_Revenue
  ADD SaleItemRuleID Integer NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_RR_RevenueData_batchJob]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_RR_RevenueData_batchJob</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>create Procedure [dbo].[otn_sp_RR_RevenueData_batchJob] 
	@FromDate Date,
	@ToDate Date
AS 
BEGIN
SET NOCOUNT ON
	select'Begin Batch', getdate()

	delete from rr_data_revenue
	where fcalcdate between @FromDate and @ToDate

	delete from rr_data_revenue_totals
	where fcalcdate between @FromDate and @ToDate

	Declare @BatchDate Date
	Declare @RRTransDateType Integer

	Declare @SuspendRRRId Integer
	Declare @SuspendCOAAccountId Integer
	Declare @SuspendRRCalcTypeTrigger Integer
	Declare @SuspendRRCalcTypeWhere Integer
	Declare @SuspendRRCalcTypeMethod Integer
	Declare @SuspendCOAAccountConfigId Integer
	Declare @SuspendCOAAccountTypeId Integer
	Declare @SuspendPercentage float
	Declare @SuspendDays Integer
	Declare @SuspendPrice float
	Declare @SuspendCOAAccount_Percentage Float
	Declare @SuspendRemainingValues Integer
	Declare @SuspendRRCOAAccountingType Integer
	Declare @SuspendAccountingType Integer

	Declare @PaymentRRRId Integer
	Declare @PaymentCOAAccountId Integer
	Declare @PaymentRRCalcTypeTrigger Integer
	Declare @PaymentRRCalcTypeWhere Integer
	Declare @PaymentRRCalcTypeMethod Integer
	Declare @PaymentCOAAccountConfigId Integer
	Declare @PaymentCOAAccountTypeId Integer
	Declare @PaymentPercentage float
	Declare @PaymentDays Integer
	Declare @PaymentPrice float
	Declare @PaymentCOAAccount_Percentage Float
	Declare @PaymentRemainingValues Integer
	Declare @PaymentRRCOAAccountingType Integer
	Declare @PaymentAccountingType Integer


	Declare @TaxRRRId Integer
	Declare @TaxCOAAccountId Integer
	Declare @TaxRRCalcTypeTrigger Integer
	Declare @TaxRRCalcTypeWhere Integer
	Declare @TaxRRCalcTypeMethod Integer
	Declare @TaxCOAAccountConfigId Integer
	Declare @TaxCOAAccountTypeId Integer
	Declare @TaxPercentage float
	Declare @TaxDays Integer
	Declare @TaxPrice float
	Declare @TaxCOAAccount_Percentage Float
	Declare @TaxRemainingValues Integer
	Declare @TaxRRCOAAccountingType Integer
	Declare @TaxAccountingType Integer


	Declare @DiscountRRRId Integer
	Declare @DiscountCOAAccountId Integer
	Declare @DiscountRRCalcTypeTrigger Integer
	Declare @DiscountRRCalcTypeWhere Integer
	Declare @DiscountRRCalcTypeMethod Integer
	Declare @DiscountCOAAccountConfigId Integer
	Declare @DiscountCOAAccountTypeId Integer
	Declare @DiscountPercentage float
	Declare @DiscountDays Integer
	Declare @DiscountPrice float
	Declare @DiscountCOAAccount_Percentage Float
	Declare @DiscountRemainingValues Integer
	Declare @DiscountRRCOAAccountingType Integer
	Declare @DiscountAccountingType Integer

	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer

	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1


	select @RRTransDateType = RRTransDateType
      from cnf_system

	select TOP 1	@SuspendRRRId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
					@SuspendRRCalcTypeTrigger = RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
					@SuspendRRCalcTypeWhere = RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
					@SuspendRRCalcTypeMethod = RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
					@SuspendCOAAccountConfigId = COA_CNF_AccountConfig.COAAccountConfigId,
					@SuspendCOAAccountTypeId = COA_CNF_AccountType.COAAccountTypeId,
					@SuspendCOAAccountId = coa_cnf_account.COAAccountId,
					@SuspendPercentage = RR_CNF_RevenueRecognitionRule.Percentage,
					@SuspendDays = RR_CNF_RevenueRecognitionRule.Days,
					@SuspendPrice = COA_CNF_AccountConfig.Price,
					@SuspendCOAAccount_Percentage = COA_CNF_AccountConfig.Percentage,
					@SuspendRemainingValues = COA_CNF_AccountConfig.RemainingValues,
					@SuspendRRCOAAccountingType = COA_CNF_AccountConfig.AccountingType
	from coa_cnf_account WITH(NOLOCK)
		INNER JOIN COA_CNF_AccountType WITH(NOLOCK)				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
		INNER JOIN COA_CNF_AccountConfig WITH(NOLOCK)			on COA_CNF_AccountConfig.COAAccountId = coa_cnf_account.COAAccountId
		INNER JOIN RR_CNF_RevenueRecognitionRule WITH(NOLOCK)	on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId
	where coa_cnf_account.COAAccountID = @SuspendID
	 order by RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId

	select TOP 1	@PaymentRRRId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
					@PaymentRRCalcTypeTrigger = RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
					@PaymentRRCalcTypeWhere = RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
					@PaymentRRCalcTypeMethod = RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
					@PaymentCOAAccountConfigId = COA_CNF_AccountConfig.COAAccountConfigId,
					@PaymentCOAAccountTypeId = COA_CNF_AccountType.COAAccountTypeId,
					@PaymentCOAAccountId = coa_cnf_account.COAAccountId,
					@PaymentPercentage = RR_CNF_RevenueRecognitionRule.Percentage,
					@PaymentDays = RR_CNF_RevenueRecognitionRule.Days,
					@PaymentPrice = COA_CNF_AccountConfig.Price,
					@PaymentCOAAccount_Percentage = COA_CNF_AccountConfig.Percentage,
					@PaymentRemainingValues = COA_CNF_AccountConfig.RemainingValues,
					@PaymentRRCOAAccountingType = COA_CNF_AccountConfig.AccountingType
	from coa_cnf_account WITH(NOLOCK)
		INNER JOIN COA_CNF_AccountType WITH(NOLOCK)				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
		INNER JOIN COA_CNF_AccountConfig WITH(NOLOCK)			on COA_CNF_AccountConfig.COAAccountId = coa_cnf_account.COAAccountId
		INNER JOIN RR_CNF_RevenueRecognitionRule WITH(NOLOCK)	on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId
	where coa_cnf_account.COAAccountID = @ACCPaymentMethod
	 order by RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId

	select TOP 1	@TaxRRRId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
					@TaxRRCalcTypeTrigger = RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
					@TaxRRCalcTypeWhere = RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
					@TaxRRCalcTypeMethod = RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
					@TaxCOAAccountConfigId = COA_CNF_AccountConfig.COAAccountConfigId,
					@TaxCOAAccountTypeId = COA_CNF_AccountType.COAAccountTypeId,
					@TaxCOAAccountId = coa_cnf_account.COAAccountId,
					@TaxPercentage = RR_CNF_RevenueRecognitionRule.Percentage,
					@TaxDays = RR_CNF_RevenueRecognitionRule.Days,
					@TaxPrice = COA_CNF_AccountConfig.Price,
					@TaxCOAAccount_Percentage = COA_CNF_AccountConfig.Percentage,
					@TaxRemainingValues = COA_CNF_AccountConfig.RemainingValues,
					@TaxRRCOAAccountingType = COA_CNF_AccountConfig.AccountingType
	from coa_cnf_account WITH(NOLOCK)
		INNER JOIN COA_CNF_AccountType WITH(NOLOCK)				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
		INNER JOIN COA_CNF_AccountConfig WITH(NOLOCK)			on COA_CNF_AccountConfig.COAAccountId = coa_cnf_account.COAAccountId
		INNER JOIN RR_CNF_RevenueRecognitionRule WITH(NOLOCK)	on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId
	where coa_cnf_account.COAAccountID = @TaxAccountID
	 order by RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId

	select TOP 1	@DiscountRRRId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
					@DiscountRRCalcTypeTrigger = RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
					@DiscountRRCalcTypeWhere = RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
					@DiscountRRCalcTypeMethod = RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
					@DiscountCOAAccountConfigId = COA_CNF_AccountConfig.COAAccountConfigId,
					@DiscountCOAAccountTypeId = COA_CNF_AccountType.COAAccountTypeId,
					@DiscountCOAAccountId = coa_cnf_account.COAAccountId,
					@DiscountPercentage = RR_CNF_RevenueRecognitionRule.Percentage,
					@DiscountDays = RR_CNF_RevenueRecognitionRule.Days,
					@DiscountPrice = COA_CNF_AccountConfig.Price,
					@DiscountCOAAccount_Percentage = COA_CNF_AccountConfig.Percentage,
					@DiscountRemainingValues = COA_CNF_AccountConfig.RemainingValues,
					@DiscountRRCOAAccountingType = COA_CNF_AccountConfig.AccountingType
	from coa_cnf_account WITH(NOLOCK)
		INNER JOIN COA_CNF_AccountType WITH(NOLOCK)				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
		INNER JOIN COA_CNF_AccountConfig WITH(NOLOCK)			on COA_CNF_AccountConfig.COAAccountId = coa_cnf_account.COAAccountId
		INNER JOIN RR_CNF_RevenueRecognitionRule WITH(NOLOCK)	on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId
	where coa_cnf_account.COAAccountID = @DiscountAccountID
	 order by RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId

	Declare @Temp table (BatchDate date)

	;with dates_CTE (date) as (
			select @FromDate 
			Union ALL
			select DATEADD(day, 1, date)
			from dates_CTE
			where date &lt; @ToDate
	) 
	INSERT INTO @Temp (
						BatchDate
					  ) 
	select *
	  from dates_CTE 

	DECLARE date_Cursor CURSOR LOCAL FOR
				select * from @Temp

	OPEN date_Cursor

	FETCH NEXT FROM date_Cursor INTO
		@BatchDate

	WHILE @@FETCH_STATUS = 0
	BEGIN

		select @BatchDate

		INSERT INTO [dbo].[RR_DATA_Revenue]
						([COAAccountId]
						,[RevenueRecognitionRuleId]
						,[RRCalcTypeWhere]
						,[RRCalcTypeMethod]
						,[COAAccountConfigId]
						,[COAAccountType]
						,[TransactionId]
						,[SaleId]
						,[SaleItemId]
						,[MatrixCellId]
						,[MatrixSheetID]
						,[SiteId]
						,[TicketID]
						,[OperatingAreaId]
						,[WorkstationId]
						,[UserGroupId]
						,[UserId]
						,[FCalcDate]
						,[Quantity]
						,[UnitAmount]
						,[GrossAmount]
						,[NetAmount]
						,[Price]
						,[Percentage]
						,[RemaningValues]
						,[RevenueAmount]
						,[AccountingType]
						,[RRCalcTypeTrigger]
						,[RRPercentage]
						,[RRDays]
						,[AttributeIDS])
					select distinct *
					from (
			       select  @SuspendCOAAccountId COAID,
									@SuspendRRRId RRID,
									@SuspendRRCalcTypeWhere RRWHERE,
									@SuspendRRCalcTypeMethod RRMETHOD,
									@SuspendCOAAccountConfigId RRCONFIG,
									@SuspendCOAAccountTypeId COATYPE,
				data_transaction.transactionid, 
				data_transaction.saleid,
									DATA_SaleItem.saleitemid,
				DATA_SaleItem.Matrixcellid,
				CNF_MatrixCell.MatrixSheetid,
				data_transaction.Siteid,
				p.ticketid,
				data_transaction.OperatingAreaId,
				data_transaction.Workstationid,
				data_transaction.UserGroupid,
				data_transaction.UserId,
									@BatchDate BatchDate,
									ISNULL(case when ((p.ticketid is null) or (cnf_matrixsheet.producttype &lt;&gt; 1)) then data_saleitem.quantity else 1 end, 0) as Quantity,
									DATA_SaleItem.UnitPrice,
									DATA_SaleItem.UnitRecharge charge,
									DATA_SaleItem.UnitRecharge charge2,
									@SuspendPrice Price,
									@SuspendCOAAccount_Percentage  Percentage,
									@SuspendRemainingValues RValues,				
									ISNULL(case when ((p.ticketid is null) or (cnf_matrixsheet.producttype &lt;&gt; 1)) then DATA_SaleItem.UnitRecharge *DATA_SaleItem.Quantity 
									            else DATA_SaleItem.UnitRecharge
										     end, 0) as UnitRecharge,
									@SuspendRRCOAAccountingType Accountingtype,
									@SuspendRRCalcTypeTrigger  RTRIGGER,
									@SuspendPercentage PERC,
									@SuspendDays DAyss,
									CNF_AttributeSet.Attributeids
	   
							from DATA_Sale WITH(NOLOCK)
								inner join data_transaction WITH(NOLOCK)			 on (data_transaction.TransactionId =  DATA_Sale.PaidTransactionId) 
								left join DATA_TransactionItem WITH(NOLOCK)			 on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
								left join DATA_SaleItem WITH(NOLOCK)				 on (data_saleitem.saleid = data_sale.saleid and DATA_TransactionItem.Itemid is null)
								left join DATA_TransactionItem ORIGITEM WITH(NOLOCK) on ORIGITEM.Saleitemid = data_saleitem.Saleitemid
								left join CNF_MatrixCell WITH(NOLOCK)				 on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
								left join CNF_MatrixSheet WITH(NOLOCK)				 on cnf_matrixsheet.matrixsheetid = cnf_matrixcell.matrixsheetid
								left join CNF_AttributeSet WITH(NOLOCK)				 on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId
								LEFT JOIN (select data_ticket.*, data_saleitem2ticket.saleitemid as S2TSaleitemid
											   from data_saleitem2ticket WITH(NOLOCK)
												INNER JOIN data_ticket WITH(NOLOCK)			ON data_ticket.ticketid = data_saleitem2ticket.ticketid 
												where data_saleitem2ticket.operationtype = 1
												  and data_ticket.voidtype &lt;&gt; 104
											) p									on p.S2TSaleitemid = data_saleitem.saleitemid

														where DATA_Sale.Paid = 1
								and data_transaction.transactiontype in (14, 16, 39)
								and DATA_SaleItem.UnitRecharge &lt;&gt; 0
								and ISNULL(DATA_TransactionItem.UnitRecharge, ORIGITEM.Unitrecharge) &lt;&gt; 0
								and data_saleitem.quantity &gt; 0
								and ISNULL(DATA_SaleItem.producttype, 0) &lt;&gt; 6
								and ((@RRTransDateType = 0 and data_transaction.fTransactionDate = @BatchDate)
									OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
								and ((data_transaction.transactionid in (select transactionid
																		from data_payment WITH(NOLOCK)
																		where PaymentStatus = 1
																		  and paymentamount &lt;&gt; 0
																		  and ((@RRTransDateType = 0 and convert(date, data_payment.fPaymentDate) = @BatchDate)
																		   OR (@RRTransDateType = 1 and convert(date, data_payment.PaymentDate) = @BatchDate)) 
																	  ))
									and (data_transaction.totalamount &lt;&gt; 0))



					UNION 

					select  @SuspendCOAAccountId COAID,
									@SuspendRRRId RRID,
									@SuspendRRCalcTypeWhere RRWHERE,
									@SuspendRRCalcTypeMethod RRMETHOD,
									@SuspendCOAAccountConfigId RRCONFIG,
									@SuspendCOAAccountTypeId COATYPE,
									data_transaction.transactionid, 
									data_transaction.saleid,
									DATA_TransactionItem.saleitemid,
									DATA_SaleItem.Matrixcellid,
									CNF_MatrixCell.MatrixSheetid,
									data_transaction.Siteid,
									p.ticketid,
									data_transaction.OperatingAreaId,
									data_transaction.Workstationid,
									data_transaction.UserGroupid,
									data_transaction.UserId,
									@BatchDate BatchDate,
									ISNULL(case when ((p.ticketid is null) or (cnf_matrixsheet.producttype &lt;&gt; 1)) then data_saleitem.quantity else 1 end, 0) as Quantity,
									DATA_SaleItem.UnitPrice,
									DATA_SaleItem.UnitRecharge,
									DATA_SaleItem.UnitRecharge,
									@SuspendPrice Price,
									@SuspendCOAAccount_Percentage  Percentage,
									@SuspendRemainingValues RValues,
									ISNULL(case when ((p.ticketid is null) or (cnf_matrixsheet.producttype &lt;&gt; 1)) then DATA_SaleItem.UnitRecharge *DATA_SaleItem.Quantity 
									            else DATA_SaleItem.UnitRecharge
										     end, 0) as UnitRecharge,
									@SuspendRRCOAAccountingType Accountingtype,
									@SuspendRRCalcTypeTrigger  RTRIGGER,
									@SuspendPercentage PERC,
									@SuspendDays DAyss,
									CNF_AttributeSet.Attributeids
	   
		   
							from DATA_Sale WITH(NOLOCK)
								inner join data_transaction WITH(NOLOCK)			 on  (data_transaction.Saleid = DATA_Sale.Saleid)
								left join DATA_TransactionItem WITH(NOLOCK)			 on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
								left join DATA_SaleItem WITH(NOLOCK)				 on (DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId)
																								--	or (data_saleitem.saleid = data_sale.saleid and DATA_TransactionItem.Itemid is null))
								left join DATA_TransactionItem ORIGITEM WITH(NOLOCK) on ORIGITEM.Saleitemid = data_saleitem.Saleitemid
								left join CNF_MatrixCell WITH(NOLOCK)				 on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
								left join CNF_MatrixSheet WITH(NOLOCK)				 on cnf_matrixsheet.matrixsheetid = cnf_matrixcell.matrixsheetid
								left join CNF_AttributeSet WITH(NOLOCK)				 on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId
								LEFT JOIN (select data_ticket.*, data_saleitem2ticket.saleitemid as S2TSaleitemid
											   from data_saleitem2ticket WITH(NOLOCK)
												INNER JOIN data_ticket WITH(NOLOCK)			ON data_ticket.ticketid = data_saleitem2ticket.ticketid 
												where data_saleitem2ticket.operationtype = 1
												  and data_ticket.voidtype &lt;&gt; 104
											) p									on p.S2TSaleitemid = data_saleitem.saleitemid

							where DATA_Sale.Paid = 1
								and data_transaction.transactiontype in (14, 16, 39)
								and DATA_SaleItem.UnitRecharge &lt;&gt; 0
								and ISNULL(DATA_TransactionItem.UnitRecharge, ORIGITEM.Unitrecharge) &lt;&gt; 0
								and data_saleitem.quantity &gt; 0
								and ISNULL(DATA_SaleItem.producttype, 0) &lt;&gt; 6
								and ((@RRTransDateType = 0 and data_transaction.fTransactionDate = @BatchDate)
									OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
								and data_transaction.transactionid in (select transactionid
																		from data_payment WITH(NOLOCK)
																		where PaymentStatus = 1
																		   and paymentamount &lt;&gt; 0
																		  and ((@RRTransDateType = 0 and convert(date, data_payment.fPaymentDate) = @BatchDate)
																		   OR (@RRTransDateType = 1 and convert(date, data_payment.PaymentDate) = @BatchDate)) 
																	  )

UNION 

					select  @SuspendCOAAccountId COAID,
									@SuspendRRRId RRID,
									@SuspendRRCalcTypeWhere RRWHERE,
									@SuspendRRCalcTypeMethod RRMETHOD,
									@SuspendCOAAccountConfigId RRCONFIG,
									@SuspendCOAAccountTypeId COATYPE,
									data_transaction.transactionid, 
									data_transaction.saleid,
									DATA_SaleItem.saleitemid,
									DATA_SaleItem.Matrixcellid,
									CNF_MatrixCell.MatrixSheetid,
									data_transaction.Siteid,
									p.ticketid,
									data_transaction.OperatingAreaId,
									data_transaction.Workstationid,
									data_transaction.UserGroupid,
									data_transaction.UserId,
									@BatchDate BatchDate,
									ISNULL(case when ((p.ticketid is null) or (cnf_matrixsheet.producttype &lt;&gt; 1)) then data_saleitem.quantity else 1 end, 0) as Quantity,
									DATA_SaleItem.UnitPrice,
									DATA_SaleItem.UnitRecharge,
									DATA_SaleItem.UnitRecharge,
									@SuspendPrice Price,
									@SuspendCOAAccount_Percentage  Percentage,
									@SuspendRemainingValues RValues,
									ISNULL(case when ((p.ticketid is null) or (cnf_matrixsheet.producttype &lt;&gt; 1)) then DATA_SaleItem.UnitRecharge *DATA_SaleItem.Quantity 
									            else DATA_SaleItem.UnitRecharge
										     end, 0) as UnitRecharge,
									@SuspendRRCOAAccountingType Accountingtype,
									@SuspendRRCalcTypeTrigger  RTRIGGER,
									@SuspendPercentage PERC,
									@SuspendDays DAyss,
									CNF_AttributeSet.Attributeids
	   
		   
							from DATA_Sale WITH(NOLOCK)
								inner join data_transaction WITH(NOLOCK)			 on  (data_transaction.Saleid = DATA_Sale.Saleid)
								left join DATA_SaleItem WITH(NOLOCK)				 on (data_saleitem.saleid = data_sale.saleid)
								left join DATA_TransactionItem ORIGITEM WITH(NOLOCK) on ORIGITEM.Saleitemid = data_saleitem.Saleitemid
								left join CNF_MatrixCell WITH(NOLOCK)				 on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
								left join CNF_MatrixSheet WITH(NOLOCK)				 on cnf_matrixsheet.matrixsheetid = cnf_matrixcell.matrixsheetid
								left join CNF_AttributeSet WITH(NOLOCK)				 on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId
								LEFT JOIN (select data_ticket.*, data_saleitem2ticket.saleitemid as S2TSaleitemid
											   from data_saleitem2ticket WITH(NOLOCK)
												INNER JOIN data_ticket WITH(NOLOCK)			ON data_ticket.ticketid = data_saleitem2ticket.ticketid 
												where data_saleitem2ticket.operationtype = 1
												  and data_ticket.voidtype &lt;&gt; 104
											) p									on p.S2TSaleitemid = data_saleitem.saleitemid

							where DATA_Sale.Paid = 1
								and data_transaction.transactiontype in (14, 16, 39)
								and DATA_SaleItem.UnitRecharge &lt;&gt; 0
								and ISNULL(DATA_SaleItem.UnitRecharge, ORIGITEM.Unitrecharge) &lt;&gt; 0
								and data_saleitem.quantity &gt; 0
								and ISNULL(DATA_SaleItem.producttype, 0) &lt;&gt; 6
								and ((@RRTransDateType = 0 and data_transaction.fTransactionDate = @BatchDate)
									OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
								and data_transaction.transactionid in (select transactionid
																		from data_payment WITH(NOLOCK)
																		where PaymentStatus = 1
																		   and paymentamount &lt;&gt; 0
																		  and ((@RRTransDateType = 0 and convert(date, data_payment.fPaymentDate) = @BatchDate)
																		   OR (@RRTransDateType = 1 and convert(date, data_payment.PaymentDate) = @BatchDate)) 
																	  )

					)p
	   
	


		INSERT INTO [dbo].[RR_DATA_Revenue]
						([COAAccountId]
						,[RevenueRecognitionRuleId]
						,[RRCalcTypeWhere]
						,[RRCalcTypeMethod]
						,[COAAccountConfigId]
						,[COAAccountType]
						,[TransactionId]
						,[SaleId]
						,[TicketID]
						,[SaleItemId]
						,[MatrixCellId]
						,[MatrixSheetID]
						,[SiteId]
						,[OperatingAreaId]
						,[WorkstationId]
						,[UserGroupId]
						,[UserId]
						,[FCalcDate]
						,[Quantity]
						,[UnitAmount]
						,[GrossAmount]
						,[NetAmount]
						,[Price]
						,[Percentage]
						,[RemaningValues]
						,[RevenueAmount]
						,[AccountingType]
						,[RRCalcTypeTrigger]
						,[RRPercentage]
						,[RRDays]
						,[AttributeIDS]
						)
		select *
		 from(
				select  distinct 
				        @SuspendCOAAccountId suspendid,
						@SuspendRRRId  RRRID,
						@SuspendRRCalcTypeWhere typewhere,
						@SuspendRRCalcTypeMethod method,
						@SuspendCOAAccountConfigId configid,
						@SuspendCOAAccountTypeId AccountTypeId,
						data_transaction.transactionid, 
						data_transaction.saleid,
						data_ticket.ticketid,
						DATA_TransactionItem.saleitemid,
						DATA_SaleItem.Matrixcellid,
						CNF_MatrixCell.MatrixSheetid,
						data_transaction.Siteid,
						data_transaction.OperatingAreaId,
						data_transaction.Workstationid,
						data_transaction.UserGroupid,
						data_transaction.UserId,
						@BatchDate BatchDate,
						ISNULL(case when ((data_ticket.ticketid is null) or (cnf_matrixsheet.producttype &lt;&gt; 1)) then data_saleitem.quantity else 1 end, 0) as Quantity,  						     
						DATA_SaleItem.UnitPrice,
						data_saleitem.UnitPrice GrossAmount,
						case when data_saleitem.ProductTaxType = 1 then DATA_SaleItem.UnitrawPrice - data_saleitem.UnitTaxes
						     else data_saleitem.UnitRawPrice
						end  as NetAmount,
						@SuspendPrice price,
						@SuspendCOAAccount_Percentage coapercentage,
						@SuspendRemainingValues remainvalue,
						ISNULL(case    
						  	    when (data_ticket.ticketid is not null) and cnf_matrixsheet.producttype = 1 and (data_saleitem.producttaxtype = 4) and (CNF_MatrixCell.TaxType = 1) then (DATA_SaleItem.UnitPrice) 
								when (data_ticket.ticketid is not null) and cnf_matrixsheet.producttype = 1 and (data_saleitem.ProductTaxType &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then (DATA_SaleItem.UnitrawPrice )														
								when (data_ticket.ticketid is not null) and cnf_matrixsheet.producttype = 1 and (data_saleitem.ProductTaxType = 1) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then (DATA_SaleItem.UnitrawPrice - DATA_SaleItem.unittaxes) 						
								when (data_ticket.ticketid is not null) and cnf_matrixsheet.producttype = 1 and (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 then 0				
								when (data_ticket.ticketid is not null) and cnf_matrixsheet.producttype = 1 and isnull((data_transaction.TotalAmount), 0) &lt;&gt; 0 then data_transaction.TotalAmount
								when (data_ticket.ticketid is not null) and cnf_matrixsheet.producttype = 1 and isnull((DATA_Sale.TotalAmount), 0) &lt;&gt; 0 then DATA_Sale.TotalAmount

								when (data_saleitem.producttaxtype = 4 or data_ticket.ticketid is not null) and (CNF_MatrixCell.TaxType = 1) then ((DATA_SaleItem.UnitPrice) * DATA_SaleItem.Quantity)
								when (data_saleitem.ProductTaxType &lt;&gt; 1 or data_ticket.ticketid is not null) and (DATA_SaleItem.UnitrawPrice is not null) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice ) * DATA_SaleItem.Quantity)						
								when (data_saleitem.ProductTaxType = 1 or data_ticket.ticketid is not null) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitPrice - DATA_SaleItem.unittaxes) * DATA_SaleItem.Quantity)						
								when (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 then 0	
								when data_ticket.ticketid is null and data_saleitem.producttype = 2 then ((DATA_SaleItem.UnitPrice - DATA_SaleItem.unittaxes) * DATA_SaleItem.Quantity)
								when isnull((data_transaction.TotalAmount), 0) &lt;&gt; 0 then data_transaction.TotalAmount
								when isnull((DATA_Sale.TotalAmount), 0) &lt;&gt; 0 then DATA_Sale.TotalAmount
								else (data_transaction.Revenue)

						end, 0) as Revenue,
						@SuspendRRCOAAccountingType Accountingtype,
						@SuspendRRCalcTypeTrigger typecalctrigger,
						@SuspendPercentage percentage,
						@SuspendDays Days,
						CNF_AttributeSet.Attributeids	 
						  
				from DATA_Sale WITH(NOLOCK)
					inner join data_transaction	WITH(NOLOCK)		on data_transaction.TransactionId = DATA_Sale.PaidTransactionId
					left join DATA_TransactionItem WITH(NOLOCK)		on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
					left join DATA_SaleItem	WITH(NOLOCK)		    on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
					left join CNF_MatrixCell WITH(NOLOCK)			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
					left join CNF_MatrixSheet WITH(NOLOCK)				on cnf_matrixsheet.matrixsheetid = cnf_matrixcell.matrixsheetid
					left join CNF_AttributeSet WITH(NOLOCK)			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId
					left join data_saleitem2ticket WITH(NOLOCK)    on data_saleitem2ticket.saleitemid = data_saleitem.saleitemid
					left join data_ticket WITH(NOLOCK)				on data_ticket.ticketid = data_saleitem2ticket.ticketid 

				where DATA_Sale.Paid = 1
				    and ((ISNULL(voidtype, 0) not in (104, 125)) or (transactionstatus = 30))
					and ISNULL(DATA_SaleItem.producttype, 0) &lt;&gt; 6
					and data_transaction.transactiontype in (14)
					and ((@RRTransDateType = 0 and data_transaction.fTransactionDate = @BatchDate)
						OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
					and data_transaction.transactionid in (select transactionid
															from data_payment WITH(NOLOCK)
															where PaymentStatus = 1
																--and ((@RRTransDateType = 0 and convert(date, data_payment.fPaymentDate) = @BatchDate)
																--OR (@RRTransDateType = 1 and convert(date, data_payment.PaymentDate) = @BatchDate)) 
										)
			)p 
		where Revenue &lt;&gt; 0									


		INSERT INTO [dbo].[RR_DATA_Revenue]
						([COAAccountId]
						,[RevenueRecognitionRuleId]
						,[RRCalcTypeWhere]
						,[RRCalcTypeMethod]
						,[COAAccountConfigId]
						,[COAAccountType]
						,[TransactionId]
						,[SaleId]
						,[TicketID]
						,[SaleItemId]
						,[MatrixCellId]
						,[MatrixSheetID]
						,[SiteId]
						,[OperatingAreaId]
						,[WorkstationId]
						,[UserGroupId]
						,[UserId]
						,[FCalcDate]
						,[Quantity]
						,[UnitAmount]
						,[GrossAmount]
						,[NetAmount]
						,[Price]
						,[Percentage]
						,[RemaningValues]
						,[RevenueAmount]
						,[AccountingType]
						,[RRCalcTypeTrigger]
						,[RRPercentage]
						,[RRDays]
						,[AttributeIDS])
			select  @SuspendCOAAccountId,
					@SuspendRRRId,
					@SuspendRRCalcTypeWhere,
					@SuspendRRCalcTypeMethod,
					@SuspendCOAAccountConfigId,
					@SuspendCOAAccountTypeId,
					data_transaction.transactionid, 
					data_transaction.saleid,
					data_ticket.ticketid,
					DATA_TransactionItem.saleitemid,
					DATA_SaleItem.Matrixcellid,
					CNF_MatrixCell.MatrixSheetid,
					data_transaction.Siteid,
					data_transaction.OperatingAreaId,
					data_transaction.Workstationid,
					data_transaction.UserGroupid,
					data_transaction.UserId,
					@BatchDate,
					ISNULL(case when ((data_ticket.ticketid is null) or (cnf_matrixsheet.producttype &lt;&gt; 1)) then ISNULL(data_saleitem.quantity, 1) else 1 end, 0) as Quantity,
					DATA_SaleItem.UnitPrice,
					case when isnull(DATA_TransactionItem.TotalAmount, 0) &lt;&gt; 0 then DATA_TransactionItem.TotalAmount
						 when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
						 else DATA_Sale.TotalAmount
					end,
					case when isnull((DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes)
						 when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
						 else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
					end as NetAmount,
					@SuspendPrice,
					@SuspendCOAAccount_Percentage,
					@SuspendRemainingValues,
					ISNULL(case when cnf_matrixsheet.producttype = 1 and data_ticket.ticketid is not null and (data_saleitem.producttaxtype = 4) and (CNF_MatrixCell.TaxType = 1) then ((DATA_SaleItem.UnitPrice))
						 when cnf_matrixsheet.producttype = 1 and data_ticket.ticketid is not null and (data_saleitem.ProductTaxType &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) 
							and (isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0) 
							and (((select sum(discountamount) from data_saleitemrule where saleitemid = DATA_SaleItem.saleitemid) &gt; 0) and (data_transaction.transactiontype in (7, 22)))							
							then ((DATA_SaleItem.UnitRawPrice + data_saleitem.unitRecharge))
       					 when cnf_matrixsheet.producttype = 1 and data_ticket.ticketid is not null and  (data_saleitem.ProductTaxType &lt;&gt; 1) and (data_transaction.transactiontype in (18)) and (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitRawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then (DATA_SaleItem.UnitRawPrice)
       					 when cnf_matrixsheet.producttype = 1 and data_ticket.ticketid is not null and  (data_saleitem.ProductTaxType &lt;&gt; 1) and (data_transaction.transactiontype in (18, 22)) and (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitRawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitRawPrice  + data_saleitem.unitRecharge))						
						 when cnf_matrixsheet.producttype = 1 and data_ticket.ticketid is not null and  (data_saleitem.ProductTaxType = 1) and (data_transaction.transactiontype in (18, 22)) and isnull((DATA_SaleItem.UnitRawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitRawPrice - DATA_SaleItem.unittaxes + data_saleitem.unitRecharge))						
						 when cnf_matrixsheet.producttype = 1 and data_ticket.ticketid is not null and  (data_saleitem.ProductTaxType &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice  + data_saleitem.unitRecharge))
						 when cnf_matrixsheet.producttype = 1 and data_ticket.ticketid is not null and  (data_saleitem.ProductTaxType = 1) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice - DATA_SaleItem.unittaxes + data_saleitem.unitRecharge))
						 when (data_saleitem.producttaxtype = 4) and (CNF_MatrixCell.TaxType = 1) then ((DATA_SaleItem.UnitPrice) * DATA_SaleItem.Quantity)
						 when (data_saleitem.ProductTaxType &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) 
							and (isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0) 
							and (((select sum(discountamount) from data_saleitemrule where saleitemid = DATA_SaleItem.saleitemid) &gt; 0) and (data_transaction.transactiontype in (7, 22)))							
							then ((DATA_SaleItem.UnitRawPrice + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)
       					 when (data_saleitem.ProductTaxType &lt;&gt; 1) and (data_transaction.transactiontype in (18, 22)) and (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitRawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then case when transactiontype &lt;&gt; 18 then ((DATA_SaleItem.UnitRawPrice  + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)
																																																														else ((DATA_SaleItem.UnitPrice  - data_saleitem.unittaxes + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)
																																																													end  						 
						 when (data_saleitem.ProductTaxType = 1) and (data_transaction.transactiontype in (18)) and isnull((DATA_SaleItem.UnitRawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then (DATA_SaleItem.UnitPrice - data_saleitem.unittaxes)

						 when (data_saleitem.ProductTaxType = 1) and (data_transaction.transactiontype in (22)) and isnull((DATA_SaleItem.UnitRawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitRawPrice - DATA_SaleItem.unittaxes + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)
						 when (data_saleitem.ProductTaxType &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice  + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)
						 when (data_saleitem.ProductTaxType = 1) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice - DATA_SaleItem.unittaxes + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)
   						 when (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 and data_saleitem.unitRecharge = 0 then 0
						 when (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 and data_saleitem.unitRecharge &lt;&gt; 0 then data_saleitem.unitRecharge
						 when isnull((data_transaction.TotalAmount), 0) &lt;&gt; 0 then data_transaction.TotalAmount
						 when isnull((DATA_Sale.TotalAmount), 0) &lt;&gt; 0 then DATA_Sale.TotalAmount
						 when data_transaction.transactiontype = 13 then (abs(data_transaction.Revenue) - (select sum(paymentfee) from data_payment DP where dp.transactionid = data_transaction.transactionid))
						 else ABS((data_transaction.Revenue))
					end, 0),
					case when TransactionType in (30) and @SuspendRRCOAAccountingType = 2 and data_transactionitem.Quantity &lt; 0 then 1
						 when TransactionType in (30) and @SuspendRRCOAAccountingType = 2 and data_transactionitem.Quantity &gt; 0 then 2
						 when TransactionType in (13, 17, 18, 22, 40) and @SuspendRRCOAAccountingType = 1 then 2
						 when TransactionType in (13, 17, 18, 22, 40) and @SuspendRRCOAAccountingType = 2 then 1
						 when TransactionType in (34) and data_transaction.Revenue &lt; 0 then 1
						 else @SuspendRRCOAAccountingType
					end Accountingtype,
					@SuspendRRCalcTypeTrigger,
					@SuspendPercentage,
					@SuspendDays,
					CNF_AttributeSet.Attributeids
	   
		from DATA_Sale WITH(NOLOCK)
			inner join data_transaction WITH(NOLOCK)		on  ((data_transaction.TransactionId = ISNULL(data_sale.voidtransactionid, DATA_Sale.PaidTransactionId)) 
																or (data_transaction.TransactionId = DATA_Sale.PaidTransactionId))
			left join DATA_TransactionItem WITH(NOLOCK)		on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
			left join DATA_SaleItem WITH(NOLOCK)			on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
			left join CNF_MatrixCell WITH(NOLOCK)			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
			left join CNF_MatrixSheet WITH(NOLOCK)			on cnf_matrixsheet.matrixsheetid = cnf_matrixcell.matrixsheetid
			left join CNF_AttributeSet WITH(NOLOCK)			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId
			left join data_saleitem2ticket WITH(NOLOCK)		on data_saleitem2ticket.saleitemid = data_saleitem.saleitemid
			left join data_ticket WITH(NOLOCK)				on data_ticket.ticketid = data_saleitem2ticket.ticketid 

		where DATA_Sale.Paid = 1
			and ISNULL(DATA_SaleItem.producttype, 0) &lt;&gt; 6
			and data_transaction.transactiontype not in (4, 5, 6, 7, 8, 9, 10, 12, 14, 15, 16, 18, 20, 22, 31, 37, 39, 42, 43, 46, 47, 48, 49, 52)
			and ((@RRTransDateType = 0 and data_transaction.fTransactionDate = @BatchDate)
				OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
			and ((data_transaction.transactionid in (select transactionid
								from data_payment WITH(NOLOCK)
								where PaymentStatus = 1
								  and paymentamount &lt;&gt; 0									
								)))

	
	
	
	
	INSERT INTO [dbo].[RR_DATA_Revenue]
						([COAAccountId]
						,[RevenueRecognitionRuleId]
						,[RRCalcTypeWhere]
						,[RRCalcTypeMethod]
						,[COAAccountConfigId]
						,[COAAccountType]
						,[TransactionId]
						,[SaleId]
						,[TicketID]
						,[SaleItemId]
						,[MatrixCellId]
						,[MatrixSheetID]
						,[SiteId]
						,[OperatingAreaId]
						,[WorkstationId]
						,[UserGroupId]
						,[UserId]
						,[FCalcDate]
						,[Quantity]
						,[UnitAmount]
						,[GrossAmount]
						,[NetAmount]
						,[Price]
						,[Percentage]
						,[RemaningValues]
						,[RevenueAmount]
						,[AccountingType]
						,[RRCalcTypeTrigger]
						,[RRPercentage]
						,[RRDays]
						,[AttributeIDS])
			select *
			from (
							select  @SuspendCOAAccountId as Suscoa,
									@SuspendRRRId as RRID,
									@SuspendRRCalcTypeWhere as TypeWhere,
									@SuspendRRCalcTypeMethod as TypeMethod,
									@SuspendCOAAccountConfigId as COAConfig,
									@SuspendCOAAccountTypeId as COAAccType,
					data_transaction.transactionid, 
					data_transaction.saleid,
					data_ticket.ticketid,
					DATA_TransactionItem.saleitemid,
					DATA_SaleItem.Matrixcellid,
					CNF_MatrixCell.MatrixSheetid,
					data_transaction.Siteid,
					data_transaction.OperatingAreaId,
					data_transaction.Workstationid,
					data_transaction.UserGroupid,
					data_transaction.UserId,
									@BatchDate as BatchDate,
									ISNULL(case when ((data_ticket.ticketid is null) or (cnf_matrixsheet.producttype &lt;&gt; 1)) then ISNULL(data_saleitem.quantity, 1) else 1 end, 0) as Quantity,
									DATA_SaleItem.UnitPrice,
									case when isnull(DATA_TransactionItem.TotalAmount, 0) &lt;&gt; 0 then DATA_TransactionItem.TotalAmount
										 when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
										 else DATA_Sale.TotalAmount
									end GrossAmount,
									case when isnull((DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes)
										 when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
										 else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
									end as NetAmount,
									@SuspendPrice COAPrice,
									@SuspendCOAAccount_Percentage  COAPerc,
									@SuspendRemainingValues RemainValues,
									ISNULL(case when cnf_matrixsheet.producttype = 1 and data_ticket.ticketid is not null and (data_saleitem.producttaxtype = 4) and (CNF_MatrixCell.TaxType = 1) then ((DATA_SaleItem.UnitPrice))
										 when cnf_matrixsheet.producttype = 1 and data_ticket.ticketid is not null and (data_saleitem.ProductTaxType &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) 
											and (isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0) 
											and (((select sum(discountamount) from data_saleitemrule where saleitemid = DATA_SaleItem.saleitemid) &gt; 0) and (data_transaction.transactiontype in (7, 22)))							
											then ((DATA_SaleItem.UnitRawPrice + data_saleitem.unitRecharge))
       									 when cnf_matrixsheet.producttype = 1 and data_ticket.ticketid is not null and  (data_saleitem.ProductTaxType &lt;&gt; 1) and (data_transaction.transactiontype in (18)) and (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitRawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then (DATA_SaleItem.UnitRawPrice)
       									 when cnf_matrixsheet.producttype = 1 and data_ticket.ticketid is not null and  (data_saleitem.ProductTaxType &lt;&gt; 1) and (data_transaction.transactiontype in (18, 22)) and (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitRawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitRawPrice  + data_saleitem.unitRecharge))						
										 when cnf_matrixsheet.producttype = 1 and data_ticket.ticketid is not null and  (data_saleitem.ProductTaxType = 1) and (data_transaction.transactiontype in (18, 22)) and isnull((DATA_SaleItem.UnitRawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitRawPrice - DATA_SaleItem.unittaxes + data_saleitem.unitRecharge))						
										 when cnf_matrixsheet.producttype = 1 and data_ticket.ticketid is not null and  (data_saleitem.ProductTaxType &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice  + data_saleitem.unitRecharge))
										 when cnf_matrixsheet.producttype = 1 and data_ticket.ticketid is not null and  (data_saleitem.ProductTaxType = 1) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice - DATA_SaleItem.unittaxes + data_saleitem.unitRecharge))
										 when (data_saleitem.producttaxtype = 4) and (CNF_MatrixCell.TaxType = 1) then ((DATA_SaleItem.UnitPrice) * DATA_SaleItem.Quantity)
										 when (data_saleitem.ProductTaxType &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) 
											and (isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0) 
											and (((select sum(discountamount) from data_saleitemrule where saleitemid = DATA_SaleItem.saleitemid) &gt; 0) and (data_transaction.transactiontype in (7, 22)))							
											then ((DATA_SaleItem.UnitRawPrice + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)
       									 when (data_saleitem.ProductTaxType &lt;&gt; 1) and (data_transaction.transactiontype in (18, 22)) and (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitRawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then case when transactiontype &lt;&gt; 18 then ((DATA_SaleItem.UnitRawPrice  + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)
																																																																		else ((DATA_SaleItem.UnitPrice  - data_saleitem.unittaxes + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)
																																																																	end  						 
										 when (data_saleitem.ProductTaxType = 1) and (data_transaction.transactiontype in (18)) and isnull((DATA_SaleItem.UnitRawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then (DATA_SaleItem.UnitPrice - data_saleitem.unittaxes)

										 when (data_saleitem.ProductTaxType = 1) and (data_transaction.transactiontype in (22)) and isnull((DATA_SaleItem.UnitRawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitRawPrice - DATA_SaleItem.unittaxes + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)
										 when (data_saleitem.ProductTaxType &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice  + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)
										 when (data_saleitem.ProductTaxType = 1) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice - DATA_SaleItem.unittaxes + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)
   										 when (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 and data_saleitem.unitRecharge = 0 then 0
										 when (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 and data_saleitem.unitRecharge &lt;&gt; 0 then data_saleitem.unitRecharge
										 when isnull((data_transaction.TotalAmount), 0) &lt;&gt; 0 then data_transaction.TotalAmount
										 when isnull((DATA_Sale.TotalAmount), 0) &lt;&gt; 0 then DATA_Sale.TotalAmount
										 when data_transaction.transactiontype = 13 then (abs(data_transaction.Revenue) - (select sum(paymentfee) from data_payment DP where dp.transactionid = data_transaction.transactionid))
										 else ABS((data_transaction.Revenue))
									end, 0) RevenueAmount,
									case when TransactionType in (13, 17, 18, 22, 30, 40) and @SuspendRRCOAAccountingType = 1 then 2
										 when TransactionType in (13, 17, 18, 22, 30, 40) and @SuspendRRCOAAccountingType = 2 then 1
										 when TransactionType in (34) and data_transaction.Revenue &lt; 0 then 1
										 else @SuspendRRCOAAccountingType
									end Accountingtype,
									@SuspendRRCalcTypeTrigger CalcTrigger,
									@SuspendPercentage RRPerc,
									@SuspendDays rrDays,
									CNF_AttributeSet.Attributeids
	   
						from DATA_Sale WITH(NOLOCK)
							inner join data_transaction WITH(NOLOCK)		on  ((data_transaction.TransactionId = ISNULL(data_sale.voidtransactionid, DATA_Sale.PaidTransactionId)) 
																				or (data_transaction.saleid = data_sale.saleid))
							left join DATA_TransactionItem WITH(NOLOCK)		on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
							left join DATA_SaleItem WITH(NOLOCK)			on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
							left join CNF_MatrixCell WITH(NOLOCK)			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
							left join CNF_MatrixSheet WITH(NOLOCK)			on cnf_matrixsheet.matrixsheetid = cnf_matrixcell.matrixsheetid
							left join CNF_AttributeSet WITH(NOLOCK)			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId
							left join data_saleitem2ticket WITH(NOLOCK)		on data_saleitem2ticket.saleitemid = data_saleitem.saleitemid
							left join data_ticket WITH(NOLOCK)				on data_ticket.ticketid = data_saleitem2ticket.ticketid 

						where ISNULL(DATA_SaleItem.producttype, 0) &lt;&gt; 6
							and data_transaction.transactiontype in (9)
							and data_transaction.transactionstatus = 5
							and ((@RRTransDateType = 0 and data_transaction.fTransactionDate = @BatchDate)
								OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))

			)p
			where RevenueAmount &lt;&gt; 0

		INSERT INTO [dbo].[RR_DATA_Revenue]
						([COAAccountId]
						,[RevenueRecognitionRuleId]
						,[RRCalcTypeWhere]
						,[RRCalcTypeMethod]
						,[COAAccountConfigId]
						,[COAAccountType]
						,[TransactionId]
						,[SaleId]
						,[ticketid]
						,[SaleItemId]
						,[MatrixCellId]
						,[MatrixSheetID]
						,[SiteId]
						,[OperatingAreaId]
						,[WorkstationId]
						,[UserGroupId]
						,[UserId]
						,[FCalcDate]
						,[Quantity]
						,[UnitAmount]
						,[GrossAmount]
						,[NetAmount]
						,[Price]
						,[Percentage]
						,[RemaningValues]
						,[RevenueAmount]
						,[AccountingType]
						,[RRCalcTypeTrigger]
						,[RRPercentage]
						,[RRDays])
		select *
		  from (
				select  @SuspendCOAAccountId as SuspendCOAAccountId,
						@SuspendRRRId as SuspendRRRId,
						@SuspendRRCalcTypeWhere as SuspendRRCalcTypeWhere,
						@SuspendRRCalcTypeMethod as SuspendRRCalcTypeMethod,
						@SuspendCOAAccountConfigId as SuspendCOAAccountConfigId,
						@SuspendCOAAccountTypeId as SuspendCOAAccountTypeId,
						data_transaction.transactionid, 
						data_transaction.saleid,
						DATA_Ticket.ticketid,
						ISNULL(DATA_SaleItem.saleitemid, SI1.saleitemid) Saleitemid,
						CNF_MatrixCell.Matrixcellid,
						CNF_MatrixCell.MatrixSheetid,
						data_transaction.Siteid,
						data_transaction.OperatingAreaId,
						data_transaction.Workstationid,
						data_transaction.UserGroupid,
						data_transaction.UserId,
						@BatchDate as BatchDate,
						1 as Quantity,
						ISNULL(DATA_Ticket.price, sum(SI1.UnitPrice)) as UnitAmount,
						ISNULL(DATA_Ticket.Price, sum(SI1.UnitPrice)) as GrossAmount,
						ISNULL((DATA_Ticket.Price - data_ticket.taxes), 0) as netprice,
						@SuspendPrice as SuspendPrice,
						@SuspendCOAAccount_Percentage as SuspendCOAAccount_Percentage,
						@SuspendRemainingValues as SuspendRemainingValues,
						ISNULL(case when dr1.accountingtype = 1 and ISNULL((DATA_Ticket.Price - data_ticket.taxes) - sum(dr1.revenueamount), 0) &lt;&gt; 0 and ((select sum(discountamount) from data_saleitemrule where saleitemid = DATA_SaleItem.saleitemid) &gt; 0) then DATA_Ticket.Price - data_ticket.taxes + (select sum(discountamount) from data_saleitemrule where saleitemid = DATA_SaleItem.saleitemid)
								when dr1.accountingtype = 2 then (select sum(revenueamount) from rr_data_revenue where rr_data_revenue.ticketid = dr1.ticketid and accountingtype = 2)			   
								when (ISNULL(data_saleitem.producttaxtype, SI1.ProductTaxType) = 4) and (CNF_MatrixCell.TaxType = 1) then ((DATA_SaleItem.UnitPrice))
								when (ISNULL(data_saleitem.producttaxtype, SI1.ProductTaxType) &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) 
											and (isnull((DATA_SaleItem.UnitrawPrice), 0) &lt;&gt; 0) and (((select sum(discountamount) from data_saleitemrule where saleitemid = DATA_SaleItem.saleitemid) &gt; 0) and (data_transaction.transactiontype in (7, 20, 22)))							
									then ((DATA_SaleItem.UnitRawPrice + data_saleitem.unitRecharge))
								when (ISNULL(data_saleitem.producttaxtype, SI1.ProductTaxType) &lt;&gt; 1) and (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitRawPrice), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitRawPrice  + data_saleitem.unitRecharge))
								when (ISNULL(data_saleitem.producttaxtype, SI1.ProductTaxType) = 1) and isnull((DATA_SaleItem.UnitRawPrice), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitRawPrice - DATA_SaleItem.unittaxes + data_saleitem.unitRecharge))
								when (ISNULL(data_saleitem.producttaxtype, SI1.ProductTaxType) &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) and isnull((DATA_SaleItem.UnitrawPrice), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice  + data_saleitem.unitRecharge))
								when (ISNULL(data_saleitem.producttaxtype, SI1.ProductTaxType) = 1) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice - DATA_SaleItem.unittaxes + data_saleitem.unitRecharge))
								when (DATA_SaleItem.UnitPrice &lt;&gt; 0) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 and data_saleitem.unitRecharge = 0 and data_saleitem.basesaleid is not null														 
								then (select top 1 DS.UnitRawPrice
									from data_saleitem DS
									where DS.saleid = data_saleitem.basesaleid
										and DS.matrixcellid = CNF_MatrixCell.Matrixcellid)							 							 
								when (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 and data_saleitem.unitRecharge = 0 then 0
								when (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 and data_saleitem.unitRecharge &lt;&gt; 0 then data_saleitem.unitRecharge
							
							when SI1.saleitemid is not null then sum((SI1.UnitRawPrice - SI1.unittaxes + SI1.unitRecharge))
							when isnull((data_transaction.TotalAmount), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - data_transaction.totaltaxes)
							
							
							
							when isnull((DATA_Sale.TotalAmount), 0) &lt;&gt; 0 then (DATA_Sale.TotalAmount - DATA_Sale.totaltaxes)
								else (data_transaction.Revenue)
							end, 0) as revenueamount,
						1 Accountingtype,
						@SuspendRRCalcTypeTrigger as SuspendRRCalcTypeTrigger,
						@SuspendPercentage as SuspendPercentage,
						@SuspendDays as SuspendDays

				from DATA_Sale WITH(NOLOCK)
					inner join data_transaction WITH(NOLOCK)			on  ((data_transaction.TransactionId = ISNULL(data_sale.voidtransactionid, DATA_Sale.PaidTransactionId)) 
																			or (data_transaction.Saleid = DATA_Sale.Saleid))
					left JOIN data_transaction2ticket					on data_transaction2ticket.transactionid = data_transaction.transactionid
					left JOIN DATA_Ticket								on data_ticket.ticketid = data_transaction2ticket.ticketid
					left join DATA_SaleItem2Ticket						ON DATA_SALEITEM2TICKET.TICKETID = DATA_TICKET.TICKETID
																						and data_saleitem2ticket.OperationType = 2
					left JOIN DATA_SaleItem							    on data_saleitem.SALEITEMID = DATA_SaleItem2Ticket.saleitemid
					left join DATA_TransactionItem						ON DATA_TRANSACTIONITEM.TRANSACTIONID = DATA_TRANSACTION.TRANSACTIONID
																			AND DATA_TRANSACTIONITEM.SALEITEMID = ISNULL(DATA_SALEITEM.SALEITEMID, DATA_TRANSACTIONITEM.SALEITEMID)
					left join rr_data_revenue DR1 WITH(NOLOCK)			on dr1.ticketid = DATA_Ticket.ticketid and accountingtype = 1
					left join data_saleitem SI1 WITH(NOLOCK)			on SI1.saleitemid = data_transactionitem.saleitemid
					left join CNF_MatrixCell WITH(NOLOCK)				on CNF_MatrixCell.Matrixcellid = Coalesce(DATA_SaleItem.Matrixcellid, DATA_SaleItem.MatrixcellID, SI1.matrixcellid)

				where DATA_Sale.Paid = 1
					and ISNULL(DATA_SaleItem.producttype, 0) &lt;&gt; 6
					and data_transaction.transactiontype  in (18, 20, 22)
					and data_saleitem.saleid = data_sale.saleid
					and ((@RRTransDateType = 0 and data_transaction.fTransactionDate = @BatchDate)
						OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
					and ((data_transaction.transactionid in (select data_payment.transactionid
															   from data_payment WITH(NOLOCK)
															  where PaymentStatus = 1
																--and paymentamount &lt;&gt; 0
																and ((@RRTransDateType = 0 and convert(date, data_payment.fPaymentDate) = @BatchDate)
															 		OR (@RRTransDateType = 1 and convert(date, data_payment.PaymentDate) = @BatchDate)) 										
																)))

			Group by	data_transaction.transactionid, 
							data_transaction.saleid,
							DATA_Ticket.ticketid,
							ISNULL(DATA_SaleItem.saleitemid, SI1.saleitemid),
							CNF_MatrixCell.Matrixcellid,
							CNF_MatrixCell.MatrixSheetid,
							data_transaction.Siteid,
							data_transaction.OperatingAreaId,
							data_transaction.Workstationid,
							data_transaction.UserGroupid,
							data_transaction.UserId,
							data_transaction.fTransactionDate,
							data_transaction.TransactionDate,
							DATA_Ticket.price,
							DATA_Ticket.Price,
							data_ticket.taxes,
							dr1.accountingtype,
							dr1.ticketid,
							data_saleitem.saleitemid,
							ISNULL(data_saleitem.producttaxtype, SI1.ProductTaxType),
							cnf_matrixcell.taxtype,
							data_saleitem.unitprice,
							data_saleitem.quantity,
							DATA_SaleItem.UnitrawPrice, 
							SI1.UnitRawPrice,
							data_transaction.TransactionType,
							DATA_SaleItem.UnitTaxes,
							data_saleitem.UnitRecharge,
							data_transaction.TotalAmount,
							DATA_Sale.TotalAmount,
							data_transaction.Revenue,
							data_saleitem.basesaleid,
							data_transaction.totaltaxes,
							data_sale.totaltaxes,
							SI1.saleitemid


union 

select  @SuspendCOAAccountId as SuspendCOAAccountId,
						@SuspendRRRId as SuspendRRRId,
						@SuspendRRCalcTypeWhere as SuspendRRCalcTypeWhere,
						@SuspendRRCalcTypeMethod as SuspendRRCalcTypeMethod,
						@SuspendCOAAccountConfigId as SuspendCOAAccountConfigId,
						@SuspendCOAAccountTypeId as SuspendCOAAccountTypeId,
						data_transaction.transactionid, 
						data_transaction.saleid,
						null,
						DATA_SaleItem.saleitemid,
						CNF_MatrixCell.Matrixcellid,
						CNF_MatrixCell.MatrixSheetid,
						data_transaction.Siteid,
						data_transaction.OperatingAreaId,
						data_transaction.Workstationid,
						data_transaction.UserGroupid,
						data_transaction.UserId,
						@BatchDate as BatchDate,
						1 as Quantity,
						ISNULL(data_saleitem.unitprice, 0) as UnitAmount,
						ISNULL(data_saleitem.unitprice, 0) as GrossAmount,
						ISNULL((data_saleitem.unitprice - data_saleitem.UnitPrice), 0) as netprice,
						@SuspendPrice as SuspendPrice,
						@SuspendCOAAccount_Percentage as SuspendCOAAccount_Percentage,
						@SuspendRemainingValues as SuspendRemainingValues,
						ISNULL(case    			   
								when (ISNULL(data_saleitem.producttaxtype, 1) = 4) and (CNF_MatrixCell.TaxType = 1) then ((DATA_SaleItem.UnitPrice))
								when (ISNULL(data_saleitem.producttaxtype, 1) &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) 
											and (isnull((DATA_SaleItem.UnitrawPrice), 0) &lt;&gt; 0) and (((select sum(discountamount) from data_saleitemrule where saleitemid = DATA_SaleItem.saleitemid) &gt; 0) and (data_transaction.transactiontype in (7, 20, 22)))							
									then ((DATA_SaleItem.UnitRawPrice + data_saleitem.unitRecharge))								
								when (ISNULL(data_saleitem.producttaxtype, 1) &lt;&gt; 1) and (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitRawPrice), 0) &lt;&gt; 0 then (((DATA_SaleItem.UnitRawPrice - DATA_SaleItem.unittaxes) + data_saleitem.unitRecharge))
								when (ISNULL(data_saleitem.producttaxtype, 1) = 1) and isnull((DATA_SaleItem.UnitRawPrice), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitRawPrice - DATA_SaleItem.unittaxes + data_saleitem.unitRecharge))
								when (ISNULL(data_saleitem.producttaxtype, 1) &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) and isnull((DATA_SaleItem.UnitrawPrice), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice  + data_saleitem.unitRecharge))
								when (ISNULL(data_saleitem.producttaxtype, 1) = 1) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice - DATA_SaleItem.unittaxes + data_saleitem.unitRecharge))
								when (DATA_SaleItem.UnitPrice &lt;&gt; 0) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 and data_saleitem.unitRecharge = 0 and data_saleitem.basesaleid is not null														 
								then (select top 1 DS.UnitRawPrice
									from data_saleitem DS
									where DS.saleid = data_saleitem.basesaleid
										and DS.matrixcellid = CNF_MatrixCell.Matrixcellid)							 							 
								when (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 and data_saleitem.unitRecharge = 0 then 0
								when (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 and data_saleitem.unitRecharge &lt;&gt; 0 then data_saleitem.unitRecharge
							
							when isnull((data_transaction.TotalAmount), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - data_transaction.totaltaxes)
							
							
							
							when isnull((DATA_Sale.TotalAmount), 0) &lt;&gt; 0 then (DATA_Sale.TotalAmount - DATA_Sale.totaltaxes)
								else (data_transaction.Revenue)
							end, 0) as revenueamount,
						1 Accountingtype,
						@SuspendRRCalcTypeTrigger as SuspendRRCalcTypeTrigger,
						@SuspendPercentage as SuspendPercentage,
						@SuspendDays as SuspendDays

				from DATA_Sale WITH(NOLOCK)
					inner join data_transaction WITH(NOLOCK)			on  ((data_transaction.TransactionId = ISNULL(data_sale.voidtransactionid, DATA_Sale.PaidTransactionId)) 
																			or (data_transaction.Saleid = DATA_Sale.Saleid))
					left join DATA_TransactionItem						ON DATA_TRANSACTIONITEM.TRANSACTIONID = DATA_TRANSACTION.TRANSACTIONID
					left JOIN DATA_SaleItem							    on data_saleitem.SALEITEMID = DATA_TRANSACTIONITEM.saleitemid
					left join CNF_MatrixCell WITH(NOLOCK)				on CNF_MatrixCell.Matrixcellid = Coalesce(DATA_SaleItem.Matrixcellid, DATA_SaleItem.MatrixcellID)

				where DATA_Sale.Paid = 1
					and ISNULL(DATA_SaleItem.producttype, 0) IN (2, 5)
					and data_transaction.transactiontype  in (18, 20, 22)
					and data_saleitem.saleid = data_sale.saleid
					and ((@RRTransDateType = 0 and data_transaction.fTransactionDate = @BatchDate)
						OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
					and ((data_transaction.transactionid in (select data_payment.transactionid
															   from data_payment WITH(NOLOCK)
															  where PaymentStatus = 1
																--and paymentamount &lt;&gt; 0
																and ((@RRTransDateType = 0 and convert(date, data_payment.fPaymentDate) = @BatchDate)
															 		OR (@RRTransDateType = 1 and convert(date, data_payment.PaymentDate) = @BatchDate)) 										
																)))

			Group by	data_transaction.transactionid, 
							data_transaction.saleid,
							DATA_SaleItem.saleitemid,
							CNF_MatrixCell.Matrixcellid,
							CNF_MatrixCell.MatrixSheetid,
							data_transaction.Siteid,
							data_transaction.OperatingAreaId,
							data_transaction.Workstationid,
							data_transaction.UserGroupid,
							data_transaction.UserId,
							data_transaction.fTransactionDate,
							data_transaction.TransactionDate,
					
							data_saleitem.saleitemid,
							(data_saleitem.producttaxtype),
							cnf_matrixcell.taxtype,
							data_saleitem.unitprice,
							data_saleitem.quantity,
							DATA_SaleItem.UnitrawPrice, 
							data_transaction.TransactionType,
							DATA_SaleItem.UnitTaxes,
							data_saleitem.UnitRecharge,
							data_transaction.TotalAmount,
							DATA_Sale.TotalAmount,
							data_transaction.Revenue,
							data_saleitem.basesaleid,
							data_transaction.totaltaxes,
							data_sale.totaltaxes
		)P 
		where revenueamount &lt;&gt; 0	


--refund on tickets in contract	
		INSERT INTO [dbo].[RR_DATA_Revenue]
						([COAAccountId]
						,[RevenueRecognitionRuleId]
						,[RRCalcTypeWhere]
						,[RRCalcTypeMethod]
						,[COAAccountConfigId]
						,[COAAccountType]
						,[TransactionId]
						,[SaleId]
						,[ticketid]
						,[SaleItemId]
						,[MatrixCellId]
						,[MatrixSheetID]
						,[SiteId]
						,[OperatingAreaId]
						,[WorkstationId]
						,[UserGroupId]
						,[UserId]
						,[FCalcDate]
						,[Quantity]
						,[UnitAmount]
						,[GrossAmount]
						,[NetAmount]
						,[Price]
						,[Percentage]
						,[RemaningValues]
						,[RevenueAmount]
						,[AccountingType]
						,[RRCalcTypeTrigger]
						,[RRPercentage]
						,[RRDays])
		select *
		  from (
				select  @SuspendCOAAccountId as SuspendCOAAccountId,
						@SuspendRRRId as SuspendRRRId,
						@SuspendRRCalcTypeWhere as SuspendRRCalcTypeWhere,
						@SuspendRRCalcTypeMethod as SuspendRRCalcTypeMethod,
						@SuspendCOAAccountConfigId as SuspendCOAAccountConfigId,
						@SuspendCOAAccountTypeId as SuspendCOAAccountTypeId,
						data_transaction.transactionid, 
						data_transaction.saleid,
						DATA_Ticket.ticketid,
						DATA_SaleItem.saleitemid,
						CNF_MatrixCell.Matrixcellid,
						CNF_MatrixCell.MatrixSheetid,
						data_transaction.Siteid,
						data_transaction.OperatingAreaId,
						data_transaction.Workstationid,
						data_transaction.UserGroupid,
						data_transaction.UserId,
						@BatchDate as BatchDate,
						1 as Quantity,
						ISNULL(DATA_Ticket.price, 0) as UnitAmount,
						ISNULL(DATA_Ticket.Price, 0) as GrossAmount,
						ISNULL((DATA_Ticket.Price - data_ticket.taxes), 0) as netprice,
						@SuspendPrice as SuspendPrice,
						@SuspendCOAAccount_Percentage as SuspendCOAAccount_Percentage,
						@SuspendRemainingValues as SuspendRemainingValues,
						ISNULL(case when dr1.accountingtype = 1 and ISNULL((DATA_Ticket.Price - data_ticket.taxes) - sum(dr1.revenueamount), 0) &lt;&gt; 0 then DATA_Ticket.Price - data_ticket.taxes
								when dr1.accountingtype = 2 then (select sum(revenueamount) from rr_data_revenue where rr_data_revenue.ticketid = dr1.ticketid and accountingtype = 2)			   
								when (data_saleitem.producttaxtype = 4) and (CNF_MatrixCell.TaxType = 1) then ((DATA_SaleItem.UnitPrice))			      
							when (data_saleitem.ProductTaxType &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) and isnull((DATA_SaleItem.UnitrawPrice), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice  + data_saleitem.unitRecharge))
							when (data_saleitem.ProductTaxType = 1) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice - DATA_SaleItem.unittaxes + data_saleitem.unitRecharge))
							when (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 and data_saleitem.unitRecharge = 0 then 0
							when (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 and data_saleitem.unitRecharge &lt;&gt; 0 then data_saleitem.unitRecharge
							when isnull((data_transaction.TotalAmount), 0) &lt;&gt; 0 then data_transaction.TotalAmount
							when isnull((DATA_Sale.TotalAmount), 0) &lt;&gt; 0 then DATA_Sale.TotalAmount
							else (data_transaction.Revenue)
						end, 0) as revenueamount,
						1 Accountingtype,
						@SuspendRRCalcTypeTrigger as SuspendRRCalcTypeTrigger,
						@SuspendPercentage as SuspendPercentage,
						@SuspendDays as SuspendDays

				from DATA_Sale WITH(NOLOCK)
					inner join data_transaction WITH(NOLOCK)			on  ((data_transaction.TransactionId = ISNULL(data_sale.voidtransactionid, DATA_Sale.PaidTransactionId)) 
																			or (data_transaction.Saleid = DATA_Sale.Saleid))
					INNER JOIN data_saleitem WITH(NOLOCK)				on data_saleitem.saleid = data_sale.saleid	
					Left join CNF_MatrixCell WITH(NOLOCK)				on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
					LEFT JOIN DATA_TICKET WITH(NOLOCK)					on data_ticket.saleitemid = data_saleitem.saleitemid
					left join rr_data_revenue DR1 WITH(NOLOCK)			on dr1.ticketid = DATA_Ticket.ticketid and accountingtype = 1

				where ISNULL(DATA_SaleItem.producttype, 0) &lt;&gt; 6
				  and data_transaction.transactiontype  in (46, 47)
				  and ((@RRTransDateType = 0 and data_transaction.fTransactionDate = @BatchDate)
					  OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))

				Group by	data_transaction.transactionid, 
							data_transaction.saleid,
							DATA_Ticket.ticketid,
							DATA_SALEITEM.saleitemid,
							CNF_MatrixCell.Matrixcellid,
							CNF_MatrixCell.MatrixSheetid,
							data_transaction.Siteid,
							data_transaction.OperatingAreaId,
							data_transaction.Workstationid,
							data_transaction.UserGroupid,
							data_transaction.UserId,
							data_transaction.fTransactionDate,
							data_transaction.TransactionDate,
							DATA_Ticket.price,
							DATA_Ticket.Price,
							data_ticket.taxes,
							dr1.accountingtype,
							dr1.ticketid,
							data_saleitem.saleitemid,
							data_saleitem.producttaxtype,
							cnf_matrixcell.taxtype,
							data_saleitem.unitprice,
							data_saleitem.quantity,
							DATA_SaleItem.UnitrawPrice,
							data_transaction.TransactionType,
							DATA_SaleItem.UnitTaxes,
							data_saleitem.UnitRecharge,
							data_transaction.TotalAmount,
							DATA_Sale.TotalAmount,
							data_transaction.Revenue
		)P 
		where revenueamount &lt;&gt; 0


		INSERT INTO [dbo].[RR_DATA_Revenue]
						([COAAccountId]
						,[RevenueRecognitionRuleId]
						,[RRCalcTypeWhere]
						,[RRCalcTypeMethod]
						,[COAAccountConfigId]
						,[COAAccountType]
						,[TransactionId]
						,[SaleId]
						,[ticketid]
						,[SaleItemId]
						,[MatrixCellId]
						,[MatrixSheetID]
						,[SiteId]
						,[OperatingAreaId]
						,[WorkstationId]
						,[UserGroupId]
						,[UserId]
						,[FCalcDate]
						,[Quantity]
						,[UnitAmount]
						,[GrossAmount]
						,[NetAmount]
						,[Price]
						,[Percentage]
						,[RemaningValues]
						,[RevenueAmount]
						,[AccountingType]
						,[RRCalcTypeTrigger]
						,[RRPercentage]
						,[RRDays])
		select  SuspendCOAAccountId,
						SuspendRRRId,
						SuspendRRCalcTypeWhere,
						SuspendRRCalcTypeMethod,
						SuspendCOAAccountConfigId,
						SuspendCOAAccountTypeId,
						transactionid, 
						saleid,
						ticketid,
						saleitemid,
						Matrixcellid,
						MatrixSheetid,
						Siteid,
						OperatingAreaId,
						Workstationid,
						UserGroupid,
						UserId,
						BatchDate,
						Quantity,
						UnitAmount,
						GrossAmount,
						netprice,
						SuspendPrice,
						SuspendCOAAccount_Percentage,
						SuspendRemainingValues,
						ISNULL(ABS(revenueamount - case when RowNum = 1 then  (select sum(totalamount) 
																		 from data_transaction DT WITH(NOLOCK) 
																		where DT.saleid = p.saleid 
																		  and dt.transactiontype in (45, 44, 46, 47, 33))
												 else 0
											end), 0)
						
						
						revenueamount,	
						 Accountingtype,
						SuspendRRCalcTypeTrigger,
						SuspendPercentage,
						SuspendDays
		  from (
				select  @SuspendCOAAccountId as SuspendCOAAccountId,
						@SuspendRRRId as SuspendRRRId,
						@SuspendRRCalcTypeWhere as SuspendRRCalcTypeWhere,
						@SuspendRRCalcTypeMethod as SuspendRRCalcTypeMethod,
						@SuspendCOAAccountConfigId as SuspendCOAAccountConfigId,
						@SuspendCOAAccountTypeId as SuspendCOAAccountTypeId,
						data_transaction.transactionid, 
						data_transaction.saleid,
						DATA_Ticket.ticketid,
						DATA_Ticket.saleitemid,
						CNF_MatrixCell.Matrixcellid,
						CNF_MatrixCell.MatrixSheetid,
						data_transaction.Siteid,
						data_transaction.OperatingAreaId,
						data_transaction.Workstationid,
						data_transaction.UserGroupid,
						data_transaction.UserId,
						@BatchDate as BatchDate,
						1 as Quantity,
						ISNULL(DATA_Ticket.price, 0) as UnitAmount,
						ISNULL(DATA_Ticket.Price, 0) as GrossAmount,
						ISNULL((DATA_Ticket.Price - data_ticket.taxes), 0) as netprice,
						@SuspendPrice as SuspendPrice,
						@SuspendCOAAccount_Percentage as SuspendCOAAccount_Percentage,
						@SuspendRemainingValues as SuspendRemainingValues,
						ISNULL((select sum(paymentamount)
						   from data_payment WITH(NOLOCK)
						  where data_payment.transactionid = data_transaction.transactionid
						), ISNULL(DATA_Ticket.Price, 0) ) as RevenueAmount,	
						1 Accountingtype,
						@SuspendRRCalcTypeTrigger as SuspendRRCalcTypeTrigger,
						@SuspendPercentage as SuspendPercentage,
						@SuspendDays as SuspendDays,
						ROW_NUMBER ( )    OVER (Partition by data_transaction.transactionid order by data_transaction.transactionid ) RowNum

				from DATA_Sale
					inner join data_transaction				on  ((data_transaction.TransactionId = ISNULL(data_sale.voidtransactionid, DATA_Sale.PaidTransactionId)) 
																		or (data_transaction.Saleid = DATA_Sale.Saleid))
					LEFT JOIN data_transaction2ticket		on data_transaction2ticket.transactionid = data_transaction.transactionid
					LEFT JOIN DATA_SaleItem SI1				on SI1.saleid = data_transaction.saleid
					LEFT JOIN data_ticket	DT1				on DT1.saleitemid = si1.saleitemid
					LEFT JOIN DATA_Ticket					on data_ticket.ticketid = ISNULL(data_transaction2ticket.ticketid, dt1.ticketid)
					LEFT JOIN DATA_SaleItem					on data_saleitem.saleitemid = data_ticket.saleitemid
					left join rr_data_revenue DR1			on dr1.ticketid = DATA_Ticket.ticketid and accountingtype = 1
					left join CNF_MatrixCell				on CNF_MatrixCell.Matrixcellid = ISNULL(DATA_SaleItem.Matrixcellid, SI1.MatrixcellID)
					left join DATA_PaymentFlex2SaleItem		on data_paymentflex2saleitem.saleitemid = data_ticket.saleitemid
					left join DATA_PaymentFlex				on data_paymentflex.paymentid = data_paymentflex2saleitem.paymentid

				where DATA_Sale.Paid = 1
				  and ISNULL(DATA_SaleItem.producttype, 0) &lt;&gt; 6
				  and data_transaction.transactiontype  in (51)
				  and ((@RRTransDateType = 0 and data_transaction.fTransactionDate = @BatchDate)
					  OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
				  --and data_transaction.transactionid in (select data_payment.transactionid   
						--								   from data_payment WITH(NOLOCK)
						--								  where data_payment.transactionid = data_transaction.transactionid
						--								    and data_payment.paymentstatus = 1
						--								)

				Group by	data_transaction.transactionid, 
							data_transaction.saleid,
							DATA_Ticket.ticketid,
							DATA_Ticket.saleitemid,
							CNF_MatrixCell.Matrixcellid,
							CNF_MatrixCell.MatrixSheetid,
							data_transaction.Siteid,
							data_transaction.OperatingAreaId,
							data_transaction.Workstationid,
							data_transaction.UserGroupid,
							data_transaction.UserId,
							data_transaction.fTransactionDate,
							data_transaction.TransactionDate,
							DATA_Ticket.price,
							DATA_Ticket.Price,
							data_ticket.taxes,
							dr1.accountingtype,
							dr1.ticketid,
							data_saleitem.saleitemid,
							data_saleitem.producttaxtype,
							cnf_matrixcell.taxtype,
							data_saleitem.unitprice,
							data_saleitem.quantity,
							DATA_SaleItem.UnitrawPrice,
							data_transaction.TransactionType,
							DATA_SaleItem.UnitTaxes,
							data_saleitem.UnitRecharge,
							data_transaction.TotalAmount,
							DATA_Sale.TotalAmount,
							data_transaction.Revenue,
							data_paymentflex.downpaymentamount,
							downpaymentfeeamount,
							TaxInDownPaymentAmount
		)P 
		where revenueamount &lt;&gt; 0	

						
		INSERT INTO [dbo].[RR_DATA_Revenue]
						([COAAccountId]
						,[RevenueRecognitionRuleId]
						,[RRCalcTypeWhere]
						,[RRCalcTypeMethod]
						,[COAAccountConfigId]
						,[COAAccountType]
						,[TransactionId]
						,[SaleId]
						,[ticketid]
						,[SaleItemId]
						,[MatrixCellId]
						,[MatrixSheetID]
						,[SiteId]
						,[OperatingAreaId]
						,[WorkstationId]
						,[UserGroupId]
						,[UserId]
						,[FCalcDate]
						,[Quantity]
						,[UnitAmount]
						,[GrossAmount]
						,[NetAmount]
						,[Price]
						,[Percentage]
						,[RemaningValues]
						,[RevenueAmount]
						,[AccountingType]
						,[RRCalcTypeTrigger]
						,[RRPercentage]
						,[RRDays]
						,[AttributeIDS])
		select  @SuspendCOAAccountId,
				@SuspendRRRId,
				@SuspendRRCalcTypeWhere,
				@SuspendRRCalcTypeMethod,
				@SuspendCOAAccountConfigId,
				@SuspendCOAAccountTypeId,
				data_transaction.transactionid, 
				data_transaction.saleid,
				DATA_Ticket.TicketID,
				DATA_TransactionItem.saleitemid,
				DATA_SaleItem.Matrixcellid,
				CNF_MatrixCell.MatrixSheetid,
				data_transaction.Siteid,
				data_transaction.OperatingAreaId,
				data_transaction.Workstationid,
				data_transaction.UserGroupid,
				data_transaction.UserId,
				@BatchDate,
				case when ((data_ticket.ticketid is null) or (cnf_matrixsheet.producttype &lt;&gt; 1)) then data_saleitem.quantity else 1 end as Quantity,
				DATA_SaleItem.UnitPrice,
				case when isnull(DATA_TransactionItem.TotalAmount, 0) &lt;&gt; 0 then DATA_TransactionItem.TotalAmount
					 when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
					 else DATA_Sale.TotalAmount
				end,
				case when isnull((DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes)
					 when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
					 else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
				end as NetAmount,
				@SuspendPrice,
				@SuspendCOAAccount_Percentage,
				@SuspendRemainingValues,
				ISNULL(DATA_SaleItem.Unitrecharge, 0) unitcharge,
				@SuspendRRCOAAccountingType Accountingtype,
				@SuspendRRCalcTypeTrigger,
				@SuspendPercentage,
				@SuspendDays,
				CNF_AttributeSet.Attributeids
	   
		from DATA_Sale WITH(NOLOCK)
			inner join data_transaction WITH(NOLOCK)			on data_transaction.TransactionId = DATA_Sale.PaidTransactionId
			left join DATA_TransactionItem WITH(NOLOCK)			on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
			left join DATA_SaleItem WITH(NOLOCK)			    on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
			left join CNF_MatrixCell WITH(NOLOCK)				on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
			left join CNF_MatrixSheet WITH(NOLOCK)				on cnf_matrixsheet.matrixsheetid = cnf_matrixcell.matrixsheetid
			left join CNF_AttributeSet WITH(NOLOCK)				on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId
			left join data_saleitem2ticket WITH(NOLOCK)			on data_saleitem2ticket.saleitemid = data_saleitem.saleitemid
			left join DATA_Ticket WITH(NOLOCK)					on data_ticket.ticketid = data_saleitem2ticket.ticketid 

		where DATA_Sale.Paid = 1
		  and ISNULL(DATA_SaleItem.producttype, 0) &lt;&gt; 6
		  and data_transaction.transactiontype in (10, 42, 43, 49)
		  and ((@RRTransDateType = 0 and data_transaction.fTransactionDate = @BatchDate)
			  OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
		  and data_transaction.transactionid in (select transactionid
												   from data_payment WITH(NOLOCK)
												  where PaymentStatus = 1
													and PaymentAmount &lt;&gt; 0
													and ((@RRTransDateType = 0 and convert(date, data_payment.fPaymentdate) = @BatchDate)
														OR (@RRTransDateType = 1 and convert(date, data_payment.PaymentDate) = @BatchDate))
												)
		

		INSERT INTO [dbo].[RR_DATA_Revenue]
						([COAAccountId]
						,[RevenueRecognitionRuleId]
						,[RRCalcTypeWhere]
						,[RRCalcTypeMethod]
						,[COAAccountConfigId]
						,[COAAccountType]
						,[TransactionId]
						,[SaleId]
						,[TicketID]
						,[SaleItemId]
						,[MatrixCellId]
						,[MatrixSheetID]
						,[SiteId]
						,[OperatingAreaId]
						,[WorkstationId]
						,[UserGroupId]
						,[UserId]
						,[FCalcDate]
						,[Quantity]
						,[UnitAmount]
						,[GrossAmount]
						,[NetAmount]
						,[Price]
						,[Percentage]
						,[RemaningValues]
						,[RevenueAmount]
						,[AccountingType]
						,[RRCalcTypeTrigger]
						,[RRPercentage]
						,[RRDays]
						,[AttributeIDS])
		select  @SuspendCOAAccountId,
				@SuspendRRRId,
				@SuspendRRCalcTypeWhere,
				@SuspendRRCalcTypeMethod,
				@SuspendCOAAccountConfigId,
				@SuspendCOAAccountTypeId,
				data_transaction.transactionid, 
				data_transaction.saleid,
				data_ticket.ticketid,
				DATA_TransactionItem.saleitemid,
				DATA_SaleItem.Matrixcellid,
				CNF_MatrixCell.MatrixSheetid,
				data_transaction.Siteid,
				data_transaction.OperatingAreaId,
				data_transaction.Workstationid,
				data_transaction.UserGroupid,
				data_transaction.UserId,
				@BatchDate,
				case when ((data_ticket.ticketid is null) or (cnf_matrixsheet.producttype &lt;&gt; 1)) then data_saleitem.quantity else 1 end as Quantity,
				DATA_SaleItem.UnitPrice,
				case when isnull(DATA_TransactionItem.TotalAmount, 0) &lt;&gt; 0 then DATA_TransactionItem.TotalAmount
					 when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
					 else DATA_Sale.TotalAmount
				end,
				case when isnull((DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes)
					 when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
					 else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
				end as NetAmount,
				@SuspendPrice,
				@SuspendCOAAccount_Percentage,
				@SuspendRemainingValues,
				ISNULL(ABS(DATA_SaleItem.Unitrecharge), 0) Revenue,
				1 Accountingtype,
				@SuspendRRCalcTypeTrigger,
				@SuspendPercentage,
				@SuspendDays,
				CNF_AttributeSet.Attributeids
	   
		from DATA_Sale WITH(NOLOCK)
			inner join data_transaction	WITH(NOLOCK)		on data_transaction.TransactionId = ISNULL(data_sale.voidtransactionid, DATA_Sale.PaidTransactionId)
			left join DATA_TransactionItem WITH(NOLOCK)		on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
			left join DATA_SaleItem WITH(NOLOCK)			on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
			left join CNF_MatrixCell WITH(NOLOCK)			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
			left join CNF_MatrixSheet WITH(NOLOCK)			on cnf_matrixsheet.matrixsheetid = cnf_matrixcell.matrixsheetid
			left join CNF_AttributeSet WITH(NOLOCK)			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId
			left join data_saleitem2ticket WITH(NOLOCK)		on data_saleitem2ticket.saleitemid = data_saleitem.saleitemid
			left join DATA_Ticket WITH(NOLOCK)				on data_ticket.ticketid = data_saleitem2ticket.ticketid 

		where DATA_Sale.Paid = 1
		  and ISNULL(DATA_SaleItem.producttype, 0) &lt;&gt; 6
		  and data_transaction.transactiontype in (31, 48, 52)
		  and ((@RRTransDateType = 0 and data_transaction.fTransactionDate = @BatchDate)
			  OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
		  and data_transaction.transactionid in (select transactionid
												   from data_payment WITH(NOLOCK)
												  where PaymentStatus = 1
													and PaymentAmount &lt;&gt; 0
													and ((@RRTransDateType = 0 and convert(date, data_payment.fPaymentdate) = @BatchDate)
														OR (@RRTransDateType = 1 and convert(date, data_payment.PaymentDate) = @BatchDate))
												)


		INSERT INTO [dbo].[RR_DATA_Revenue]
						([COAAccountId]
						,[RevenueRecognitionRuleId]
						,[RRCalcTypeWhere]
						,[RRCalcTypeMethod]
						,[COAAccountConfigId]
						,[COAAccountType]
						,[TransactionId]
						,[SaleId]
						,[SaleItemId]
						,[MatrixCellId]
						,[MatrixSheetID]
						,[SiteId]
						,[OperatingAreaId]
						,[WorkstationId]
						,[UserGroupId]
						,[UserId]
						,[FCalcDate]
						,[Quantity]
						,[UnitAmount]
						,[GrossAmount]
						,[NetAmount]
						,[Price]
						,[Percentage]
						,[RemaningValues]
						,[RevenueAmount]
						,[AccountingType]
						,[RRCalcTypeTrigger]
						,[RRPercentage]
						,[RRDays]
						,[AttributeIDS])
		select  @SuspendCOAAccountId,
				@SuspendRRRId,
				@SuspendRRCalcTypeWhere,
				@SuspendRRCalcTypeMethod,
				@SuspendCOAAccountConfigId,
				@SuspendCOAAccountTypeId,
				data_transaction.transactionid, 
				data_transaction.saleid,
				DATA_TransactionItem.saleitemid,
				DATA_SaleItem.Matrixcellid,
				CNF_MatrixCell.MatrixSheetid,
				data_transaction.Siteid,
				data_transaction.OperatingAreaId,
				data_transaction.Workstationid,
				data_transaction.UserGroupid,
				data_transaction.UserId,
				@BatchDate,
				Coalesce(DATA_TransactionItem.Quantity, 1),
				DATA_SaleItem.UnitPrice,
				case when isnull(DATA_TransactionItem.TotalAmount, 0) &lt;&gt; 0 then DATA_TransactionItem.TotalAmount
					 when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
					 else DATA_Sale.TotalAmount
				end,
				case when isnull((DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes)
					 when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
					 else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
				end as NetAmount,
				@SuspendPrice,
				@SuspendCOAAccount_Percentage,
				@SuspendRemainingValues,
				ISNULL(case when (data_saleitem.producttaxtype = 4) and (CNF_MatrixCell.TaxType = 1) then ((DATA_SaleItem.UnitPrice) * DATA_SaleItem.Quantity)
					 when (data_saleitem.ProductTaxType &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice + DATA_SaleItem.unittaxes) * DATA_SaleItem.Quantity)
					 when (data_saleitem.ProductTaxType = 1) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice) * DATA_SaleItem.Quantity)
					 when (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 then 0
					 when isnull((data_transaction.TotalAmount), 0) &lt;&gt; 0 then data_transaction.TotalAmount
					 when isnull((DATA_Sale.TotalAmount), 0) &lt;&gt; 0 then DATA_Sale.TotalAmount
					 else (data_transaction.Revenue)
				end, 0),
				case when @SuspendRRCOAAccountingType = 1 then 2
					 when @SuspendRRCOAAccountingType = 2 then 1
					 else @SuspendRRCOAAccountingType
				end Accountingtype,
				@SuspendRRCalcTypeTrigger,
				@SuspendPercentage,
				@SuspendDays,
				CNF_AttributeSet.Attributeids
	   
		from DATA_Sale WITH(NOLOCK)
			inner join data_transaction WITH(NOLOCK)			on data_transaction.Saleid = DATA_Sale.Saleid
			left join DATA_TransactionItem WITH(NOLOCK)			on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
			left join DATA_SaleItem	WITH(NOLOCK)			    on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
			left join CNF_MatrixCell WITH(NOLOCK)				on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
			left join CNF_AttributeSet WITH(NOLOCK)				on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

		where data_transaction.transactiontype in (8)
		  and ISNULL(DATA_SaleItem.producttype, 0) &lt;&gt; 6
		  and ((@RRTransDateType = 0 and data_transaction.fTransactionDate = @BatchDate)
			  OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
		  and data_transaction.transactionid in (select transactionid
												   from data_payment WITH(NOLOCK)
												  where PaymentStatus = 1
													and PaymentAmount &lt;&gt; 0
													and ((@RRTransDateType = 0 and convert(date, data_payment.fPaymentDate) = @BatchDate)
														OR (@RRTransDateType = 1 and convert(date, data_payment.Paymentdate) = @BatchDate))
					 							)


--No Tickets on Reservation Deposits
		INSERT INTO [dbo].[RR_DATA_Revenue]
						([COAAccountId]
						,[RevenueRecognitionRuleId]
						,[RRCalcTypeWhere]
						,[RRCalcTypeMethod]
						,[COAAccountConfigId]
						,[COAAccountType]
						,[TransactionId]
						,[SaleId]
						,[SiteId]
						,[OperatingAreaId]
						,[WorkstationId]
						,[UserGroupId]
						,[UserId]
						,[FCalcDate]
						,[Quantity]
						,[GrossAmount]
						,[NetAmount]
						,[Price]
						,[Percentage]
						,[RemaningValues]
						,[RevenueAmount]
						,[AccountingType]
						,[RRCalcTypeTrigger]
						,[RRPercentage]
						,[RRDays])
		select  @SuspendCOAAccountId,
				@SuspendRRRId,
				@SuspendRRCalcTypeWhere,
				@SuspendRRCalcTypeMethod,
				@SuspendCOAAccountConfigId,
				@SuspendCOAAccountTypeId,
				data_transaction.transactionid, 
				data_transaction.saleid,
				data_transaction.Siteid,
				data_transaction.OperatingAreaId,
				data_transaction.Workstationid,
				data_transaction.UserGroupid,
				data_transaction.UserId,
				@BatchDate,
				0 Quantity,
				data_transaction.revenue TotalAmount,
				data_transaction.revenue NetAmount,
				@SuspendPrice,
				@SuspendCOAAccount_Percentage,
				@SuspendRemainingValues,
				data_transaction.revenue,
				ISNULL(case when data_transaction.revenue &lt; 0 then 1
				     else @SuspendRRCOAAccountingType
				 end, 0) ,
				@SuspendRRCalcTypeTrigger,
				@SuspendPercentage,
				@SuspendDays
	   
		from DATA_Sale WITH(NOLOCK)
			inner join data_transaction WITH(NOLOCK)			on data_transaction.saleid = DATA_Sale.saleid

		where data_transaction.transactiontype in (12, 15)
		  and ((@RRTransDateType = 0 and data_transaction.fTransactionDate = @BatchDate)
			  OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
		  and data_transaction.transactionid in (select transactionid
												   from data_payment WITH(NOLOCK)
												  where PaymentStatus = 1
													and PaymentAmount &lt;&gt; 0
													and ((@RRTransDateType = 0 and convert(date, data_payment.fpaymentDate) = @BatchDate)
														OR (@RRTransDateType = 1 and convert(date, data_payment.PaymentDate) = @BatchDate))
												)


		INSERT INTO [dbo].[RR_DATA_Revenue]
						([COAAccountId]
						,[RevenueRecognitionRuleId]
						,[RRCalcTypeWhere]
						,[RRCalcTypeMethod]
						,[COAAccountConfigId]
						,[COAAccountType]
						,[TransactionId]
						,[SaleId]
						,[TicketID]
						,[SaleItemId]
						,[MatrixCellId]
						,[MatrixSheetID]
						,[SiteId]
						,[OperatingAreaId]
						,[WorkstationId]
						,[UserGroupId]
						,[UserId]
						,[FCalcDate]
						,[Quantity]
						,[UnitAmount]
						,[GrossAmount]
						,[NetAmount]
						,[Price]
						,[Percentage]
						,[RemaningValues]
						,[RevenueAmount]
						,[AccountingType]
						,[RRCalcTypeTrigger]
						,[RRPercentage]
						,[RRDays]
						,[AttributeIDS])
		select *
		  from (
				select  @SuspendCOAAccountId as COAAccountId,
						@SuspendRRRId as RevenueRecognitionRuleId,
						@SuspendRRCalcTypeWhere as RRCalcTypeWhere,
						@SuspendRRCalcTypeMethod as RRCalcTypeMethod,
						@SuspendCOAAccountConfigId as COAAccountConfigId,
						@SuspendCOAAccountTypeId as COAAccountType,
						data_transaction.transactionid, 
						data_transaction.saleid,
						DATA_Ticket.Ticketid,
						DATA_SaleItem.saleitemid,
						DATA_SaleItem.Matrixcellid,
						CNF_MatrixCell.MatrixSheetid,
						data_transaction.Siteid,
						data_transaction.OperatingAreaId,
						data_transaction.Workstationid,
						data_transaction.UserGroupid,
						data_transaction.UserId,
						@BatchDate as calcdate,
						case when ((data_ticket.ticketid is null) or (cnf_matrixsheet.producttype &lt;&gt; 1)) then data_saleitem.quantity else 1 end as Quantity,
						DATA_SaleItem.UnitPrice,
						case when ((data_ticket.ticketid is null) or (cnf_matrixsheet.producttype &lt;&gt; 1)) then case when isnull((DATA_SaleItem.TotalAmount), 0) &lt;&gt; 0 then (DATA_SaleItem.TotalAmount)
																													when isnull((data_transaction.TotalAmount), 0) &lt;&gt; 0 then (data_transaction.TotalAmount)
																													else (DATA_Sale.TotalAmount)
																												end 
							 else	case when isnull((DATA_SaleItem.TotalAmount), 0) &lt;&gt; 0 then (DATA_SaleItem.TotalAmount)/DATA_SaleItem.Quantity
										when isnull((data_transaction.TotalAmount), 0) &lt;&gt; 0 then (data_transaction.TotalAmount)/DATA_SaleItem.Quantity
										else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
									end
						end as totalamount,

						case when ((data_ticket.ticketid is null) or (cnf_matrixsheet.producttype &lt;&gt; 1)) then case when isnull((DATA_SaleItem.TotalAmount - DATA_SaleItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_SaleItem.TotalAmount - DATA_SaleItem.TotalTaxes)
																													when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
																													else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
																												end 
							 else	case when isnull((DATA_SaleItem.TotalAmount - DATA_SaleItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_SaleItem.TotalAmount - DATA_SaleItem.TotalTaxes)/DATA_SaleItem.Quantity
										when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)/DATA_SaleItem.Quantity
										else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
									end
						end as NetAmount,
						@SuspendPrice as suspendprice,
						@SuspendCOAAccount_Percentage as percentage,
						@SuspendRemainingValues as remainingValues,
						ISNULL(case    when (data_ticket.ticketid is not null) and data_ticket.voidtype in (104, 125) and data_transaction.transactionstatus &lt;&gt; 5 then 0

						        when (data_ticket.ticketid is not null) and cnf_matrixsheet.producttype = 1 and (data_saleitem.producttaxtype = 4) and (CNF_MatrixCell.TaxType = 1) then (DATA_SaleItem.UnitPrice) 
								when (data_ticket.ticketid is not null) and cnf_matrixsheet.producttype = 1 and (data_saleitem.ProductTaxType &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then (DATA_SaleItem.UnitrawPrice )						
								when (data_ticket.ticketid is not null) and cnf_matrixsheet.producttype = 1 and (data_saleitem.ProductTaxType = 1) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then (DATA_SaleItem.UnitrawPrice - DATA_SaleItem.unittaxes) 	
								
								when (data_saleitem.unitrecharge &lt;&gt; 0 and data_saleitem.unitrawprice = 0) then 0
								when (data_ticket.ticketid is not null) and cnf_matrixsheet.producttype = 1 and (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 then ISNULL((data_saleitem.unitrecharge * data_saleitem.quantity), 0)		
								

								when (data_ticket.ticketid is not null) and cnf_matrixsheet.producttype = 1 and isnull((data_transaction.TotalAmount), 0) &lt;&gt; 0 then data_transaction.TotalAmount - data_transaction.totaltaxes
								when (data_ticket.ticketid is not null) and cnf_matrixsheet.producttype = 1 and isnull((DATA_Sale.TotalAmount), 0) &lt;&gt; 0 then DATA_Sale.TotalAmount
								when (data_saleitem.ProductTaxType &lt;&gt; 1 and data_ticket.ticketid is not null and (DATA_SaleItem.UnitrawPrice is not null) and isnull(DATA_SaleItem.UnitrawPrice, 0) &lt;&gt; 0) then (DATA_SaleItem.UnitrawPrice )
								when (data_saleitem.producttaxtype = 4 or data_ticket.ticketid is not null) and (CNF_MatrixCell.TaxType = 1) then ((DATA_SaleItem.UnitPrice) * DATA_SaleItem.Quantity)
								when (data_saleitem.ProductTaxType &lt;&gt; 1 or data_ticket.ticketid is not null) and (DATA_SaleItem.UnitrawPrice is not null) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice ) * DATA_SaleItem.Quantity)						

								when (data_saleitem.ProductTaxType = 1 or data_ticket.ticketid is not null) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice - DATA_SaleItem.unittaxes) * DATA_SaleItem.Quantity)										
								when (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 then ISNULL((data_saleitem.unitrecharge * data_saleitem.quantity), 0)				
								when isnull((data_transaction.TotalAmount), 0) &lt;&gt; 0 then data_transaction.TotalAmount
								when isnull((DATA_Sale.TotalAmount), 0) &lt;&gt; 0 then DATA_Sale.TotalAmount
								else (data_transaction.Revenue)
						end, 0) as Revenueamount,
						@SuspendRRCOAAccountingType Accountingtype,
						@SuspendRRCalcTypeTrigger as rrTrigger,
						@SuspendPercentage as suspercentage,
						@SuspendDays as suspendday,
						CNF_AttributeSet.Attributeids
	   
				from DATA_Sale WITH(NOLOCK)
					inner join data_transaction WITH(NOLOCK)				on data_transaction.TransactionId = DATA_Sale.PaidTransactionId
					left  join DATA_SaleItem WITH(NOLOCK)			    	on DATA_SaleItem.saleid = data_transaction.saleid
					left  join CNF_MatrixCell WITH(NOLOCK)					on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
					left  join CNF_MatrixSheet WITH(NOLOCK)					on cnf_matrixsheet.matrixsheetid = cnf_matrixcell.matrixsheetid
					left  join CNF_AttributeSet WITH(NOLOCK)				on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId
					left  join (select distinct ticketid, saleitemid, operationtype
										from data_saleitem2ticket)data_saleitem2ticket
								on data_saleitem2ticket.saleitemid = data_saleitem.saleitemid 
																				and data_saleitem2ticket.OperationType in (1, 11)
					left  join DATA_Ticket WITH(NOLOCK)						on data_ticket.ticketid = data_saleitem2ticket.ticketid 
					                                                       --   and voidtype not in (102)

				where DATA_Sale.Paid = 1
				  and ISNULL(DATA_SaleItem.producttype, 0) &lt;&gt; 6
				  and data_transaction.transactiontype in (16)
				  and ((@RRTransDateType = 0 and data_transaction.fTransactionDate = @BatchDate)
					  OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
				  and data_transaction.transactionid in (select transactionid
														  from data_payment WITH(NOLOCK)
														 where PaymentStatus = 1
														   
														)
				  and data_saleitem.saleitemid not in (select data_saleitem.saleitemid
														from data_saleitem WITH(NOLOCK)
															inner join data_transactionitem WITH(NOLOCK)   on data_transactionitem.saleitemid = data_saleitem.saleitemid
															inner join data_transaction WITH(NOLOCK)       on data_transaction.transactionid = data_transactionitem.transactionid
													   where data_transaction.transactiontype in (5)
													   )
		)p  
		where RevenueAmount &lt;&gt; 0


		INSERT INTO [dbo].[RR_DATA_Revenue]
						([COAAccountId]
						,[RevenueRecognitionRuleId]
						,[RRCalcTypeWhere]
						,[RRCalcTypeMethod]
						,[COAAccountConfigId]
						,[COAAccountType]
						,[TransactionId]
						,[SaleId]
						,[TicketID]
						,[SaleItemId]
						,[MatrixCellId]
						,[MatrixSheetID]
						,[SiteId]
						,[OperatingAreaId]
						,[WorkstationId]
						,[UserGroupId]
						,[UserId]
						,[FCalcDate]
						,[Quantity]
						,[UnitAmount]
						,[GrossAmount]
						,[NetAmount]
						,[Price]
						,[Percentage]
						,[RemaningValues]
						,[RevenueAmount]
						,[AccountingType]
						,[RRCalcTypeTrigger]
						,[RRPercentage]
						,[RRDays]
						,[AttributeIDS])
		select *
		from (
						select  @SuspendCOAAccountId as susCOA,
									@SuspendRRRId as RRID,
								
									@SuspendRRCalcTypeWhere as SusWhere,
									@SuspendRRCalcTypeMethod as Method,
									@SuspendCOAAccountConfigId as SusConfigID,
									@SuspendCOAAccountTypeId as SusCoaID,
							
									data_transaction.transactionid, 
									data_transaction.saleid,
									data_ticket.ticketid,
									SI.saleitemid,
									CNF_MatrixCell.Matrixcellid,
							
									CNF_MatrixCell.MatrixSheetid,
									data_transaction.Siteid,
									data_transaction.OperatingAreaId,
									data_transaction.Workstationid,
									data_transaction.UserGroupid,
									data_transaction.UserId,
									@BatchDate as BatchDate,
							
									case when ((data_ticket.ticketid is null) or (cnf_matrixsheet.producttype &lt;&gt; 1)) then ISNULL(SI.quantity, 1) else 1 end as Quantity,
									data_ticket.Price TickPrice,
									ISNULL(case when data_ticket.ticketid is not null then ABS(data_ticket.price) 
										 else SI.totalAmount
									end, 0) as GrossAmount,
									ISNULL(case when data_ticket.ticketid is not null then ABS(data_ticket.price - data_ticket.taxes) 
										 else (SI.totalAmount - SI.totaltaxes)					 
									end, 0)  as NetAmount,
									@SuspendPrice as Price,
									@SuspendCOAAccount_Percentage as susPerc,
									@SuspendRemainingValues as susremain,
									ISNULL(case when SI.saleitemid in (select saleitemid from data_saleitemrule where data_saleitemrule.saleitemid = SI.saleitemid) and data_ticket.ticketid is not null
																then SI.unitrawprice - SI.unitrecharge - SI.unittaxes
									            when data_ticket.ticketid is not null and ABS((data_ticket.price + SI.unitrecharge) - data_ticket.Taxes) &lt;&gt; 0 then ABS((data_ticket.price + SI.unitrecharge) - data_ticket.Taxes)
									            when data_ticket.ticketid is not null and ABS((data_ticket.price + SI.unitrecharge) - data_ticket.Taxes) = 0 then SI.UnitRawPrice
											   
											    when data_ticket.ticketid is null and (SI.TotalAmount + SI.unitrecharge) - SI.totaltaxes = 0 then SI.unitrecharge
										 else (SI.TotalAmount + SI.unitrecharge) - SI.totaltaxes
									 end, 0) RevenuAmount,
									case when @SuspendRRCOAAccountingType = 1 then 2
										 when @SuspendRRCOAAccountingType = 2 then 1
										 else @SuspendRRCOAAccountingType
									end Accountingtype,
									@SuspendRRCalcTypeTrigger as SusTrigger,
									@SuspendPercentage as Perc,
									@SuspendDays as Days,
									CNF_AttributeSet.Attributeids
	   
						from DATA_Sale WITH(NOLOCK)
								inner join data_transaction	WITH(NOLOCK)		on data_transaction.TransactionId = DATA_Sale.voidTransactionId
								left  join data_transaction2ticket WITH(NOLOCK)	on data_transaction2ticket.transactionid = data_transaction.transactionid		
								left join data_ticket WITH(NOLOCK)				on data_ticket.ticketid = data_transaction2ticket.ticketid
								left join CNF_MatrixCell WITH(NOLOCK)			on CNF_MatrixCell.Matrixcellid = data_ticket.Matrixcellid
								left join CNF_MatrixSheet WITH(NOLOCK)			on cnf_matrixsheet.matrixsheetid = cnf_matrixcell.matrixsheetid
								left join CNF_AttributeSet WITH(NOLOCK)			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId
									left join (select distinct Transactionid, UnitRawPrice, data_saleitem.TotalAmount, data_saleitem.unitrecharge, data_saleitem.unittaxes, data_saleitem.quantity, data_saleitem.producttype, data_saleitem.TotalTaxes, data_saleitem.saleitemid, origsaleitemid, data_saleitem2ticket.Ticketid
											 from data_saleitem WITH(NOLOCK)
													inner join data_saleitem2ticket WITH(NOLOCk)	on data_saleitem2ticket.saleitemid = data_saleitem.origsaleitemid
																										and data_saleitem2ticket.Operationtype = 2
													INNER JOIN data_transactionitem WITH(NOLOCK)    on data_transactionitem.saleitemid = data_saleitem.saleitemid
											where data_saleitem.quantity &lt; 0 
										  )SI						on SI.Ticketid = data_ticket.ticketid  and SI.Transactionid = data_transaction.Transactionid

							where DATA_Sale.Paid = 1
							  and ISNULL(SI.producttype, 0) &lt;&gt; 6
							  and data_transaction.transactiontype in (5)
							  and data_transaction.transactionstatus in (5)
							  and ((@RRTransDateType = 0 and data_transaction.fTransactionDate = @BatchDate)
								  OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))					
								and (data_transaction.transactionid in (select transactionid
																		from data_payment WITH(NOLOCK)
																	   where PaymentStatus = 1
																		 and PaymentAmount &lt;&gt; 0
																		 and ((@RRTransDateType = 0 and convert(date, data_payment.fpaymentDate) = @BatchDate)
																			 OR (@RRTransDateType = 1 and convert(date, data_payment.PaymentDate) = @BatchDate))

																		UNION ALL
																		select data_payment.transactionid
																		  from data_payment WITH(NOLOCK)
																			INNER JOIN data_transaction WITH(NOLOCK)    on data_transaction.transactionid = data_payment.transactionid
																			INNER JOIN data_saleitem WITH(NOLOCK)		on data_saleitem.saleid = data_transaction.saleid
																															and data_saleitem.quantity &lt; 0
																			INNER JOIN data_saleitemrule WITH(NOLOCK)   on data_saleitemrule.saleitemid = data_saleitem.saleitemid
															)
									)
							and PaidTransactionid is not null
							--and SI.saleitemid in (select saleitemid from data_transactionitem where data_transactionitem.transactionid = data_transaction.transactionid)

union

							select  @SuspendCOAAccountId as susCOA,
									@SuspendRRRId as RRID,
								
									@SuspendRRCalcTypeWhere as SusWhere,
									@SuspendRRCalcTypeMethod as Method,
									@SuspendCOAAccountConfigId as SusConfigID,
									@SuspendCOAAccountTypeId as SusCoaID,
								
									data_transaction.transactionid, 
									data_transaction.saleid,
									data_ticket.ticketid,
									data_saleitem.saleitemid,
									CNF_MatrixCell.Matrixcellid,
									CNF_MatrixCell.MatrixSheetid,
									data_transaction.Siteid,
									data_transaction.OperatingAreaId,
									data_transaction.Workstationid,
									data_transaction.UserGroupid,
									data_transaction.UserId,
									@BatchDate as BatchDate,
								
									case when ((data_ticket.ticketid is null) or (cnf_matrixsheet.producttype &lt;&gt; 1)) then ISNULL(data_saleitem.quantity, 1) else 1 end as Quantity,
									data_ticket.Price TickPrice,
									ISNULL(case when data_ticket.ticketid is not null then ABS(data_ticket.price) 
										 else data_saleitem.totalAmount
									end, 0) as GrossAmount,
									ISNULL(case when data_ticket.ticketid is not null then ABS(data_ticket.price - data_ticket.taxes) 
										 else (data_saleitem.totalAmount - data_saleitem.totaltaxes)					 
									end, 0)  as NetAmount,
									@SuspendPrice as Price,
									@SuspendCOAAccount_Percentage as susPerc,
									@SuspendRemainingValues as susremain,
									ISNULL(
									case when data_ticket.ticketid is not null then ABS((data_ticket.price + data_saleitem.unitrecharge) - data_ticket.taxes)							             
										 when (select discountamount from data_saleitemrule where data_saleitemrule.saleitemid = data_saleitem.saleitemid) &lt;&gt; 0 and
										        data_saleitem.TotalAmount = 0 then (select discountamount from data_saleitemrule where data_saleitemrule.saleitemid = data_saleitem.saleitemid)
										 when (select discountamount from data_saleitemrule where data_saleitemrule.saleitemid = data_saleitem.saleitemid) &lt;&gt; 0 and
										        data_saleitem.totalamount &lt;&gt; 0 and data_ticket.ticketid is null then data_saleitem.totalamount + (select discountamount from data_saleitemrule where data_saleitemrule.saleitemid = data_saleitem.saleitemid)
										 when (data_saleitem.TotalAmount + data_saleitem.unitrecharge) - data_saleitem.totaltaxes = 0 then data_saleitem.unitrecharge
										 else (data_saleitem.TotalAmount + data_saleitem.unitrecharge) - data_saleitem.totaltaxes
									 end
									 , 0) RevenuAmount,
									case when @SuspendRRCOAAccountingType = 1 then 2
										 when @SuspendRRCOAAccountingType = 2 then 1
										 else @SuspendRRCOAAccountingType
									end Accountingtype,
									@SuspendRRCalcTypeTrigger as SusTrigger,
									@SuspendPercentage as Perc,
									@SuspendDays as Days,
									CNF_AttributeSet.Attributeids
	   
					from DATA_Sale WITH(NOLOCK)
									inner join data_transaction	WITH(NOLOCK)		on data_transaction.TransactionId = DATA_Sale.voidTransactionId
									left  join data_transactionitem WITH(NOLOCK)	on data_transactionitem.transactionid = data_transaction.transactionid
									left join data_saleitem WITH(NOLOCK)			on data_saleitem.saleitemid = data_transactionitem.saleitemid
									left join data_saleitem2ticket WITH(NOLOCK)		on data_saleitem2ticket.saleitemid = data_saleitem.saleitemid		
									left join data_ticket WITH(NOLOCK)				on data_ticket.ticketid = data_saleitem2ticket.ticketid
									left join CNF_MatrixCell WITH(NOLOCK)			on CNF_MatrixCell.Matrixcellid = data_saleitem.Matrixcellid
									left join CNF_MatrixSheet WITH(NOLOCK)			on cnf_matrixsheet.matrixsheetid = cnf_matrixcell.matrixsheetid
									left join CNF_AttributeSet WITH(NOLOCK)			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId


								where DATA_Sale.Paid = 1
								  and ISNULL(data_saleitem.producttype, 0) &lt;&gt; 6
								  and data_transaction.transactionid not in (select transactionid from data_transaction2ticket)
								  and data_transaction.transactiontype in (5)
								  and data_transaction.transactionstatus in (5)
								  and ((@RRTransDateType = 0 and data_transaction.fTransactionDate = @BatchDate)
									  OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))					
								and PaidTransactionid is not null
								and (data_transaction.transactionid in (select transactionid
																		from data_payment WITH(NOLOCK)
																	   where PaymentStatus = 1
																		 and PaymentAmount &lt;&gt; 0
																		 and ((@RRTransDateType = 0 and convert(date, data_payment.fpaymentDate) = @BatchDate)
																			 OR (@RRTransDateType = 1 and convert(date, data_payment.PaymentDate) = @BatchDate))

																		UNION ALL
																		select data_payment.transactionid
																		  from data_payment WITH(NOLOCK)
																			INNER JOIN data_transaction WITH(NOLOCK)    on data_transaction.transactionid = data_payment.transactionid
																			INNER JOIN data_saleitem WITH(NOLOCK)		on data_saleitem.saleid = data_transaction.saleid
																															and data_saleitem.quantity &lt; 0
																			INNER JOIN data_saleitemrule WITH(NOLOCK)   on data_saleitemrule.saleitemid = data_saleitem.saleitemid
																		 where PaymentStatus = 1
																		 and PaymentAmount &lt;&gt; 0
															))

	union

							select  @SuspendCOAAccountId as susCOA,
									@SuspendRRRId as RRID,
								
									@SuspendRRCalcTypeWhere as SusWhere,
									@SuspendRRCalcTypeMethod as Method,
									@SuspendCOAAccountConfigId as SusConfigID,
									@SuspendCOAAccountTypeId as SusCoaID,
								
									data_transaction.transactionid, 
									data_transaction.saleid,
									data_ticket.ticketid,
									data_saleitem.saleitemid,
									CNF_MatrixCell.Matrixcellid,
								
									CNF_MatrixCell.MatrixSheetid,
									data_transaction.Siteid,
									data_transaction.OperatingAreaId,
									data_transaction.Workstationid,
									data_transaction.UserGroupid,
									data_transaction.UserId,
									@BatchDate as BatchDate,
								
									case when ((data_ticket.ticketid is null) or (cnf_matrixsheet.producttype &lt;&gt; 1)) then ISNULL(data_saleitem.quantity, 1) else 1 end as Quantity,
									data_ticket.Price TickPrice,
									ISNULL(case when data_ticket.ticketid is not null then ABS(data_ticket.price) 
										 else data_saleitem.totalAmount
									end, 0) as GrossAmount,
									ISNULL(case when data_ticket.ticketid is not null then ABS(data_ticket.price - data_ticket.taxes) 
										 else (data_saleitem.totalAmount - data_saleitem.totaltaxes)					 
									end, 0)  as NetAmount,
									@SuspendPrice as Price,
									@SuspendCOAAccount_Percentage as susPerc,
									@SuspendRemainingValues as susremain,
									ISNULL(case when data_ticket.ticketid is not null then ABS((data_ticket.price + data_saleitem.unitrecharge) - data_ticket.taxes)
									      when (data_saleitem.TotalAmount + data_saleitem.unitrecharge) - data_saleitem.totaltaxes = 0 then data_saleitem.unitrecharge
										 else (data_saleitem.TotalAmount + data_saleitem.unitrecharge) - data_saleitem.totaltaxes
									 end, 0) RevenuAmount,
									case when @SuspendRRCOAAccountingType = 1 then 2
										 when @SuspendRRCOAAccountingType = 2 then 1
										 else @SuspendRRCOAAccountingType
									end Accountingtype,
									@SuspendRRCalcTypeTrigger as SusTrigger,
									@SuspendPercentage as Perc,
									@SuspendDays as Days,
									CNF_AttributeSet.Attributeids
	   
					from DATA_Sale WITH(NOLOCK)
									inner join data_transaction	WITH(NOLOCK)		on data_transaction.TransactionId = DATA_Sale.voidTransactionId
									left  join data_transactionitem WITH(NOLOCK)	on data_transactionitem.transactionid = data_transaction.transactionid
									left join data_saleitem WITH(NOLOCK)			on data_saleitem.saleitemid = data_transactionitem.saleitemid
									left join data_saleitem2ticket WITH(NOLOCK)		on data_saleitem2ticket.saleitemid = data_saleitem.saleitemid		
									left join data_ticket WITH(NOLOCK)				on data_ticket.ticketid = data_saleitem2ticket.ticketid
									left join CNF_MatrixCell WITH(NOLOCK)			on CNF_MatrixCell.Matrixcellid = data_saleitem.Matrixcellid
									left join CNF_MatrixSheet WITH(NOLOCK)			on cnf_matrixsheet.matrixsheetid = cnf_matrixcell.matrixsheetid
									left join CNF_AttributeSet WITH(NOLOCK)			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId


								where DATA_Sale.Paid = 1
								  and ISNULL(data_saleitem.producttype, 0) &lt;&gt; 6
								  and data_saleitem.printoption = 4
								  and data_transaction.transactiontype in (5)
								  and data_transaction.transactionstatus in (5)
								  and ((@RRTransDateType = 0 and data_transaction.fTransactionDate = @BatchDate)
									  OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))					
									and data_transaction.transactionid in (select transactionid
																			from data_payment WITH(NOLOCK)
																		   where PaymentStatus = 1
																			 and PaymentAmount &lt;&gt; 0
																			 and ((@RRTransDateType = 0 and convert(date, data_payment.fpaymentDate) = @BatchDate)
																				 OR (@RRTransDateType = 1 and convert(date, data_payment.PaymentDate) = @BatchDate))
																		   )
								and PaidTransactionid is not null
								and (data_transaction.transactionid in (select transactionid
																		from data_payment WITH(NOLOCK)
																	   where PaymentStatus = 1
																		 and PaymentAmount &lt;&gt; 0
																		 and ((@RRTransDateType = 0 and convert(date, data_payment.fpaymentDate) = @BatchDate)
																			 OR (@RRTransDateType = 1 and convert(date, data_payment.PaymentDate) = @BatchDate))

																		UNION ALL
																		select data_payment.transactionid
																		  from data_payment WITH(NOLOCK)
																			INNER JOIN data_transaction WITH(NOLOCK)    on data_transaction.transactionid = data_payment.transactionid
																			INNER JOIN data_saleitem WITH(NOLOCK)		on data_saleitem.saleid = data_transaction.saleid
																															and data_saleitem.quantity &lt; 0
																			INNER JOIN data_saleitemrule WITH(NOLOCK)   on data_saleitemrule.saleitemid = data_saleitem.saleitemid
																		 where PaymentStatus = 1
																		 and PaymentAmount &lt;&gt; 0
															))
				)p

--PaymentMethod for Normal Payments
		INSERT INTO [dbo].[RR_DATA_Revenue]
						([COAAccountId]
						,[RevenueRecognitionRuleId]
						,[RRCalcTypeWhere]
						,[RRCalcTypeMethod]
						,[COAAccountConfigId]
						,[COAAccountType]
						,[TransactionId]
						,[SaleId]
						,[SiteId]
						,[OperatingAreaId]
						,[WorkstationId]
						,[UserGroupId]
						,[UserId]
						,[FCalcDate]
						,[Quantity]
						,[GrossAmount]
						,[NetAmount]
						,[Price]
						,[Percentage]
						,[RemaningValues]
						,[RevenueAmount]
						,[AccountingType]
						,[RRCalcTypeTrigger]
						,[RRPercentage]
						,[RRDays])
		select  coaaccountid,
				RRID,
				TypeWhere,
				method,
				Configid,
				AccountType,
				transactionid, 
				saleid,
				Siteid,
				OperatingAreaId,
				WorkstationID,
				UserGroupid,
				UserId,
				BatchDate,
				Qty,
				Gross,
				net,
				price,
				percentage,
				RemaningValue,
				ISNULL(abs(RevenueAmount), 0),
				Accountingtype,
				TypeTrigger,
				PaymentPercentage,
				RRDays
		  from (
				select  coaaccountid,
						RRID,
						TypeWhere,
						method,
						Configid,
						AccountType,
						transactionid, 
						saleid,
						Siteid,
						OperatingAreaId,
						WorkstationID,
						UserGroupid,
						UserId,
						BatchDate,
						Qty,
						Gross,
						net,
						price,
						percentage,
						RemaningValue,
						case when Rownumber = 1 then RevenueAmount + Change 
							 else RevenueAmount 
						 end RevenueAmount,
						Accountingtype,
						TypeTrigger,
						PaymentPercentage,
						RRDays
				from (
						select  @PaymentCOAAccountId as coaaccountid,
								@PaymentRRRId as RRID,
								@PaymentRRCalcTypeWhere as TypeWhere,
								@PaymentRRCalcTypeMethod as method,
								@PaymentCOAAccountConfigId as Configid,
								@PaymentCOAAccountTypeId as AccountType,
								data_transaction.transactionid, 
								data_transaction.saleid,
								data_transaction.Siteid,
								data_transaction.OperatingAreaId,
								data_transaction.Workstationid,
								data_transaction.UserGroupid,
								data_transaction.UserId,
								@BatchDate as BatchDate,
								0 as Qty,
								0 as Gross,
								0 as net,
								0 as price,
								100 as percentage,
								0 as RemaningValue,
								(Payment.PaymentAmount) as RevenueAmount,
								case when data_transaction.TransactionType NOT in (5, 8, 13, 17, 18, 20, 22, 30, 31, 40, 46, 47, 48, 52) and Payment.paymentamount &lt; 0 then 2
								     when data_transaction.TransactionType in (5, 8, 13, 17, 18, 20, 22, 30, 31, 40, 46, 47, 48, 52) and Payment.paymentamount &gt; 0 then 1
								     when data_transaction.TransactionType in (5, 8, 13, 17, 18, 20, 22, 30, 31, 40, 46, 47, 48, 52) and @PaymentRRCOAAccountingType = 1 then 2
									 when data_transaction.TransactionType in (5, 8, 13, 17, 18, 20, 22, 30, 31, 40, 46, 47, 48, 52) and @PaymentRRCOAAccountingType = 2 then 1
									 when data_transaction.TransactionType in (7) and (Payment.PaymentAmount + Payment.PaymentFee) &lt;= 0  then 2
									 when data_transaction.TransactionType in (7) and (Payment.PaymentAmount + Payment.PaymentFee) &gt; 0  then 1
									 when data_transaction.transactiontype = 14 and Payment.paymentamount &lt; 0 then 2
									 when data_transaction.transactiontype = 30 and Payment.paymentamount &lt; 0 then 1
									 else @PaymentRRCOAAccountingType
								end Accountingtype,
								data_transaction.Change,
								Payment.ChangeAmount,
								@PaymentRRCalcTypeTrigger as TypeTrigger,
								@PaymentPercentage as PaymentPercentage,
								@PaymentDays as RRDays,
								ISNULL((select sum(FeeAmount) as FeeAmount
										 from DATA_PaymentPlan2Transaction	
											INNER JOIN DATA_PaymentPlan			on data_paymentplan.paymentplanid = DATA_PaymentPlan2Transaction.paymentplanid
										 where DATA_PaymentPlan2Transaction.Transactionid = data_transaction.transactionid
										   and DATA_PaymentPlan2Transaction.flexpaymentstatus &lt;&gt; 5
										), 0) as fee,
								Row_Number ()  OVER (PARTITION BY data_transaction.transactionid order by data_transaction.transactionid, Payment.PaymentAmount desc)  as Rownumber
		  
						from DATA_Sale WITH(NOLOCK)
							INNER join data_transaction WITH(NOLOCK)			on (data_transaction.TransactionId = Isnull(data_sale.voidtransactionid, DATA_Sale.PaidTransactionId)) 
							LEFT JOIN (select data_transaction.saleid, data_payment.transactionid, data_payment.PaymentAmount, DATA_Payment.ChangeAmount, DATA_Payment.PaymentStatus, data_payment.PaymentFee,
							                  data_transaction.transactiontype
							             from data_payment WITH(NOLOCK)
											INNER JOIN data_transaction WITH(NOLOCK)		ON data_transaction.transactionid = data_payment.transactionid
										where data_payment.Paymentstatus = 1
									  ) Payment						ON payment.saleid = DATA_Sale.saleid 
									  --and payment.transactiontype = data_transaction.transactiontype
									   and payment.Transactionid = data_transaction.Transactionid
			
						where Payment.PaymentStatus = 1
						  and data_transaction.transactiontype not in (6, 4)	
						  and ((@RRTransDateType = 0 and data_transaction.fTransactionDate = @BatchDate)
							  OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
						  and ((data_transaction.transactiontype in (5, 30) and Payment.paymentamount &lt;= 0)
						   or data_transaction.transactiontype not in (5,30))

						UNION

						select  @PaymentCOAAccountId as coaaccountid,
								@PaymentRRRId as RRID,
								@PaymentRRCalcTypeWhere as TypeWhere,
								@PaymentRRCalcTypeMethod as method,
								@PaymentCOAAccountConfigId as Configid,
								@PaymentCOAAccountTypeId as AccountType,
								data_transaction.transactionid, 
								data_transaction.saleid,
								data_transaction.Siteid,
								data_transaction.OperatingAreaId,
								data_transaction.Workstationid,
								data_transaction.UserGroupid,
								data_transaction.UserId,
								@BatchDate as BatchDate,
								0 as Qty,
								0 as Gross,
								0 as net,
								0 as price,
								100 as percentage,
								0 as RemaningValue,
								case when transactiontype &lt;&gt; 45 then (data_payment.PaymentAmount)
										else (data_payment.PaymentAmount) 												 
								end as RevenueAmount,
								case when TransactionType NOT in (5, 8, 13, 17, 18, 20, 22, 30, 31, 40, 46, 47, 48, 52) and data_payment.paymentamount &lt; 0 then 2
								     when TransactionType in (5, 8, 13, 17, 18, 20, 22, 30, 31, 40, 46, 47, 48, 52) and data_payment.paymentamount &gt; 0 then 1
								     when TransactionType in (5, 8, 13, 17, 18, 20, 22, 30, 31, 40, 46, 47, 48, 52) and @PaymentRRCOAAccountingType = 1 then 2
									 when TransactionType in (5, 8, 13, 17, 18, 20, 22, 30, 31, 40, 46, 47, 48, 52) and @PaymentRRCOAAccountingType = 2 then 1
									 when TransactionType in (7) and (data_payment.PaymentAmount + data_Payment.PaymentFee) &lt;= 0  then 2
									 when TransactionType in (7) and (data_payment.PaymentAmount + data_Payment.PaymentFee) &gt; 0  then 1
									 when data_transaction.transactiontype = 14 and paymentamount &lt; 0 then 2
									 when data_transaction.transactiontype = 30 and paymentamount &lt; 0 then 1
									 else @PaymentRRCOAAccountingType
								end Accountingtype,
								data_transaction.Change,
								DATA_Payment.ChangeAmount,
								@PaymentRRCalcTypeTrigger as TypeTrigger,
								@PaymentPercentage as PaymentPercentage,
								@PaymentDays as RRDays,
								ISNULL((select sum(FeeAmount) as FeeAmount
										 from DATA_PaymentPlan2Transaction	
											INNER JOIN DATA_PaymentPlan			on data_paymentplan.paymentplanid = DATA_PaymentPlan2Transaction.paymentplanid
										 where DATA_PaymentPlan2Transaction.Transactionid = data_transaction.transactionid
										   and DATA_PaymentPlan2Transaction.flexpaymentstatus &lt;&gt; 5
										), 0) as fee,
								Row_Number ()  OVER (PARTITION BY data_transaction.transactionid order by data_transaction.transactionid, data_payment.PaymentAmount desc)  as Rownumber
		  
						from DATA_Sale WITH(NOLOCK)
							INNER join data_transaction WITH(NOLOCK)			on (data_transaction.saleid = data_sale.saleid)
							INNER JOIN DATA_Payment WITH(NOLOCK)				on data_payment.transactionid = data_transaction.transactionid
			
						where data_payment.PaymentStatus = 1
						   and data_transaction.transactiontype not in (6, 4)						   
						  and ((@RRTransDateType = 0 and data_transaction.fTransactionDate = @BatchDate)
							  OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
						  and ((data_transaction.transactiontype in (5, 30) and DATA_Payment.paymentamount &lt;= 0)
						       or data_transaction.transactiontype not in (5,30))
									
				)p
		)r
		where RevenueAmount &lt;&gt; 0
							
												
--Reversing the payment method for installment billing.  When ticket 79425 if done we should be able to remove this section.	
		INSERT INTO [dbo].[RR_DATA_Revenue]
						([COAAccountId]
						,[RevenueRecognitionRuleId]
						,[RRCalcTypeWhere]
						,[RRCalcTypeMethod]
						,[COAAccountConfigId]
						,[COAAccountType]
						,[TransactionId]
						,[SaleId]
						,[SiteId]
						,[OperatingAreaId]
						,[WorkstationId]
						,[UserGroupId]
						,[UserId]
						,[FCalcDate]
						,[Quantity]
						,[GrossAmount]
						,[NetAmount]
						,[Price]
						,[Percentage]
						,[RemaningValues]
						,[RevenueAmount]
						,[AccountingType]
						,[RRCalcTypeTrigger]
						,[RRPercentage]
						,[RRDays])
		select  coaaccountid,
				RRID,
				TypeWhere,
				method,
				Configid,
				AccountType,
				transactionid, 
				saleid,
				Siteid,
				OperatingAreaId,
				WorkstationID,
				UserGroupid,
				UserId,
				BatchDate,
				Qty,
				Gross,
				net,
				price,
				percentage,
				RemaningValue,
				ISNULL(sum(abs(RevenueAmount)), 0),
				Accountingtype,
				TypeTrigger,
				PaymentPercentage,
				RRDays
		  from (
				select  coaaccountid,
						RRID,
						TypeWhere,
						method,
						Configid,
						AccountType,
						transactionid, 
						saleid,
						Siteid,
						OperatingAreaId,
						WorkstationID,
						UserGroupid,
						UserId,
						BatchDate,
						Qty,
						Gross,
						net,
						price,
						percentage,
						RemaningValue,
						(ISNULL(Amount, 0) - ISNULL(TotalPaid, 0)) + Change RevenueAmount,
						Accountingtype,
						TypeTrigger,
						PaymentPercentage,
						RRDays
				  from (
						select	@PaymentCOAAccountId as coaaccountid,
								@PaymentRRRId as RRID,
								@PaymentRRCalcTypeWhere as TypeWhere,
								@PaymentRRCalcTypeMethod as method,
								@PaymentCOAAccountConfigId as Configid,
								@PaymentCOAAccountTypeId as AccountType,
								case when (ABS(data_payment.paymentamount) &gt; ISNULL(Item.feeamount, PF.feeamount)) then  ISNULL((Item.Amount), (PF.Amount) )
								     else ISNULL((Item.Amount - Item.feeamount), (PF.Amount - PF.feeamount) ) 
								 end as amount, 
								ISNULL(Item.refundablefeeamount, PF.refundablefeeamount)  feeamount,
								data_transaction.transactionid,
								data_transaction.saleid,
								data_transaction.siteid, 
								data_transaction.OperatingAreaId,
								data_transaction.Workstationid,
								data_transaction.UserGroupid,
								data_transaction.UserId,
								@BatchDate as BatchDate,
								0 as Qty,
								0 as Gross,
								0 as net,
								0 as price,
								100 as percentage,
								0 as RemaningValue,
								case when data_transaction.transactiontype = 47 then (ISNULL((select case when sum(DATA_PaymentPlan.refundablefeeamount) = 0 then (sum(DATA_PaymentPlan.amount) - sum(DATA_PaymentPlan.feeamount))
													else sum(DATA_PaymentPlan.amount)
												end TotalPaid
										from DATA_PaymentFlex PF
										INNER JOIN DATA_PaymentPlan			on DATA_PaymentPlan.PaymentID = PF.PaymentId
										where  PF.PaymentID = 	ITEM.Paymentid
											and DATA_PaymentPlan.Paymentmethodid is not null
											and paymentdate is not null), 
											(select case when sum(DATA_PaymentPlan.refundablefeeamount) = 0 then (sum(DATA_PaymentPlan.amount) - sum(DATA_PaymentPlan.feeamount))
													else sum(DATA_PaymentPlan.amount)
												end TotalPaid
										from DATA_PaymentFlex PF1
										INNER JOIN DATA_PaymentPlan			on DATA_PaymentPlan.PaymentID = PF1.PaymentId
										where  PF1.PaymentID = 	PF.Paymentid
											and DATA_PaymentPlan.Paymentmethodid is not null
											and paymentdate is not null)))
										else 0
										end as TotalPaid,
								2 Accountingtype,
								@PaymentRRCalcTypeTrigger as TypeTrigger,
								@PaymentPercentage as PaymentPercentage,
								@PaymentDays as RRDays,
								max(Item.saleitemid) SaleitemID,
								data_transaction.Change,
								(select sum(paymentamount)
								   from data_payment
								  where data_payment.transactionid = data_transaction.transactionid
								) as payment

							from data_transaction WITH(NOLOCK)
								LEFT  JOIN (select max(data_saleitem.saleitemid) Saleitemid,
								                   DATA_PaymentFlex.flexcontractID,
												   DATA_PaymentFlex.feeamount,
												   DATA_PaymentFlex.Amount,
												   data_paymentflex.refundablefeeamount,
												   data_saleitem.saleid,
												   DATA_PaymentFlex.Paymentid
												 

								              from  data_saleitem WITH(NOLOCK)	
													LEFT  JOIn data_Paymentflex2saleitem WITH(NOLOCK)		on data_Paymentflex2saleitem.saleitemid = data_saleitem.saleitemid
													LEFT  JOIN DATA_PaymentFlex WITH(NOLOCK)				on data_paymentflex.paymentid = data_Paymentflex2saleitem.paymentid
												where DATA_PaymentFlex.Amount is not null
											  group by   DATA_PaymentFlex.flexcontractID,
												   DATA_PaymentFlex.feeamount,
												   DATA_PaymentFlex.Amount,
												   data_paymentflex.refundablefeeamount,
												   data_saleitem.saleid,
												   DATA_PaymentFlex.Paymentid
											)Item						ON Item.saleid = data_transaction.saleid
								LEFT  JOIN CNF_FlexContract WITH(NOLOCK)				on cnf_flexContract.FlexContractId = ITEM.flexcontractID
								LEFT  JOIn data_transaction DT WITH(NOLOCK)				on DT.saleid = data_transaction.saleid and DT.transactiontype = 9
								LEFT  JOIN data_payment WITH(NOLOCK)					on data_payment.transactionid = DT.transactionid
								LEFT  JOIN DATA_PaymentFlex PF WITH(NOLOCK)				on PF.paymentid = data_payment.paymentid
								LEFT  JOIN CNF_FlexContract CF WITH(NOLOCK)				on CF.FlexContractId = PF.flexcontractID 

						  where data_transaction.transactiontype in (46, 47)
						     and data_transaction.transactiontype &lt;&gt; 6
							and ((@RRTransDateType = 0 and data_transaction.fTransactionDate = @BatchDate)
								OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
									
						group by    ITEM.Amount,
									data_transaction.transactionid,
									ITEM.Paymentid,
									data_transaction.saleid,
									data_transaction.siteid,
									data_transaction.OperatingAreaId,
									data_transaction.Workstationid,
									data_transaction.UserGroupid,
									data_transaction.UserId,
									data_transaction.TransactionDate,
									data_transaction.fTransactionDate,
									data_transaction.Change,
									data_transaction.transactiontype,
									ITEM.refundablefeeamount,
									ITEM.feeamount,
									PF.Amount,
									PF.feeamount,
									PF.refundablefeeamount,
									PF.Paymentid,
									data_payment.PaymentAmount
						)p
				)r
		group by 	coaaccountid,
					RRID,
					TypeWhere,
					method,
					Configid,
					AccountType,
					transactionid, 
					saleid,
					Siteid,
					OperatingAreaId,
					Workstationid,
					UserGroupid,
					UserId,
					BatchDate,
					Qty,
					Gross,
					net,
					price,
					percentage,
					RemaningValue,
					Accountingtype,
					TypeTrigger,
					PaymentPercentage,
					RRDays
		Having sum(abs(RevenueAmount)) &lt;&gt; 0
															
--Tax
					INSERT INTO [dbo].[RR_DATA_Revenue]
								([COAAccountId]
								,[RevenueRecognitionRuleId]
								,[RRCalcTypeWhere]
								,[RRCalcTypeMethod]
								,[COAAccountConfigId]
								,[COAAccountType]
								,[TransactionId]
								,[SaleId]
								,[SiteId]
								,[Saleitemid]
								,[Matrixcellid]
								,[Ticketid]
								,[OperatingAreaId]
								,[WorkstationId]
								,[UserGroupId]
								,[UserId]
								,[FCalcDate]
								,[Quantity]
								,[GrossAmount]
								,[NetAmount]
								,[Price]
								,[Percentage]
								,[RemaningValues]
								,[RevenueAmount]
								,[AccountingType]
								,[RRCalcTypeTrigger]
								,[RRPercentage]
								,[RRDays]
								,[AttributeIDs]
								,[SaleitemtaxID])
								select distinct coaid,
								       rrid,
									   rrWhere,
									   rrmethod,
									   configid,
									   typeid,
									   transactionid,
									   saleid,
									   siteid,
									   saleitemid,
									   matrixcellid,
									   ticketid,
									   operatingareaid,
									   workstationid,
									   usergroupid,
									   userid,
									   batchdate,
									   quantity,
									   grossamount,
									   netamount,
									   price,
									   perc,
									   rmvvalues,
									   ISNULL(revenueamount, 0) revenueamount,
									   accountingtype,
									   rrtrigger,
									   taxperc,
									   days,
									   Attributes,
									   SaleitemTaxID
								from (	
								select distinct @TaxCOAAccountId as coaid,
										@TaxRRRId as rrid,
										@TaxRRCalcTypeWhere as rrWhere,
										@TaxRRCalcTypeMethod as rrmethod,
										@TaxCOAAccountConfigId as configid,
										@TaxCOAAccountTypeId as typeid,
										data_transaction.transactionid, 
										data_transaction.saleid,
										data_transaction.Siteid,
										data_saleitem.saleitemid,
										data_saleitem.matrixcellid,
										COALESCE(COALESCE(data_ticket.ticketid, dt.ticketid, data_saleitem.Itemticketid, data_saleitem.Ticketid),
										(select max(DT.ticketid) as ticketid
												from data_ticket DT
												where DT.saleitemid = DATA_SaleItem.OrigSaleItemID),
										 ( case when ISNULL(DATA_SaleItem.producttype, 0) &lt;&gt; 6 then
										  (select top 1 ticketid
													from data_transaction2ticket
													where transactionid = DATA_Transaction.transactionid)
											else null
											end ) ) as ticketid,
										data_transaction.OperatingAreaId,
										data_transaction.Workstationid,
										data_transaction.UserGroupid,
										data_transaction.UserId,
										@BatchDate as BatchDate,
										0 Quantity,
										0 Grossamount,
										0 NetAmount,
										0 Price,
										100 Perc,
										0 RMVValues,
										ABS(case when (transactiontype in (5) and (select sum(totalamount) - sum(revenue)
																					from data_transaction
																					where transactiontype &lt;&gt; 5
																						and saleid = DATA_Sale.saleid) &lt;&gt; 0)  then 0
										         when (transactiontype in (5))  then sum(taxamount) * sum(DATA_SaleItem.Quantity)
										         when (transactiontype not in (5) and data_sale.StatusCode &lt;&gt; 1 and sum(DATA_SaleItem.Quantity) &lt; 0)  then 0									
										         when data_ticket.ticketid is not null then taxamount
												 else sum(taxamount) * (case when data_ticket.ticketid is null then sum(DATA_SaleItem.Quantity) else 1 end) 
										end)  revenueamount,


										case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 40, 46, 47) and @TaxRRCOAAccountingType = 1 then 2
												when TransactionType in (5, 8, 17, 18, 20, 22, 30, 40, 46, 47) and @TaxRRCOAAccountingType = 2 then 1
											    when TransactionType in (7) and DATA_SaleItem.totalamount &lt;= 0  then 1
												when TransactionType in (7) and DATA_SaleItem.totalamount &gt; 0  then 2
												else @TaxRRCOAAccountingType
									    end Accountingtype,
										@TaxRRCalcTypeTrigger as rrtrigger,
										@TaxPercentage as taxperc,
										@TaxDays as days,
										null Attributes,
										data_saleitemtax.saleitemtaxid
		   
							from Data_Sale WITH(NOLOCK)
								INNER JOIN DATA_Transaction WITH(NOLOCK)					on data_transaction.transactionid = Data_Sale.Paidtransactionid 
								left join DATA_TransactionItem WITH(NOLOCK)					on DATA_TransactionItem.TransactionId = data_transaction.TransactionId							                                                     
								left join DATA_SaleItem WITH(NOLOCK)						on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
								left join data_saleitem2ticket with(NOLOCK)					on data_saleitem2ticket.saleitemid = data_saleitem.saleitemid
								left join data_ticket WITH(NOLOCK)                          on data_ticket.ticketid = data_saleitem2ticket.ticketid
																							--   and voidtype not in (104, 125)
								left join data_saleitem2ticket SIT2 WITH(NOLOCK)			on SIT2.saleitemid = data_saleitem.saleitemid
								left join data_transaction2ticket WITH(NOLOCK)				on data_transaction2ticket.transactionid = DATA_Transaction.transactionid
																								and SIT2.ticketid = data_transaction2ticket.ticketid
								left join data_ticket DT WITH(NOLOCK)						on DT.Ticketid = data_transaction2ticket.ticketid

								left join DATA_SaleItemTax WITH(NOLOCK)						on data_saleitemtax.saleitemid = data_saleitem.saleitemid
								left JOIN CNF_Tax WITH(NOLOCK)								on cnf_tax.taxid = data_saleitemtax.taxid

							where transactiontype NOT IN (5, 30, 33, 45, 12, 15)
							   and Data_Sale.paid = 1
							   and ISNULL(data_ticket.voidtype, 0) not in (104, 125)
							   and transactionstatus in (5)
							   and ((transactiontype &lt;&gt; 4) or (transactiontype = 4) and (DATA_SaleItem.producttype = 6))
								and ((@RRTransDateType = 0 and data_transaction.fTransactionDate = @BatchDate)
								 OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
								  and data_transaction.transactionid in (select distinct transactionid
								                                           from data_payment WITH(NOLOCK)
																		   where data_payment.paymentstatus = 1
																		     and data_payment.paymentAmount &lt;&gt; 0
																		)
								and (((transactiontype &lt;&gt; 9) and (data_ticket.ticketid in (select ticketid from data_ticketstatus where data_ticketstatus.ticketid = data_ticket.ticketid and data_ticketstatus.voidtype in (0, 1))))
								    or (transactiontype = 9) 
									or (data_ticket.ticketid is null)
									or (data_transaction.transactionstatus = 30))

							group by 			data_transaction.transactionid, 
												data_transaction.saleid,
												data_transaction.Siteid,
												data_transaction.OperatingAreaId,
												data_transaction.Workstationid,
												data_transaction.UserGroupid,
												data_transaction.UserId,
												Data_Transaction.TransactionDate,
												TransactionType,
												fTransactionDate,
												DATA_SaleItem.totalamount,
												data_saleitem.saleitemid,
												data_saleitem.matrixcellid,
												cnf_tax.taxid,
												data_sale.StatusCode,
												data_ticket.ticketid,
												data_saleitem.Itemticketid, 
												data_saleitem.Ticketid,
												DATA_Sale.saleid,
												DATA_SaleItem.producttype,
												DATA_SaleItem.OrigSaleItemID,
												dt.ticketid,
												taxamount,
												data_saleitemtax.saleitemtaxid

								having case when (transactiontype in (5) and sum(DATA_SaleItem.Quantity) &gt; 0)  then 0
										     when (transactiontype not in (5) and data_sale.StatusCode &lt;&gt; 1 and sum(DATA_SaleItem.Quantity) &lt; 0)  then 0									
										     else sum(taxamount * DATA_SaleItem.Quantity)
										end  &lt;&gt; 0

								UNION

								select distinct @TaxCOAAccountId as coaid,
										@TaxRRRId as rrid,
										@TaxRRCalcTypeWhere as rrWhere,
										@TaxRRCalcTypeMethod as rrmethod,
										@TaxCOAAccountConfigId as configid,
										@TaxCOAAccountTypeId as typeid,
										data_transaction.transactionid, 
										data_transaction.saleid,
										data_transaction.Siteid,
										data_saleitem.saleitemid,
										data_saleitem.matrixcellid,
										case when (select count(*) from data_ticket where data_ticket.saleitemid = data_saleitem.OrigSaleItemId) &lt;&gt; (sum(data_saleitem.quantity)*-1)  then null
										     else 
										COALESCE(COALESCE(data_ticket.ticketid, data_saleitem.Itemticketid, data_saleitem.Ticketid),
										(select max(DT.ticketid) as ticketid
												from data_ticket DT
												where DT.saleitemid = DATA_SaleItem.OrigSaleItemID),
										 ( case when ISNULL(DATA_SaleItem.producttype, 0) &lt;&gt; 6 then
										  (select top 1 ticketid
													from data_transaction2ticket
													where transactionid = DATA_Transaction.transactionid)
											else null
											end ) ) end as ticketid,
										data_transaction.OperatingAreaId,
										data_transaction.Workstationid,
										data_transaction.UserGroupid,
										data_transaction.UserId,
										@BatchDate as BatchDate,
										0 Quantity,
										0 Grossamount,
										0 NetAmount,
										0 Price,
										100 Perc,
										0 RMVValues,
										ISNULL(ABS(case when (transactiontype in (5) and (select sum(totalamount) - sum(revenue)
																					from data_transaction
																					where transactiontype &lt;&gt; 5
																						and saleid = DATA_Sale.saleid) &lt;&gt; 0)  then 0
										         when (transactiontype in (5)) and data_ticket.ticketid is not null then sum(taxamount)
												 when (transactiontype in (5))  then sum(taxamount) * sum(DATA_SaleItem.Quantity)
												 when (transactiontype in (30)) and sum(data_saleitem.Quantity) &lt; - 1 and 
												       (select count(*) from data_ticket where data_ticket.saleitemid = data_saleitem.OrigSaleItemId) &lt;&gt; sum(data_saleitem.quantity) then sum(taxamount) * sum(data_saleitem.quantity)

										         when (transactiontype not in (5) and data_sale.StatusCode &lt;&gt; 1 and sum(DATA_SaleItem.Quantity) &lt; 0)  then 0
										         else sum(taxamount) * (case when data_ticket.ticketid is null then sum(DATA_SaleItem.Quantity) else 1 end)
										end), 0)  revenueamount,
										case    when @TaxRRCOAAccountingType = 1 then 2
												when @TaxRRCOAAccountingType = 2 then 1
												else @TaxRRCOAAccountingType
									    end Accountingtype,
										@TaxRRCalcTypeTrigger as rrtrigger,
										@TaxPercentage as taxperc,
										@TaxDays as days,
										null Attributes,
										data_saleitemtax.saleitemtaxid
		   
						from Data_Sale WITH(NOLOCK)
								INNER JOIN DATA_Transaction WITH(NOLOCK)					on data_transaction.transactionid = Data_Sale.Voidtransactionid 
								left join DATA_TransactionItem WITH(NOLOCK)					on (DATA_TransactionItem.TransactionId = data_transaction.TransactionId)
								left join DATA_SaleItem WITH(NOLOCK)						on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId								
								left join data_ticket WITH(NOLOCK)                          on data_ticket.saleitemid = data_saleitem.OrigSaleItemId
								                                                               and data_ticket.Printdatetime is not null
								left join DATA_SaleItemTax WITH(NOLOCK)						on data_saleitemtax.saleitemid = data_saleitem.saleitemid
								left JOIN CNF_Tax WITH(NOLOCK)								on cnf_tax.taxid = data_saleitemtax.taxid
								inner join (select distinct transactionid
								                                           from data_payment WITH(NOLOCK)
																		   where data_payment.paymentstatus = 1
																		   	and ((@RRTransDateType = 0 and convert(date, data_payment.fpaymentDate) = @BatchDate)
																			OR (@RRTransDateType = 1 and convert(date, data_payment.PaymentDate) = @BatchDate))) TranRecord
																			on tranrecord.transactionid = data_transaction.transactionid
								left join (select ticketid, transactionid, voidtype
											 from data_ticketstatus WITH(NOLOCK)
											where voidtype not in (0, 1)) Ticketstatus							ON Ticketstatus.ticketid = data_ticket.ticketid
																												and Ticketstatus.transactionid &lt;&gt; data_transaction.transactionid
							where transactiontype IN (5, 30)
							   and (select count(*) from data_ticket where data_ticket.saleitemid = data_saleitem.OrigSaleItemId) &lt;&gt; (data_saleitem.quantity)
							   and Data_Sale.paid = 1
							   and transactionstatus in (5)
							   and data_sale.paidtransactionid is not null
							   and ((transactiontype &lt;&gt; 4) or (transactiontype = 4) and (DATA_SaleItem.producttype = 6))
							   and ((@RRTransDateType = 0 and data_transaction.fTransactionDate = @BatchDate)
								 OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
							   and (data_ticket.ticketid in (select ticketid from data_ticketstatus where data_ticketstatus.ticketid = data_ticket.ticketid and data_ticketstatus.voidtype in (1, 0))
							         or (data_ticket.ticketid is null))

							group by 			data_transaction.transactionid, 
												data_transaction.saleid,
												data_transaction.Siteid,
												data_transaction.OperatingAreaId,
												data_transaction.Workstationid,
												data_transaction.UserGroupid,
												data_transaction.UserId,
												Data_Transaction.TransactionDate,
												TransactionType,
												fTransactionDate,
												DATA_SaleItem.totalamount,
												data_saleitem.saleitemid,
												data_saleitem.matrixcellid,
												cnf_tax.taxid,
												data_sale.StatusCode,
												data_ticket.ticketid,
												data_saleitem.Itemticketid, 
												data_saleitem.Ticketid,
												DATA_Sale.saleid,
												DATA_SaleItem.producttype,
												DATA_SaleItem.OrigSaleItemID,
												data_saleitemtax.saleitemtaxid
								having case when (transactiontype in (5) and sum(DATA_SaleItem.Quantity) &gt; 0)  then 0
										     when (transactiontype not in (5) and data_sale.StatusCode &lt;&gt; 1 and sum(DATA_SaleItem.Quantity) &lt; 0)  then 0									
										     else sum(taxamount * DATA_SaleItem.Quantity)
										end  &lt;&gt; 0
						
							UNION

							select distinct  @TaxCOAAccountId as coaid,
										@TaxRRRId as rrid,
										@TaxRRCalcTypeWhere as rrWhere,
										@TaxRRCalcTypeMethod as rrmethod,
										@TaxCOAAccountConfigId as configid,
										@TaxCOAAccountTypeId as typeid,
										data_transaction.transactionid, 
										data_transaction.saleid,
										data_transaction.Siteid,
										data_saleitem.saleitemid,
										data_saleitem.matrixcellid,
										case when cnf_matrixcell.DocTemplateId is not null then 																			
										(COALESCE(COALESCE(data_ticket.ticketid, dt.ticketid, data_saleitem.Itemticketid, data_saleitem.Ticketid),



										(select max(DT.ticketid) as ticketid
												from data_ticket DT
												where DT.saleitemid = DATA_SaleItem.OrigSaleItemID),
										  (select top 1 ticketid
													from data_transaction2ticket
													where transactionid = data_transaction.transactionid)))
											else COALESCE(data_ticket.ticketid, dt.ticketid, data_saleitem.Itemticketid, data_saleitem.Ticketid, (select top 1 ticketid
													from data_transaction2ticket
													where transactionid = data_transaction.transactionid))
											end as ticketid,
										data_transaction.OperatingAreaId,
										data_transaction.Workstationid,
										data_transaction.UserGroupid,
										data_transaction.UserId,
										@BatchDate as BatchDate,
										0 Quantity,
										0 Grossamount,
										0 NetAmount,
										0 Price,
										100 Perc,
										0 RMVValues,
										ISNULL(ABS(case when (data_transaction.transactiontype in (5) and sum(DATA_SaleItem.Quantity) &gt; 0)  then 0
										         when (data_transaction.transactiontype in (5) and sum(DATA_SaleItem.Quantity) &lt; 0)  then sum(taxamount) * sum(DATA_SaleItem.Quantity)
										         when (data_transaction.transactiontype not in (5) and data_sale.StatusCode &lt;&gt; 1 and sum(DATA_SaleItem.Quantity) &lt; 0)  then 0									
										         when  data_ticket.ticketid is not null then taxamount	 
												 when (DT.Voidtype = 125) then 0
												 else (case when DT.ticketid is null then sum(taxamount) * sum(DATA_SaleItem.Quantity) else TaxAmount end)
										end) , 0) revenueamount,
										case    when data_transaction.TransactionType in (5, 8, 17, 18, 20, 22, 30, 40, 46, 47) and @TaxRRCOAAccountingType = 1 then 2
												when data_transaction.TransactionType in (5, 8, 17, 18, 20, 22, 30, 40, 46, 47) and @TaxRRCOAAccountingType = 2 then 1
											    when data_transaction.TransactionType in (7) and DATA_SaleItem.totalamount &lt;= 0  then 1
												when data_transaction.TransactionType in (7) and DATA_SaleItem.totalamount &gt; 0  then 2
												else @TaxRRCOAAccountingType
									    end Accountingtype,
										@TaxRRCalcTypeTrigger as rrtrigger,
										@TaxPercentage as taxperc,
										@TaxDays as days,
										null Attributes,
										data_saleitemtax.saleitemtaxid
		   
									from Data_Sale WITH(NOLOCK)
											INNER JOIN data_transaction WITH(NOLOCK)						ON data_transaction.transactionid = data_sale.paidtransactionid
											left JOIN (select distinct DATA_Transaction.transactionid, 
															DATA_Transaction.Saleid,
															data_transaction.siteid,
															data_transaction.OperatingAreaId,
															data_transaction.workstationid,
															data_transaction.userid,
															data_transaction.usergroupid,
															data_transaction.transactiontype,
															data_transaction.fTransactionDate,
															data_transaction.transactiondate,
															data_transactionitem.saleitemid

											
													from DATA_Transaction
														left join DATA_TransactionItem WITH(NOLOCK)					on (DATA_TransactionItem.transactionid in (select dt.transactionid 
																																								from data_transaction dt WITH(NOLOCK)
																																								where dt.saleid in (select dt1.saleid 
																																													from data_transaction dt1
																																													where dt1.transactionid = DATA_Transaction.transactionid)
																																								  and transactiontype not in (5, 30)
																																							  )
																															)
														where data_transaction.transactionid in (select transactionid from data_payment WITH(NOLOCK) where paymentstatus = 1 and paymentamount &lt;&gt; 0))p
																														ON p.saleid = data_sale.saleid
																							
								left join DATA_SaleItem WITH(NOLOCK)						on DATA_SaleItem.saleitemid = p.SaleitemId
								left join data_ticket WITH(NOLOCK)                          on data_ticket.saleitemid = DATA_SaleItem.saleitemid 
								                                                               --and voidtype not in (104, 125)
								
								left join data_saleitem2ticket WITH(NOLOCK)					on data_saleitem2ticket.saleitemid = data_saleitem.saleitemid
								left join data_transaction2ticket WITH(NOLOCK)				on data_transaction2ticket.transactionid = data_transaction.transactionid
																								and data_saleitem2ticket.ticketid = data_transaction2ticket.ticketid
								left join data_ticket DT WITH(NOLOCK)						on DT.Ticketid = data_transaction2ticket.ticketid
																								
								left join DATA_SaleItemTax WITH(NOLOCK)						on data_saleitemtax.saleitemid = data_saleitem.saleitemid
								left JOIN CNF_Tax WITH(NOLOCK)								on cnf_tax.taxid = data_saleitemtax.taxid
								left join cnf_matrixcell WITH(NOLOCK)					on cnf_matrixcell.matrixcellid = data_saleitem.matrixcellid


							where data_transaction.transactiontype NOT IN (9, 30, 33, 45, 12, 15)
							  and ISNULL(data_ticket.voidtype, 0) not in (104, 125)
							   and Data_Sale.paid = 1
							   and transactionstatus in (5)
							   and ((data_transaction.transactiontype &lt;&gt; 4) or (data_transaction.transactiontype = 4) and (DATA_SaleItem.producttype = 6))
								and ((@RRTransDateType = 0 and data_transaction.fTransactionDate = @BatchDate)
								 OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
								  --and data_transaction.transactionid in (select distinct transactionid
								  --                                         from data_payment WITH(NOLOCK)
										--								   where data_payment.paymentstatus = 1
										--								      and data_payment.paymentAmount &lt;&gt; 0
										--								   	and ((@RRTransDateType = 0 and convert(date, data_payment.fpaymentDate) = @BatchDate)
										--									OR (@RRTransDateType = 1 and convert(date, data_payment.PaymentDate) = @BatchDate))
										--								)
								and ((data_saleitem.saleitemid in (select saleitemid from rr_data_revenue)) or (p.transactiontype = 7) or data_saleitem.producttype = 6)
							group by 			data_transaction.transactionid, 
												data_transaction.saleid,
												data_transaction.Siteid,
												data_transaction.OperatingAreaId,
												data_transaction.Workstationid,
												data_transaction.UserGroupid,
												data_transaction.UserId,
												data_transaction.TransactionType,
												DATA_SaleItem.totalamount,
												data_saleitem.saleitemid,
												cnf_tax.taxid,
												data_sale.StatusCode,
												data_saleitem.matrixcellid,
												data_ticket.ticketid,
												data_saleitem.Itemticketid, 
												data_saleitem.Ticketid,
												cnf_matrixcell.DocTemplateId,
												DATA_SaleItem.OrigSaleItemID,
												dt.ticketid,
												taxamount,
												DT.VoidType,
												data_saleitemtax.saleitemtaxid

								having case when (data_transaction.transactiontype in (5) and sum(DATA_SaleItem.Quantity) &gt; 0)  then 0
										     when (data_transaction.transactiontype not in (5) and data_sale.StatusCode &lt;&gt; 1 and sum(DATA_SaleItem.Quantity) &lt; 0)  then 0									
										     else sum(taxamount * DATA_SaleItem.Quantity)
										end  &lt;&gt; 0
								)p
								where RevenueAmount &lt;&gt; 0

				

--Discount
					INSERT INTO [dbo].[RR_DATA_Revenue]
								([COAAccountId]
								,[RevenueRecognitionRuleId]
								,[RRCalcTypeWhere]
								,[RRCalcTypeMethod]
								,[COAAccountConfigId]
								,[COAAccountType]
								,[TransactionId]
								,[SaleId]
								,[Saleitemid]
								,[Ticketid]
								,[Matrixcellid]
								,[SiteId]
								,[OperatingAreaId]
								,[WorkstationId]
								,[UserGroupId]
								,[UserId]
								,[FCalcDate]
								,[Quantity]
								,[GrossAmount]
								,[NetAmount]
								,[Price]
								,[Percentage]
								,[RemaningValues]
								,[RevenueAmount]
								,[AccountingType]
								,[RRCalcTypeTrigger]
								,[RRPercentage]
								,[RRDays]
								,[SaleitemRuleID])

								select  @DiscountCOAAccountId,
										@DiscountRRRId,
										@DiscountRRCalcTypeWhere,
										@DiscountRRCalcTypeMethod,
										@DiscountCOAAccountConfigId,
										@DiscountCOAAccountTypeId,
										data_transaction.transactionid, 
										data_transaction.saleid,
										p.Saleitemid,
										p.Ticketid,
										p.Matrixcellid,
										data_transaction.Siteid,
										data_transaction.OperatingAreaId,
										data_transaction.Workstationid,
										data_transaction.UserGroupid,
										data_transaction.UserId,
										@BatchDate,
										0,
										case when PromotionType = 7 then ABS(p.GLAmount) else 0 end,
										case when PromotionType = 7 then ABS(p.GLAmount) else 0 end,
										0,
										100,
										0,
										ISNULL(ABS(p.GLAmount), 0) RevenueAmount,
										case    when data_transaction.TransactionType in (5, 8, 17, 18, 20, 22, 30, 40, 46, 47) 
										            and promotiontype in (3, 5, 7, 200) then 1
										        when data_transaction.TransactionType in (5, 8, 17, 18, 20, 22, 30, 40, 46, 47) and (discountamount) &lt; 0 then 1
												when data_transaction.TransactionType in (4, 5, 8, 17, 18, 20, 22, 30, 40, 46, 47) and (discountamount) &gt; 0 then 2
											    when data_transaction.TransactionType in (7) and promotiontype in (101) and (GLAmount) &lt; 0  then 1
												when data_transaction.TransactionType in (7) and promotiontype in (101) and (GLAmount) &gt;= 0  then 2
												when PromotionType IN (3, 5, 7, 200) then  2
												when (discountamount) &gt; 0 then 2
												when (glamount) &gt; 0 then 1
												else @DiscountRRCOAAccountingType
									    end Accountingtype,

										@DiscountRRCalcTypeTrigger,
										@DiscountPercentage,
										@DiscountDays,
										SaleitemRuleID
							FROM
							(
								SELECT distinct DATA_SaleItem.Saleitemid,
												case when CNF_Promotion.PromotionType = 7 then DATA_SaleItem.matrixcellid else null end as matrixcellid,
												DATA_Sale.saleid AS SAleid,
      											DATA_Transaction.TransactionType,
      											( SELECT top 1 transactionid
													FROM data_transaction		WITH (NOLOCK)
												   WHERE saleid = DATA_Sale.saleid
													AND transactiontype in (14, 16, 7)
													AND paid = 1
												) AS tester,
												COALESCE(data_ticket.ticketid, dt.ticketid, data_saleitem.Itemticketid, data_saleitem.Ticketid) as ticketid,
												CASE WHEN DATA_Transaction.TransactionId IN (
																							  SELECT TR.TransactionID
																								FROM DATA_Transaction TR			WITH (NOLOCK)
																									LEFT JOIN DATA_Payment DP		WITH (NOLOCK) ON TR.TransactionId = DP.TransactionId
																							  WHERE TR.SaleId = DATA_Sale.SaleId
																								AND TR.Paid = 1
																								AND ((DP.PaymentStatus NOT IN (0, 2, 3)) or (dp.paymentid is null))
																							)
      
															THEN DATA_Transaction.Transactionid
													 ELSE (
															  SELECT MIN(TR.TransactionID)
																FROM DATA_Transaction TR				WITH (NOLOCK)
																	LEFT JOIN DATA_Payment DP			WITH (NOLOCK) ON TR.TransactionId = DP.TransactionId
															   WHERE TR.SaleId = DATA_Sale.saleid
																 AND TR.TransactionType = 16
																 AND TR.Paid = 1
																 AND DP.PaymentStatus NOT IN (0, 2, 3)
														  )
												END Transactionid, 
												CASE WHEN CNF_Promotion.PromotionType IN (1, 3, 5, 7, 200) AND CNF_PromotionItemRule.NewProduct = 1 and DATA_SaleItemRule.DiscountAmount &lt;&gt; 0 and CNF_MatrixCell.Price &lt;&gt; 0 and max(data_saleitemrule.perc) &lt;&gt; 0 then ((DATA_SaleItem.UnitPrice - data_saleitem.UnitTaxes ) * ISNULL(DATA_SaleItem.Quantity, 1))  
												      WHEN CNF_Promotion.PromotionType IN (1, 3, 5, 7, 200) AND CNF_PromotionItemRule.NewProduct = 1 and DATA_SaleItemRule.DiscountAmount &lt;&gt; 0 and CNF_MatrixCell.Price &lt;&gt; 0 THEN  ((CNF_MatrixCell.Price) * ISNULL(DATA_SaleItem.Quantity, 1))
												      WHEN CNF_Promotion.PromotionType IN (1, 3, 5, 7, 200) AND CNF_PromotionItemRule.NewProduct = 1 and DATA_SaleItemRule.DiscountAmount &lt;&gt; 0 and CNF_MatrixCell.Price = 0 THEN ((DATA_SaleItem.UnitPrice - data_saleitem.UnitTaxes ) * ISNULL(DATA_SaleItem.Quantity, 1))
													  ELSE  CASE WHEN sum(1*data_saleItemRule.DiscountAmount/DATA_SaleItemRule.ApplyToQty) &lt; 0 AND transactiontype IN (20, 22, 30, 7, 5, 40, 46, 47) AND
																																								(SELECT Count(*) 
																																								   FROM data_transaction WITH (NOLOCK)
																																								  WHERE saleid = data_sale.saleid
																																								 ) = 1 					  					  					  										  
																	  THEN Sum(1 * DATA_SaleItemRule.DiscountAmount/DATA_SaleItemRule.ApplyToQty)
															     WHEN 1*(data_saleItemRule.DiscountAmount/DATA_SaleItemRule.ApplyToQty) &lt; 0 and COALESCE(data_ticket.ticketid, dt.ticketid, data_saleitem.Itemticketid, data_saleitem.Ticketid) is null then -1 * (DATA_SaleItemRule.DiscountAmount)
																 WHEN 1*(data_saleItemRule.DiscountAmount/DATA_SaleItemRule.ApplyToQty) &lt; 0 THEN -1 * (DATA_SaleItemRule.DiscountAmount/DATA_SaleItemRule.ApplyToQty)
																 WHEN sum(1*data_saleItemRule.DiscountAmount/DATA_SaleItemRule.ApplyToQty) &gt; 0 AND transactiontype IN (20, 22, 30, 5, 40, 46, 47) and COALESCE(data_ticket.ticketid, dt.ticketid, data_saleitem.Itemticketid, data_saleitem.Ticketid) is not null THEN Sum(-1 * DATA_SaleItemRule.DiscountAmount/DATA_SaleItemRule.ApplyToQty)
																 WHEN sum(1*data_saleItemRule.DiscountAmount/DATA_SaleItemRule.ApplyToQty) &gt; 0 AND transactiontype IN (20, 22, 30, 7, 5, 40, 46, 47) and COALESCE(data_ticket.ticketid, dt.ticketid, data_saleitem.Itemticketid, data_saleitem.Ticketid) is null THEN Sum(-1 * DATA_SaleItemRule.DiscountAmount)		            	                  
																 ELSE sum(1*Data_SaleItemRule.DiscountAmount/DATA_SaleItemRule.ApplyToQty)
															END
												END AS GLAmount,
												CNF_Promotion.PromotionType,
												CNF_PromotionItemRule.NewProduct,
												DATA_SaleItemRule.discountamount/DATA_SaleItemRule.ApplyToQty as discountamount,
										        DATA_SaleItemRule.saleitemruleid


								FROM dbo.DATA_SaleItemRule				WITH (NOLOCK)
									LEFT JOIN dbo.CNF_PromotionItemRule WITH (NOLOCK) ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
									LEFT JOIN dbo.CNF_PromotionItem		WITH (NOLOCK) ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
									LEFT JOIN dbo.CNF_Promotion			WITH (NOLOCK) ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId
									LEFT JOIN dbo.CNF_DmgCategory		WITH (NOLOCK) ON CNF_DmgCategory.DmgCategoryId = CNF_Promotion.DmgCategoryId
									LEFT JOIN dbo.DATA_SaleItem			WITH (NOLOCK) ON DATA_SaleItem.SaleItemId = DATA_SaleItemRule.SaleItemId
									LEFT JOIN dbo.DATA_Sale				WITH (NOLOCK) ON DATA_Sale.SaleID = DATA_SaleItem.SaleID
									LEFT JOIN DATA_TransactionItem		WITH (NOLOCK) ON DATA_TransactionItem.SaleItemId = DATA_SaleItem.SaleItemId 
									LEFT JOIN DATA_Transaction			WITH (NOLOCK) ON  DATA_Transaction.TransactionId = DATA_TransactionItem.TransactionId
									LEFT JOIN CNF_MatrixCell			WITH (NOLOCK) ON CNF_MatrixCell.MatrixCellId =  DATA_SaleItem.MatrixCellId
									left join data_ticket WITH(NOLOCK)                          on data_ticket.saleitemid = data_saleitem.saleitemid
																									and voidtype not in (104, 125)
									left join data_saleitem2ticket WITH(NOLOCK)					on data_saleitem2ticket.saleitemid = data_saleitem.saleitemid
									left join data_transaction2ticket WITH(NOLOCK)				on data_transaction2ticket.transactionid = DATA_Transaction.transactionid
																									and data_saleitem2ticket.ticketid = data_transaction2ticket.ticketid
									left join data_ticket DT WITH(NOLOCK)						on DT.Ticketid = data_transaction2ticket.ticketid
 
								WHERE DATA_Sale.Paid = 1								  
								  and DATA_SaleItemRule.ApplyToQty &lt;&gt; 0
								  and  ((@RRTransDateType = 0 and DATA_Transaction.fTransactionDate = @BatchDate)
										OR (@RRTransDateType = 1 and convert(date, DATA_Transaction.TransactionDate) = @BatchDate)
										or (data_transaction.approved = 1 and data_transaction.paid = 0))
								  and DATA_Transaction.saleid in (
																	SELECT ff.saleid 
																	  FROM DATA_Transaction ff WITH (NOLOCK) 
																		LEFT JOIN Data_Payment WITH (NOLOCK) on (ff.Transactionid = Data_Payment.Transactionid) 
																	 WHERE  ((@RRTransDateType = 0 and ff.fTransactionDate = @BatchDate)
																		OR (@RRTransDateType = 1 and convert(date, ff.TransactionDate) = @BatchDate))
																	   AND ((DATA_PAyment.PaymentStatus NOT in (0,2,3)) or (data_payment.paymentid is null)) 
																	   AND (TransactionType not in (12, 15)) 
																	   AND ff.PAid = 1
																 )  
								 and transactiontype NOT IN (4, 12, 15, 33, 45, 46, 47, 115)
								 AND (((DATA_SaleItem.quantity &gt; 0) AND (transactiontype NOT IN (18, 20, 22, 30, 5, 40, 46, 47, 40)) and data_sale.StatusCode = 1) OR ((DATA_SaleItem.quantity &lt; 0) AND (transactiontype IN (4, 18, 20, 22, 30, 7, 5, 40, 46, 47, 40))))

         
								group BY DATA_SaleItem.Saleitemid,
										 DATA_Sale.saleid,
										 Data_transaction.Paid,
										 DATA_SaleItem.Quantity,
										 Data_Transaction.Transactionid,
										 Data_Transaction.fTransactionDate,
										 Data_Saleitem.Matrixcellid,
										 CNF_DmgCategory.DmgCategoryCode,
										 CNF_Promotion.PromotionType,
										 CNF_PromotionItemRule.NewProduct,
										 CNF_MatrixCell.Price,
										 transactiontype,
										 CNF_DmgCategory.Description,
										 DATA_SaleItemRule.discountamount,
										 DATA_SaleItemRule.saleitemruleid,
										 data_ticket.ticketid, 
										 dt.ticketid, 
										 data_saleitem.Itemticketid, 
										 data_saleitem.Ticketid,
										 DATA_SaleItemRule.ApplyToQty,
										 DATA_SaleItem.UnitPrice,
										 data_saleitem.UnitTaxes 
							)p
								LEFT JOIN data_transaction WITH (NOLOCK) on data_transaction.transactionid = p.transactionid

							WHERE ((p.TransactionType not in (5, 115)) or (Tester is not null))
							  AND data_transaction.transactionid is not null
							  and p.GLAmount &lt;&gt; 0
					


		  Select 'End of Batch', getdate()	

		exec otn_sp_RR_RevenueData_OnDepositTrigger @BatchDate, @RRTransDateType				
	

		exec otn_sp_RR_RevenueData_OnSaleTrigger @BatchDate, @RRTransDateType				


		exec otn_sp_RR_RevenueData_OnMoneyCardLoad @BatchDate, @RRTransDateType						


		exec otn_sp_RR_RevenueData_OnMoneyCardCashOut @BatchDate, @RRTransDateType				


		exec otn_sp_RR_RevenueData_OnCreditWriteoff @BatchDate, @RRTransDateType					


		exec otn_sp_RR_RevenueData_OnMoneyRefundTrigger @BatchDate, @RRTransDateType					
		

		exec otn_sp_RR_RevenueData_OnAdvancedPaymentTrigger @BatchDate, @RRTransDateType					
		 		 

		exec otn_sp_RR_RevenueData_PaymentMethodTaxDiscounts @BatchDate, '5, 9, 10, 14, 18, 20, 22, 16, 30, 31, 41, 42, 43, 48, 49, 52, 101, 102, 103, 104, 105,33, 45, 46, 47, 51,',  @RRTransDateType    --1:35.53
		 

		exec otn_sp_RR_RevenueData_PaymentMethodTaxDiscounts2 @BatchDate, '6, 8, 12, 13, 15, 34, 116,', @RRTransDateType	
		

		exec otn_sp_RR_RevenueData_OnFlexContractCancel @BatchDate, @RRTransDateType


		exec otn_sp_RR_RevenueData_OnCreditSettlementTrigger @BatchDate, @RRTransDateType
		 

		exec otn_sp_RR_RevenueData_SettleUpSuspendAccount @BatchDate, @RRTransDateType
		 

		exec otn_sp_RR_RevenueData_OnTicketUsageTrigger @BatchDate, @RRTransDateType, 1
		  

		exec otn_sp_RR_RevenueData_OnTimePeriodTrigger @BatchDate, @RRTransDateType
		  

		exec otn_sp_RR_RevenueData_OnChangeValiditydateTrigger @BatchDate, @RRTransDateType
		  

		exec otn_sp_RR_RevenueData_OnUpgradeTrigger @BatchDate, @RRTransDateType
		  

		exec otn_sp_RR_RevenueData_OnTicketUsageTrigger @BatchDate, @RRTransDateType, 7
		 

		exec otn_sp_RR_RevenueData_PaymentMethodTaxDiscounts @BatchDate, '7, ',  @RRTransDateType 
		  
			
		exec otn_sp_RR_RevenueData_OnUpgradeTrigger_refund @BatchDate, @RRTransDateType



		exec otn_sp_RR_RevenueData_SettleUpgradeSuspendAccount @BatchDate, @RRTransDateType

		
		exec otn_sp_RR_RevenueData_OnEventTrigger @BatchDate, @RRTransDateType	


		exec otn_sp_RR_RevenueData_OnTicketExpiredTrigger @BatchDate, @RRTransDateType


		exec otn_sp_RR_RevenueData_CalculateCOATotals @BatchDate, @RRTransDateType


		FETCH NEXT FROM date_Cursor INTO @BatchDate
	end

		delete from rr_data_revenue where fcalcdate &gt;= cast(Getdate() as date)
		delete from rr_data_revenue_totals where fcalcdate  &gt;= cast(Getdate() as date)
		
	CLOSE date_Cursor;
	DEALLOCATE date_Cursor;

End


</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_RR_RevenueData_PaymentMethodTaxDiscounts]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_RR_RevenueData_PaymentMethodTaxDiscounts
  </SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>create Procedure [dbo].[otn_sp_RR_RevenueData_PaymentMethodTaxDiscounts]
	@BatchDate Date,
	@Transactions varchar(500),
	@RRTransDateType integer
AS 
BEGIN
	 
	Create Table #TransactionIDs(
	TransactionId Int NOT NULL)

	DECLARE @DelimPosition INT
	DECLARE @AccountConfigID INT
	Declare @SuspendRRRId Integer
	Declare @SuspendCOAAccountId Integer
	Declare @SuspendRRCalcTypeTrigger Integer
	Declare @SuspendRRCalcTypeWhere Integer
	Declare @SuspendRRCalcTypeMethod Integer
	Declare @SuspendCOAAccountConfigId Integer
	Declare @SuspendCOAAccountTypeId Integer
	Declare @SuspendPercentage float
	Declare @SuspendDays Integer
	Declare @SuspendPrice float
	Declare @SuspendCOAAccount_Percentage Float
	Declare @SuspendRemainingValues Integer
	Declare @SuspendRRCOAAccountingType Integer
	Declare @SuspendAccountingType Integer


    SET @DelimPosition = CHARINDEX(',', @Transactions)

    WHILE @DelimPosition &gt; 0
    BEGIN
        INSERT INTO #TransactionIDs(TransactionId)
            VALUES(CAST(RTRIM(LEFT(@Transactions, @DelimPosition - 1)) AS INT))

        SET @Transactions = right(@Transactions, len(@Transactions) - @DelimPosition)

        SET @DelimPosition = CHARINDEX(',', @Transactions)
    END

	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer

	Declare @OnCreditWriteoff Integer = 9
	Declare @StartTime DateTime

	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account WITH(NOLOCK)
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account WITH(NOLOCK)
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account WITH(NOLOCK)
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account WITH(NOLOCK)
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1

select TOP 1	@SuspendRRRId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
					@SuspendRRCalcTypeTrigger = RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
					@SuspendRRCalcTypeWhere = RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
					@SuspendRRCalcTypeMethod = RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
					@SuspendCOAAccountConfigId = COA_CNF_AccountConfig.COAAccountConfigId,
					@SuspendCOAAccountTypeId = COA_CNF_AccountType.COAAccountTypeId,
					@SuspendCOAAccountId = coa_cnf_account.COAAccountId,
					@SuspendPercentage = RR_CNF_RevenueRecognitionRule.Percentage,
					@SuspendDays = RR_CNF_RevenueRecognitionRule.Days,
					@SuspendPrice = COA_CNF_AccountConfig.Price,
					@SuspendCOAAccount_Percentage = COA_CNF_AccountConfig.Percentage,
					@SuspendRemainingValues = COA_CNF_AccountConfig.RemainingValues,
					@SuspendRRCOAAccountingType = COA_CNF_AccountConfig.AccountingType
	from coa_cnf_account WITH(NOLOCK)
		INNER JOIN COA_CNF_AccountType WITH(NOLOCK)				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
		INNER JOIN COA_CNF_AccountConfig WITH(NOLOCK)			on COA_CNF_AccountConfig.COAAccountId = coa_cnf_account.COAAccountId
		INNER JOIN RR_CNF_RevenueRecognitionRule WITH(NOLOCK)	on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId
	where coa_cnf_account.COAAccountID = @SuspendID
	 order by RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId


select  @AccountConfigID = coaaccountconfigid
from (
select top 1 coa_cnf_accountconfig.coaaccountconfigid
 from COA_CNF_Account WITH(NOLOCK)
	INNER JOIN coa_cnf_accountconfig WITH(NOLOCK)			on coa_cnf_accountconfig.coaaccountid = COA_CNF_Account.coaaccountid
	 where Code = 'SUSPENSE'
	  and SystemAccount = 1

	  )p
	

		--	--	--Normal Sale Split out the Payments to Smaller Subset.
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])		
					select COAAccountId, 
						   RevenueRecognitionRuleId,		   
						   RRCalcTypeWhere,
						   RRCalcTypeMethod,	   
						   COAAccountConfigId,
						   COAAccountTypeId,
						   Transactionid,
						   Saleid,
						   SiteID,
						   OperatingAreaID,
						   Workstationid,
						   UserGroupID,
						   userID,
						   batchdate,
						   Quantity,
						   GrossAmount,
						   NetAmount,
						   Price,
						   Percentage,
						   RemainingValue,
						   abs(sum(RevenueAmount)),
						   case when transactiontype = 14 and sum(RevenueAmount) &lt; 0 then 2 else accountingtype end as accountingtype,
						   rrcalctypetrigger,
						   rrpercentage,
						   rrdays
						   from(				   		    
						select distinct COA.COAAccountId, 
						   p.RevenueRecognitionRuleId,		   
						   p.RRCalcTypeWhere,
						   p.RRCalcTypeMethod,	   
						   p.COAAccountConfigId,
						   COA.COAAccountTypeId,
						   RR_DATA_REVENUE.Transactionid as Transactionid,
						   RR_DATA_REVENUE.saleid as Saleid,
						   RR_DATA_REVENUE.Siteid as SiteID,
						   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
						   RR_DATA_REVENUE.Workstationid as Workstationid,
						   RR_DATA_REVENUE.UserGroupid as UserGroupID,
						   RR_DATA_REVENUE.UserId as userID,
						   @BatchDate as batchdate,
						  data_payment.paymentid,
						   0 as Quantity,
						   0 as GrossAmount,
						   0 as NetAmount,
						   0 as Price,
						   100 as Percentage,
						   0 as RemainingValue, 	
						   (data_payment.PaymentAmount) -
						   (case when data_payment.paymentid = (select top 1 paymentid
																from data_payment WITH(NOLOCK)
																	where data_payment.paymentstatus = 1 
																	and transactionid = RR_DATA_REVENUE.Transactionid
																	and data_payment.paymentamount &gt; (select sum(Change) *-1
																								from data_transaction WITH(NOLOCK)
																								where data_transaction.transactionid = RR_DATA_REVENUE.Transactionid))
								then (select sum(Change) *-1
																								from data_transaction WITH(NOLOCK)
																								where data_transaction.transactionid = RR_DATA_REVENUE.Transactionid)
								else 0
							end )
							as RevenueAmount,
							case when DATA_Transaction.transactiontype not in (46, 47) then p.Accountingtype
							     else 2
							end Accountingtype,		
						    p.RRCalcTypeTrigger,
						    p.RRPercentage,
						    p.RRDays,
							DATA_Transaction.transactiontype

						from RR_DATA_REVENUE WITH(NOLOCK)
						INNER JOIN DATA_Transaction	 WITH(NOLOCK)					on data_transaction.transactionid = rr_data_revenue.transactionid
						INNER JOIN data_payment	 WITH(NOLOCK)						on data_payment.transactionid = rr_data_revenue.transactionid 
									                                                                 and data_payment.PaymentStatus = 1
									                                                               and ((1 = (select count(*) from data_payment where data_Payment.transactionid = data_transaction.transactionid and data_payment.PaymentStatus = 1))
																								       and  ((data_payment.PaymentAmount + data_transaction.change) = case when rr_data_revenue.Accountingtype = 1 then (RR_DATA_REVENUE.RevenueAmount)
																								                                            else (RR_DATA_REVENUE.RevenueAmount * -1)
																																	   end))
																									or ((data_payment.paymentid = (select top 1 DP.paymentid from data_payment DP where dp.transactionid = data_transaction.transactionid and DP.PaymentStatus = 1 order by dp.PaymentAmount desc))
																									   and (data_payment.Paymentamount + data_transaction.change = case when rr_data_revenue.Accountingtype = 1 then (RR_DATA_REVENUE.RevenueAmount)
																								                                            else (RR_DATA_REVENUE.RevenueAmount * -1)
																																	   end))
																									or ((data_payment.transactionid = rr_data_revenue.transactionid) and  ((data_payment.paymentid &lt;&gt; (select top 1 DP.paymentid from data_payment DP where dp.transactionid = data_transaction.transactionid and DP.PaymentStatus = 1 order by dp.PaymentAmount desc))
																									   and (data_payment.Paymentamount = case when rr_data_revenue.Accountingtype = 1 then (RR_DATA_REVENUE.RevenueAmount)
																								                                            else (RR_DATA_REVENUE.RevenueAmount * -1)
																																	   end)))
						left  JOIN DATA_PaymentCard	WITH(NOLOCK)					on data_paymentcard.paymentid = data_payment.PaymentId
						left JOIN CNF_PaymentCard WITH(NOLOCK)						on cnf_paymentcard.paymentcardid = data_paymentcard.paymentcardid
						INNER JOIN CNF_PaymentMethod WITH(NOLOCK)					on CNF_PaymentMethod.PaymentMethodId = data_payment.PaymentMethodId
						INNER JOIN COA_CNF_Account COA WITH(NOLOCK)					on COA.COAAccountid = case when CNF_PaymentCard.paymentcardid is not null then
																														case when cnf_paymentmethod.driverid = 48 then CNF_PaymentMethod.COAAccountid
																														     when cnf_paymentcard.coaaccountid is not null then cnf_paymentcard.coaaccountid
																														     else CNF_PaymentMethod.coaaccountid
																														 end
						                                                                                       else CNF_PaymentMethod.COAAccountid
																											end
						INNER JOIN (select transactionid, RevenueRecognitionRuleId, RRCalcTypeWhere, 
											RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount,  Accountingtype
											from RR_DATA_Revenue WITH(NOLOCK)
											INNER JOIN COA_CNF_Account WITH(NOLOCK)		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
											where COA_CNF_Account.coaAccountID = @ACCPaymentMethod
											and RR_DATA_REVENUE.fcalcdate = @BatchDate
										)p    on p.transactionid = 	data_payment.transactionid and p.accountingtype = rr_data_revenue.accountingtype
											and p.revenueamount = rr_data_revenue.revenueamount
					where data_payment.paymentstatus = 1
					and DATA_Transaction.TransactionType in (select transactionid
																from #TransactionIDs)
					and RR_DATA_REVENUE.fcalcdate = @BatchDate
					AND data_payment.Transactionid in (select transactionid
												        from rr_Data_Revenue WITH(NOLOCK)
												       where coaaccountid in (@ACCPaymentMethod)
													     and fcalcdate = @BatchDate
												)
					 AND RR_DATA_REVENUE.coaaccountid in (@ACCPaymentMethod)
				)P

				group by COAAccountId, 
						   RevenueRecognitionRuleId,	   
						   RRCalcTypeWhere,
						   RRCalcTypeMethod,	   
						   COAAccountConfigId,
						   COAAccountTypeId,
						   Transactionid,
						   Saleid,
						   SiteID,
						   OperatingAreaID,
						   Workstationid,
						   UserGroupID,
						   userID,
						   batchdate,
						   Quantity,
						   GrossAmount,
						   NetAmount,
						   Price,
						   Percentage,
						   RemainingValue,						 
						   accountingtype,
						   rrcalctypetrigger,
						   rrpercentage,
						   rrdays,
						   transactiontype

		----Normal Sale Split out the Payments to Payment Fees
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])				    
				select distinct COA.COAAccountId, 
						   p.RevenueRecognitionRuleId,	   
						   p.RRCalcTypeWhere,
						   p.RRCalcTypeMethod,	   
						   p.COAAccountConfigId,
						   COA.COAAccountTypeId,
						   RR_DATA_REVENUE.Transactionid as Transactionid,
						   RR_DATA_REVENUE.saleid as Saleid,
						   RR_DATA_REVENUE.Siteid as SiteID,
						   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
						   RR_DATA_REVENUE.Workstationid as Workstationid,
						   RR_DATA_REVENUE.UserGroupid as UserGroupID,
						   RR_DATA_REVENUE.UserId as userID,
						   @BatchDate,
						   0,
						   0,
						   0,
						   0,
						   100,
						   0,  	
						   ABS(data_payment.paymentfee) as RevenueAmount,
						   case when data_payment.paymentfee &gt;= 0 then 2
						        else 1
							end accountingtype,		
						   p.RRCalcTypeTrigger,
						   p.RRPercentage,
						   p.RRDays

						from RR_DATA_REVENUE WITH(NOLOCK)
						INNER JOIN DATA_Transaction	 WITH(NOLOCK)					on data_transaction.transactionid = rr_data_revenue.transactionid
						INNER JOIN data_payment	WITH(NOLOCK)						on data_payment.transactionid = rr_data_revenue.transactionid
						left  JOIN DATA_PaymentCard	WITH(NOLOCK)					on data_paymentcard.paymentid = data_payment.PaymentId
						left JOIN CNF_PaymentCard WITH(NOLOCK)						on cnf_paymentcard.paymentcardid = data_paymentcard.paymentcardid
						INNER JOIN CNF_PaymentMethod WITH(NOLOCK)					on CNF_PaymentMethod.PaymentMethodId = data_payment.PaymentMethodId
						INNER JOIN COA_CNF_Account COA WITH(NOLOCK)					on COA.COAAccountid = CNF_PaymentMethod.FeeCOAAccountId

						INNER JOIN (select transactionid, RevenueRecognitionRuleId, RRCalcTypeWhere, 
											RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount,  Accountingtype
											from RR_DATA_Revenue WITH(NOLOCK)
											INNER JOIN COA_CNF_Account WITH(NOLOCK)		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
											where COA_CNF_Account.coaAccountID = @ACCPaymentMethod
										)p    on p.transactionid = 	data_payment.transactionid

					where data_payment.paymentstatus = 1
					and DATA_Transaction.TransactionType in (select transactionid
 															   from #TransactionIDs)
					and data_payment.paymentfee &lt;&gt; 0
					and RR_DATA_REVENUE.fcalcdate = @BatchDate

					AND data_payment.Transactionid not in (select transactionid
												from rr_Data_Revenue WITH(NOLOCK)
												where coaaccountid in (select FeeCOAAccountId
																			from cnf_paymentmethod CP WITH(NOLOCK)
																		)
																			and transactionid is not null
												)
					AND data_payment.Transactionid in (select transactionid
												from rr_Data_Revenue WITH(NOLOCK)
												where coaaccountid in (@ACCPaymentMethod)
												)

		---Installment Billing Fees
		INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])	
				   select *
				   from (
		select distinct COA.COAAccountId, 
						   p.RevenueRecognitionRuleId,		   
						   p.RRCalcTypeWhere,
						   p.RRCalcTypeMethod,	   
						   p.COAAccountConfigId,
						   COA.COAAccountTypeId,
						   RR_DATA_REVENUE.Transactionid as Transactionid,
						   RR_DATA_REVENUE.saleid as Saleid,
						   RR_DATA_REVENUE.Siteid as SiteID,
						   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
						   RR_DATA_REVENUE.Workstationid as Workstationid,
						   RR_DATA_REVENUE.UserGroupid as UserGroupID,
						   RR_DATA_REVENUE.UserId as userID,
						   @BatchDate as BatchDate,
						   0 as Quantity,
						   0 as GrossAmount,
						   0 as NetAmount,
						   0 as Price,
						   100 as Perc,
						   0 as Remaining,  	
						   ISNULL((select sum(feeamount)
								from DATA_PaymentPlan2Transaction	
								INNER JOIN DATA_PaymentPlan			on data_paymentplan.paymentplanid = DATA_PaymentPlan2Transaction.paymentplanid
								where DATA_PaymentPlan2Transaction.Transactionid = data_payment.Transactionid
								and DATA_PaymentPlan2Transaction.flexpaymentstatus &lt;&gt; 5), 0) as RevenueAmount,
						   case when data_payment.paymentfee &gt;= 0 then 2
						        else 1
							end accountingtype,		
						   p.RRCalcTypeTrigger,
						   p.RRPercentage,
						   p.RRDays

						from RR_DATA_REVENUE
						INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
						INNER JOIN data_payment							on data_payment.transactionid = rr_data_revenue.transactionid
						INNER JOIN CNF_PaymentMethod					on CNF_PaymentMethod.PaymentMethodId = data_payment.PaymentMethodId


						INNER JOIN (select transactionid, RevenueRecognitionRuleId, RRCalcTypeWhere, 
											RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount,  Accountingtype
											from RR_DATA_Revenue
											INNER JOIN COA_CNF_Account		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
											where COA_CNF_Account.coaAccountID = @ACCPaymentMethod
										)p    on p.transactionid = 	data_payment.transactionid

						INNER JOIN (select distinct DATA_PaymentFlex.paymentid, data_saleitem.saleid, (DATA_PaymentFlex.downpaymentfeeamount + data_paymentflex.feeAmount) as FeeAmount,  CNF_Promotion.COAAccountId
									from data_saleitem
										INNER JOIn data_Paymentflex2saleitem	on data_Paymentflex2saleitem.saleitemid = data_saleitem.saleitemid
										INNER JOIN DATA_PaymentFlex				on data_paymentflex.paymentid = data_Paymentflex2saleitem.paymentid
										INNER JOIN CNF_FlexContract				on cnf_flexContract.FlexContractId = DATA_PaymentFlex.flexcontractID
										INNER JOIN CNF_FlexContractFee			on CNF_FlexContractFee.FlexContractId = CNF_FlexContract.flexcontractID
										INNER JOIN CNF_Promotion				on CNF_Promotion.promotionID = CNF_FlexContractFee.promotionID

									where CNF_Promotion.COAAccountId is not null
									  )r1				on r1.saleid = DATA_Transaction.saleid
						INNER JOIN COA_CNF_Account COA					on COA.COAAccountid = R1.COAAccountId


					where data_payment.paymentstatus = 1
					and DATA_Transaction.TransactionType in (select transactionid
																from #TransactionIDs)
					and RR_DATA_REVENUE.fcalcdate = @BatchDate
					AND data_payment.Transactionid in (select distinct transactionid
												from rr_Data_Revenue
												where coaaccountid in (@ACCPaymentMethod)
												)
					)p
					where revenueamount &lt;&gt; 0
 
		--	--Normal Transactions Reverse out of PaymentMethods
			INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])				    					
					select COAAccountId, 
						   Max(RevenueRecognitionRuleId),	   
						   RRCalcTypeWhere,
						   RRCalcTypeMethod,	   
						   Max(COAAccountConfigId),
						   COAAccountTypeId,
						   Transactionid,
						   saleid,
						   Siteid,
						   OperatingAreaId,
						   Workstationid,
						   UserGroupid,
						   UserId,
						   batchdate,
						   0,
						   0,
						   0,						
						   0,
						   100,
						   0,
						   ABS(sum(RevenueAmount)) as RevenueAmount,
						   case when accountingtype = 1 then 2
								else 1
							end Accountingtype,		
						   RRCalcTypeTrigger,
						   RRPercentage,
						   RRDays
						   from (
			select distinct rr_data_Revenue.coaaccountid as rrcoaaccountid,
								       p.COAAccountId, 
									   p.RevenueRecognitionRuleId,	   
									   p.RRCalcTypeWhere,
									   p.RRCalcTypeMethod,	   
									   p.COAAccountConfigId,
									   p.COAAccountTypeId,
									   rr_data_Revenue.Transactionid Transactionid,
									   rr_data_Revenue.saleid saleid,
									   rr_data_Revenue.Siteid siteid,
									   rr_data_Revenue.OperatingAreaId OperatingAreaid,
									   rr_data_Revenue.Workstationid workstationid,
									   rr_data_Revenue.UserGroupid usergroupid,
									   rr_data_Revenue.UserId userid,
									   @BatchDate batchdate,
									   rr_data_Revenue.RevenueAmount  as RevenueAmount,
								       p.Accountingtype,
									   transactiontype,		
									   p.RRCalcTypeTrigger,
									   p.RRPercentage,
									   p.RRDays
							FROM rr_data_Revenue   				        WITH (NOLOCK)
								   INNER JOIN (select saleid, transactionid, RevenueRecognitionRuleId, RRCalcTypeWhere, Saleitemid, RR_DATA_Revenue.COAAccountId, 
													   RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount, COA_CNF_Account.COAAccountTypeId,  Accountingtype
													  from RR_DATA_Revenue WITH(NOLOCK)
														INNER JOIN COA_CNF_Account WITH(NOLOCK)		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
													 where COA_CNF_Account.coaAccountID = @ACCPaymentMethod
													)p								ON p.transactionid = 	rr_data_Revenue.transactionid and rr_data_revenue.accountingtype = p.accountingtype
									INNER JOIN DATA_Transaction WITH(NOLOCK)			on data_transaction.transactionid = rr_data_revenue.transactionid
							where RR_DATA_REVENUE.fcalcdate = @BatchDate
							  
							  and DATA_Transaction.TransactionType in (select transactionid
																from #TransactionIDs)
							  and data_transaction.transactiontype not in (46, 47, 51)
							  and rr_data_Revenue.coaaccountid in (select coaaccountid
																	 from cnf_paymentmethod WITH(NOLOCK)
																	 where coaaccountid is not null
																	union all
																   select coaaccountid
																	 from cnf_paymentcard WITH(NOLOCK)
																	 where coaaccountid is not null
																  )
						)r	
							group by	 COAAccountId, 		   
									   RRCalcTypeWhere,
									   RRCalcTypeMethod,	   
									   COAAccountTypeId,
									   Transactionid,
									   saleid,
									   Siteid,
									   OperatingAreaId,
									   Workstationid,
									   UserGroupid,
									   UserId,
									   batchdate,				
									   Accountingtype,		
									   RRCalcTypeTrigger,
									   RRPercentage,
									   RRDays, 
									   TransactionType
							

----Normal Sale Split out the Payments to returned Checks
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])				    
				select distinct 
							COA.COAAccountId, 
						   @SuspendRRRId,	   
						   @SuspendRRCalcTypeWhere,
						   @SuspendRRCalcTypeMethod,	   
						   @SuspendCOAAccountConfigId,
						   COA.COAAccountTypeId,
						   DATA_Transaction.Transactionid as Transactionid,
						   DATA_Transaction.saleid as Saleid,
						   DATA_Transaction.Siteid as SiteID,
						   DATA_Transaction.OperatingAreaId as OperatingAreaID,
						   DATA_Transaction.Workstationid as Workstationid,
						   DATA_Transaction.UserGroupid as UserGroupID,
						   DATA_Transaction.UserId as userID,
						   @BatchDate,
						   0,
						   0,
						   0,
						   0,
						   100,
						   0,  	
						  ABS(data_transaction.tip) as RevenueAmount,
							2 accountingtype,		
							 @SuspendRRCalcTypeTrigger,
							100,
							0

						from  DATA_Transaction	 WITH(NOLOCK)					
						INNER JOIN data_payment	WITH(NOLOCK)						on data_payment.transactionid = DATA_Transaction.transactionid
						left  JOIN DATA_PaymentCard	WITH(NOLOCK)					on data_paymentcard.paymentid = data_payment.PaymentId
						left JOIN CNF_PaymentCard WITH(NOLOCK)						on cnf_paymentcard.paymentcardid = data_paymentcard.paymentcardid
						INNER JOIN CNF_PaymentMethod WITH(NOLOCK)					on CNF_PaymentMethod.PaymentMethodId = data_payment.PaymentMethodId
						INNER JOIN COA_CNF_Account COA WITH(NOLOCK)					on COA.COAAccountid = CNF_PaymentMethod.returnedcheckcoaaccountid
						
						where  data_payment.paymentstatus = 1
						  and DATA_Transaction.TransactionType in (select transactionid
														from #TransactionIDs)
							and DATA_Transaction.tip &lt;&gt; 0
															and ((@RRTransDateType = 0 and convert(date, DATA_Transaction.fTransactionDate) = @BatchDate)
								 OR (@RRTransDateType = 1 and convert(date, DATA_Transaction.TransactionDate) = @BatchDate))

----Breakage for Fixed Vouchers.   The left over money.
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])				    
					select distinct COA.COAAccountId, 
						   p.RevenueRecognitionRuleId,	   
						   p.RRCalcTypeWhere,
						   p.RRCalcTypeMethod,	   
						   p.COAAccountConfigId,
						   COA.COAAccountTypeId,
						   RR_DATA_REVENUE.Transactionid as Transactionid,
						   RR_DATA_REVENUE.saleid as Saleid,
						   RR_DATA_REVENUE.Siteid as SiteID,
						   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
						   RR_DATA_REVENUE.Workstationid as Workstationid,
						   RR_DATA_REVENUE.UserGroupid as UserGroupID,
						   RR_DATA_REVENUE.UserId as userID,
						   @BatchDate,
						   0,
						   0,
						   0,
						   0,
						   100,
						   0,  	
						  ABS(DATA_Transaction.Tip) as RevenueAmount,
							2 accountingtype,		
							p.RRCalcTypeTrigger,
							p.RRPercentage,
							p.RRDays

						from RR_DATA_REVENUE WITH(NOLOCK)

							INNER JOIN data_transaction WITH(NOLOCK)		on data_transaction.transactionid = rr_data_revenue.transactionid
							INNER JOIN DATA_Payment WITH(NOLOCK)			on data_payment.transactionid = data_transaction.transactionid
							INNER JOIN CNF_PaymentMethod WITH(NOLOCK)	on cnf_paymentmethod.paymentmethodid = data_payment.paymentmethodid
							INNER JOIN CNF_Driver WITH(NOLOCK) 			on cnf_driver.driverID = cnf_paymentmethod.driverid
							INNER JOIN COA_CNF_Account COA WITH(NOLOCK)	on COA.COAAccountid = CNF_PaymentMethod.FixedVoucherCOAAccountId


							INNER JOIN (select transactionid, RevenueRecognitionRuleId, RRCalcTypeWhere, 
																	RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount,  Accountingtype
																	from RR_DATA_Revenue WITH(NOLOCK)
																	INNER JOIN COA_CNF_Account WITH(NOLOCK)		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
																	where COA_CNF_Account.coaAccountID = @ACCPaymentMethod
																)p    on p.transactionid = 	data_payment.transactionid


						where data_payment.paymentstatus = 1
						  and TransactionType in (select transactionid
														from #TransactionIDs)
							and DATA_Transaction.tip &lt;&gt; 0
							and RR_DATA_REVENUE.fcalcdate = @BatchDate


--Normal Transaction break out Tax
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[Saleitemid]
				   ,[matrixcellid]
				   ,[matrixsheetid]
				   ,[Ticketid]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays]
				   ,[AttributeIDs]
				   ,[SaleItemTaxID])				    
						  select COAAccountId, 
							min(p.RevenueRecognitionRuleId),   
						   RRCalcTypeWhere,
						   RRCalcTypeMethod,	   
						   COAAccountConfigId,
						   COAAccountTypeId,
						   Transactionid,
						   saleid,
						   Siteid,
						   Saleitemid,
						   matrixcellid,
						   matrixsheetid,
						   TicketID,
						   OperatingAreaId,
						   Workstationid,
						   UserGroupid,
						   UserId,
						   batchdate,
						   0,
						   0,
						   0,						
						   price,
						   percentage,
						   test,
						   ABS(sum(RevenueAmount)) as RevenueAmount,
				           case when TransactionType in (5, 17, 18, 20, 22, 30) and sum(RevenueAmount) &lt;= 0  then 1
						        when TransactionType in (5, 17, 18, 20, 22, 30) and sum(RevenueAmount) &lt;= 0  then 2
								else Accountingtype
							end Accountingtype,		
						   RRCalcTypeTrigger,
						   RRPercentage,
						   RRDays,
						   AttributeIDs,
						   Saleitemtaxid
						   from (
						  select distinct COA.COAAccountId, 
						   min(p.RevenueRecognitionRuleId) RevenueRecognitionRuleId,		   
						   RR_DATA_REVENUE.RRCalcTypeWhere,
						   RR_DATA_REVENUE.RRCalcTypeMethod,	   
						   RR_DATA_REVENUE.COAAccountConfigId,
						   COA.COAAccountTypeId,
						   RR_DATA_REVENUE.Transactionid as Transactionid,
						   RR_DATA_REVENUE.saleid as Saleid,
						   RR_DATA_REVENUE.Siteid as SiteID,
						   RR_data_revenue.Saleitemid,
						   RR_data_revenue.matrixcellid,
						   RR_data_revenue.MatrixSheetId,
						   RR_data_revenue.TicketiD,
						   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
						   RR_DATA_REVENUE.Workstationid as Workstationid,
						   RR_DATA_REVENUE.UserGroupid as UserGroupID,
						   RR_DATA_REVENUE.UserId as userID,
						   @BatchDate as batchdate,
						   0 as Quantity,
						   0 as GrossAmount,
						   0 as NetAmount,
						   0 as price,
						   100 as percentage,
						   0 as test, 	
						   RR_DATA_REVENUE.revenueamount,
						   Transactiontype,
						   p.Accountingtype,					   		
						   RR_DATA_REVENUE.RRCalcTypeTrigger,
						   RR_DATA_REVENUE.RRPercentage,
						   RR_DATA_REVENUE.RRDays,
						   RR_DATA_REVENUE.AttributeIDs,
						   RR_DATA_REVENUE.saleitemtaxid

					from RR_DATA_REVENUE WITH(NOLOCK)
						INNER JOIN DATA_Transaction	 WITH(NOLOCK)					on data_transaction.transactionid = rr_data_revenue.transactionid
						INNER JOIN data_saleitemtax WITH(NOLOCK)                    on data_saleitemtax.saleitemTaxid = rr_data_revenue.SaleitemTaxID
						INNER JOIN DATA_SaleItem WITH(NOLOCK)						on data_saleitem.saleitemid = data_saleitemtax.saleitemid
						INNER JOIN CNF_Tax	WITH(NOLOCK)							on cnf_tax.taxid = data_saleitemtax.taxid
						INNER JOIN coa_cnf_account coa	WITH(NOLOCK)				on coa.coaaccountid = cnf_tax.coaaccountid
						INNER JOIN (select saleid, transactionid, RevenueRecognitionRuleId, RRCalcTypeWhere, Saleitemid, RR_DATA_Revenue.coaaccountid,
												RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount,  Accountingtype
												from RR_DATA_Revenue WITH(NOLOCK)
												INNER JOIN COA_CNF_Account WITH(NOLOCK)		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
												where COA_CNF_Account.coaAccountID = @TaxAccountID
												and RR_DATA_REVENUE.fcalcdate = @BatchDate
											)p    on p.transactionid = 	RR_DATA_REVENUE.transactionid and p.Saleitemid = rr_data_revenue.saleitemid
														and rr_data_revenue.RevenueAmount = p.RevenueAmount
					where RR_DATA_REVENUE.coaaccountid = @TaxAccountID
					and RR_DATA_REVENUE.fcalcdate = @BatchDate
					and TransactionType not in (46)
					and TransactionType in (select transactionid
														from #TransactionIDs)
					AND DATA_Transaction.Transactionid not in (select transactionid
																	from rr_Data_Revenue WITH(NOLOCK)
																	where coaaccountid in (select coaaccountid
																								from cnf_tax WITH(NOLOCK)
																								where coaaccountid is not null
																							)
																	)
					group by COA.COAAccountId,    
						   RR_DATA_REVENUE.RRCalcTypeWhere,
						   RR_DATA_REVENUE.RRCalcTypeMethod,	   
						   RR_DATA_REVENUE.COAAccountConfigId,
						   COA.COAAccountTypeId,
						   COA.Code,
						   RR_DATA_REVENUE.Transactionid,
						   RR_DATA_REVENUE.saleid,
						   RR_DATA_REVENUE.Siteid,
						   RR_DATA_REVENUE.OperatingAreaId,
						   RR_DATA_REVENUE.Workstationid,
						   RR_DATA_REVENUE.UserGroupid,
						   RR_DATA_REVENUE.UserId,
						   DATA_Transaction.ftransactiondate, 
						   DATA_Transaction.transactiondate,
						   taxamount,
						   Transactiontype,
							p.Accountingtype,					   		
						   RR_DATA_REVENUE.RRCalcTypeTrigger,
						   RR_DATA_REVENUE.RRPercentage,
						   RR_DATA_REVENUE.RRDays,
						   RR_DATA_REVENUE.Saleitemid,
						   data_saleitem.Quantity,
						   RR_DATA_REVENUE.TicketID,
						   RR_DATA_REVENUE.matrixcellid,
						  
						   RR_DATA_REVENUE.matrixsheetid,
							RR_DATA_REVENUE.revenueamount,
							RR_DATA_REVENUE.Saleitemtaxid,
							RR_DATA_REVENUE.AttributeIDs


					)p
					where revenueamount &lt;&gt; 0
					group by COAAccountId, 	   
							RRCalcTypeWhere,
							RRCalcTypeMethod,	   
							COAAccountConfigId,
							COAAccountTypeId,
							Transactionid,
							saleid,
							Siteid,
							Saleitemid,
							OperatingAreaId,
							Workstationid,
							UserGroupid,
							UserId,
							Accountingtype,		
							RRCalcTypeTrigger,
							RRPercentage,
							RRDays,
							price,
							percentage,
							test,
							batchdate,
							TransactionType,
							Ticketid,
							matrixcellid,
							matrixsheetid,
							Saleitemtaxid,
							AttributeIDs
							
																															
--------Reverse Tax Out
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[Saleitemid]
				   ,[matrixcellid]
				   ,[matrixsheetid]
				   ,[Ticketid]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])	
				      select  COAAccountId, 
									   RevenueRecognitionRuleId,		   
									   RRCalcTypeWhere,
									   RRCalcTypeMethod,	   
									   COAAccountConfigId,
									   COAAccountTypeId,
									   Transactionid,
									   saleid,
									   siteid,
									   saleitemid,
									   matrixcellid,
									   matrixsheetid,
									   Ticketid,
									   OperatingAreaid,
									   workstationid,
									   usergroupid,
									   userid,
									   batchdate,
									   Quantity,
									   grossamount,
									   netamount,
									   price,
									   percentage,
									   tax,
									   ABS(sum(RevenueAmount))  as RevenueAmount,
									   Accountingtype,	
									   RRCalcTypeTrigger,
									   RRPercentage,
									   RRDays
					  from (		    
				             select distinct 
								       p.COAAccountId, 
									   p.RevenueRecognitionRuleId,	   
									   p.RRCalcTypeWhere,
									   p.RRCalcTypeMethod,	   
									   p.COAAccountConfigId,
									   p.COAAccountTypeId,
									   RR_DATA_REVENUE.Saleitemid,
									   RR_DATA_REVENUE.matrixcellid,
									   RR_DATA_REVENUE.matrixsheetid,
									   RR_DATA_REVENUE.TicketID,
									   rr_data_Revenue.Transactionid Transactionid,
									   rr_data_Revenue.saleid saleid,
									   rr_data_Revenue.Siteid siteid,
									   rr_data_Revenue.OperatingAreaId OperatingAreaid,
									   rr_data_Revenue.Workstationid workstationid,
									   rr_data_Revenue.UserGroupid usergroupid,
									   rr_data_Revenue.UserId userid,
									   @BatchDate batchdate,
									   rr_data_Revenue.Quantity Quantity,
									   rr_data_Revenue.GrossAmount grossamount,
									   rr_data_Revenue.NetAmount netamount,
									   0 price,
									   100 percentage,
									   0 tax,
									   rr_data_Revenue.RevenueAmount  as RevenueAmount,
									   data_transaction.transactiontype,
								       case when rr_data_Revenue.Accountingtype = 2 then 1
									        else 2											
										end as Accountingtype,			
									   p.RRCalcTypeTrigger,
									   p.RRPercentage,
									   p.RRDays,
									   rr_data_revenue.AttributeIDs,
									   rr_data_revenue.SaleItemTaxId
							FROM rr_data_Revenue   				        WITH (NOLOCK)
								   INNER JOIN (select distinct saleid, transactionid, RevenueRecognitionRuleId, RRCalcTypeWhere, RR_DATA_Revenue.COAAccountId, 
																RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, COA_CNF_Account.COAAccountTypeId
																from RR_DATA_Revenue WITH(NOLOCK)
																	INNER JOIN COA_CNF_Account WITH(NOLOCK)		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
																where COA_CNF_Account.coaAccountID = @TaxAccountID	
													)p								ON p.Transactionid = 	rr_data_Revenue.Transactionid
									INNER JOIN data_transaction WITH(NOLOCK)						on data_transaction.transactionid = rr_data_revenue.transactionid

							where RR_DATA_REVENUE.fcalcdate = @BatchDate
							  and TransactionType not in (46)
							  and DATA_Transaction.TransactionType in (select transactionid
																		from #TransactionIDs)
							  and rr_data_Revenue.coaaccountid in (select coaaccountid
						                                             from cnf_tax WITH(NOLOCK)
																    where coaaccountid is not null
															      )
								
							)p
							group by   COAAccountId, 
									   RevenueRecognitionRuleId,	   
									   RRCalcTypeWhere,
									   RRCalcTypeMethod,	   
									   COAAccountConfigId,
									   COAAccountTypeId,
									   Transactionid,
									   saleid,
									   siteid,
									   OperatingAreaid,
									   workstationid,
									   usergroupid,
									   userid,
									   batchdate,
									   Quantity,
									   grossamount,
									   netamount,
									   price,
									   percentage,
									   tax,
								       Accountingtype,		
									   RRCalcTypeTrigger,
									   RRPercentage,
									   RRDays,
									   TransactionType,
									   Saleitemid,
									   TicketID,
									   matrixcellid,
									   matrixsheetid


		------		--Normal Transaction Break out the discounts
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[saleitemid]
				   ,[Ticketid]
				   ,[matrixcellid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays]
				   ,[Saleitemruleid])
				   select COAAccountId, 
						   RevenueRecognitionRuleId,	   
						   RRCalcTypeWhere,
						   RRCalcTypeMethod,	   
						   COAAccountConfigId,
						   COAAccountTypeId,
						   Transactionid,
						   Saleid,
						   Saleitemid,
						   ticketid,
						   matrixcellid,
						   SiteID,
						   OperatingAreaID,
						   Workstationid,
						   UserGroupID,
						   userID,
						   batchdate,
						   quantity,
						   grossamount,
						   netamount,
						   price,
						   percentage,
						   remaningValues, 	
						   RevenueAmount,
						   Accountingtype,		
						   RRCalcTypeTrigger,
						   RRPercentage,
						   RRDays,
						   Saleitemruleid
				   from (				    
						select distinct 
						   COA.COAAccountId, 
						   RR_DATA_REVENUE.RevenueRecognitionRuleId,	   
						   RR_DATA_REVENUE.RRCalcTypeWhere,
						   RR_DATA_REVENUE.RRCalcTypeMethod,	   
						   RR_DATA_REVENUE.COAAccountConfigId,
						   COA.COAAccountTypeId,
						   RR_DATA_REVENUE.Transactionid as Transactionid,
						   RR_DATA_REVENUE.saleid as Saleid,
						   RR_DATA_REVENUE.saleitemid as saleitemid,
						   RR_DATA_REVENUE.ticketid,
						   RR_DATA_REVENUE.Siteid as SiteID,
						   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
						   RR_DATA_REVENUE.Workstationid as Workstationid,
						   RR_DATA_REVENUE.UserGroupid as UserGroupID,
						   RR_DATA_REVENUE.UserId as userID,
						   @BatchDate as batchdate,
						   0 as quantity,
						   case when cnf_promotion.PromotionType = 7 then abs(case when DATA_SaleItemRule.discountamount &lt;&gt; 0 then DATA_SaleItemRule.discountamount
						            else DATA_SaleItemRule.Price
								end) else 0 end as grossamount,
						   case when cnf_promotion.PromotionType = 7 then abs(case when DATA_SaleItemRule.discountamount &lt;&gt; 0 then DATA_SaleItemRule.discountamount
						            else DATA_SaleItemRule.Price
								end) else 0 end as netamount,
						   0 as price,
						   100 as percentage,
						   0 as remaningValues, 
						   RR_DATA_REVENUE.revenueamount,
						   p.Accountingtype,		
						   RR_DATA_REVENUE.RRCalcTypeTrigger,
						   RR_DATA_REVENUE.RRPercentage,
						   RR_DATA_REVENUE.RRDays,
						   DATA_SaleItemRule.SaleItemRuleId,
						   p.matrixcellid

					from RR_DATA_REVENUE WITH(NOLOCK)
						INNER JOIN DATA_Transaction	 WITH(NOLOCK)					on data_transaction.transactionid = rr_data_revenue.transactionid
						LEFT  JOIN DATA_Sale WITH(NOLOCK)				            ON DATA_Sale.SaleID = data_transaction.SaleID
						LEFT  JOIN DATA_SaleItem	WITH(NOLOCK)		            ON DATA_SaleItem.saleitemid = RR_DATA_REVENUE.saleitemid
						LEFT JOIN DATA_SaleItemRule	WITH(NOLOCK)					ON data_saleitemrule.saleitemid = DATA_SaleItem.saleitemid
																						and data_saleitemrule.saleitemruleid = rr_data_revenue.saleitemruleid
						LEFT JOIN CNF_PromotionItemRule	WITH(NOLOCK)				ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
						LEFT JOIN CNF_PromotionItem WITH(NOLOCK)					ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
						LEFT JOIN CNF_Promotion	 WITH(NOLOCK)						ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId	
						LEFT JOIN COA_CNF_Account	COA	WITH(NOLOCK)		        ON COA.coaaccountid = CNF_Promotion.coaaccountid
						
						
						INNER JOIN (select transactionid, RevenueRecognitionRuleId, RRCalcTypeWhere, saleitemid, matrixcellid,
											RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount,  Accountingtype
											from RR_DATA_Revenue WITH(NOLOCK)
											INNER JOIN COA_CNF_Account WITH(NOLOCK)		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
											where COA_CNF_Account.coaAccountID = @DiscountAccountID
										)p    on p.transactionid = 	DATA_Transaction.transactionid and p.saleitemid = rr_data_revenue.saleitemid



					where ((RR_DATA_REVENUE.coaaccountid = @DiscountAccountID) or (cnf_promotion.Promotiontype in (3, 5, 7, 101, 200)))
					and RR_DATA_REVENUE.coaaccountid = @DiscountAccountID
					and DATA_Transaction.TransactionType in (select transactionid
																from #TransactionIDs)
					and RR_DATA_REVENUE.fcalcdate = @BatchDate
					 and data_transaction.transactiontype not in (46, 47, 51)

					)p
					where revenueamount &lt;&gt; 0	
					  and coaaccountid is not null													
																																								
		----		--Reverse out Discounts														
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[Ticketid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays]
				   ,[saleitemruleid])	
				   select COAAccountId, 
						   RevenueRecognitionRuleId,		   
						   RRCalcTypeWhere,
						   RRCalcTypeMethod,	   
						   COAAccountConfigId,
						   COAAccountTypeId,
						   Transactionid,
						   Saleid,
						   ticketid,
						   SiteID,
						   OperatingAreaID,
						   Workstationid,
						   UserGroupID,
						   userID,
						   batchdate,
						   quantity,
						   grossamount,
						   netamount,
						   price,
						   percentage,
						   remaningValues, 	
						   sum(RevenueAmount),
						   Accountingtype,		
						   RRCalcTypeTrigger,
						   RRPercentage,
						   RRDays,
						   saleitemruleid
				   from (		    
				select distinct 				           
                           p.COAAccountId, 
						   p.RevenueRecognitionRuleId,	   
						   p.RRCalcTypeWhere,
						   p.RRCalcTypeMethod,	   
						   p.COAAccountConfigId,
						   p.COAAccountTypeId,
						   rr_data_Revenue.Transactionid,
						   rr_data_Revenue.saleid,
						   rr_data_Revenue.ticketid,
						   rr_data_Revenue.saleitemid,
						   rr_data_Revenue.Siteid,
						   rr_data_Revenue.OperatingAreaId,
						   rr_data_Revenue.Workstationid,
						   rr_data_Revenue.UserGroupid,
						   rr_data_Revenue.UserId,
						   @BatchDate batchdate,
							0 as quantity,
						   0 as grossamount,
						   0 as netamount,
						   0 as price,
						   100 as percentage,
						   0 as remaningValues,
						   rr_data_Revenue.RevenueAmount  as RevenueAmount,
						   case when p.accountingtype = 1 then 2
					        else 1
						   end Accountingtype,
						   p.RRCalcTypeTrigger,
						   p.RRPercentage,
						   p.RRDays,
						   rr_data_Revenue.matrixcellid,
 						   rr_data_Revenue.RevenueRecognitionDataId,
						   rr_data_Revenue.saleitemruleid

						  FROM rr_data_Revenue WITH(NOLOCK)  
								   INNER JOIN (select RR_DATA_Revenue.saleid, RR_DATA_Revenue.transactionid, RevenueRecognitionRuleId, RRCalcTypeWhere, Saleitemid, RR_DATA_Revenue.COAAccountId, 
													   RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount, COA_CNF_Account.COAAccountTypeId,  Accountingtype,
													   rr_data_Revenue.RevenueRecognitionDataId, saleitemruleid
													  from RR_DATA_Revenue WITH(NOLOCK)
														INNER JOIN COA_CNF_Account WITH(NOLOCK)		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
														INNER JOIN data_transaction WITH(NOLOCK)     on data_transaction.transactionid = RR_DATA_Revenue.transactionid 
													 where COA_CNF_Account.coaAccountID = @DiscountAccountID
													  and data_transaction.transactiontype not in (46, 47, 51)
													  and revenueamount &lt;&gt; 0
													)p								ON p.saleid = 	rr_data_Revenue.saleid and p.saleitemid = rr_data_revenue.saleitemid and p.saleitemruleid = rr_data_revenue.saleitemruleid
								INNER JOIN data_transaction  WITH(NOLOCK)       on data_transaction.transactionid = rr_data_revenue.transactionid

						where  Rr_data_Revenue.coaaccountid in (select coaaccountid from cnf_promotion WITH(NOLOCK))

						 and RR_DATA_REVENUE.fcalcdate = @BatchDate
						 and data_transaction.transactiontype not in (46, 47, 51)
						 and rr_data_Revenue.coaAccountID &lt;&gt; @DiscountAccountID
						 and DATA_Transaction.TransactionType in (select transactionid
															from #TransactionIDs)
						 and Rr_data_Revenue.Accountingtype = case when DATA_Transaction.TransactionType in (5, 17, 18, 20, 22, 30) and (select discountamount from data_saleitemrule where data_saleitemrule.saleitemid = rr_data_revenue.saleitemid  and promotiontype &lt;&gt; 3) &lt; 0 then 2
						                                           when RR_DATA_REVENUE.Accountingtype = 2 and (select discountamount from data_saleitemrule where data_saleitemrule.saleitemid = rr_data_revenue.saleitemid) &gt; 0 then 2 
						                                           else 1
															   end
						)p		
						
						group by  COAAccountId, 
						   RevenueRecognitionRuleId,	   
						   RRCalcTypeWhere,
						   RRCalcTypeMethod,	   
						   COAAccountConfigId,
						   COAAccountTypeId,
						   Transactionid,
						   Saleid,
						   SiteID,
						   OperatingAreaID,
						   Workstationid,
						   UserGroupID,
						   userID,
						   batchdate,
						   quantity,
						   grossamount,
						   netamount,
						   price,
						   percentage,
						   remaningValues, 	
						   Accountingtype,		
						   RRCalcTypeTrigger,
						   RRPercentage,
						   RRDays,
						   ticketid,
						   saleitemruleid
						   
 						   																																																																																		

	----Added for COA 7.4.21
	----COA for Rounding Pennies
					INSERT INTO [dbo].[RR_DATA_Revenue]
					   ([COAAccountId]
					   ,[RevenueRecognitionRuleId]
					   ,[RRCalcTypeWhere]
					   ,[RRCalcTypeMethod]
					   ,[COAAccountConfigId]
					   ,[COAAccountType]
					   ,[TransactionId]
					   ,[SaleId]
					   ,[SiteId]
					   ,[OperatingAreaId]
					   ,[WorkstationId]
					   ,[UserGroupId]
					   ,[UserId]
					   ,[FCalcDate]
					   ,[Quantity]
					   ,[GrossAmount]
					   ,[NetAmount]
					   ,[Price]
					   ,[Percentage]
					   ,[RemaningValues]
					   ,[RevenueAmount]
					    ,[AccountingType]
					   ,[RRCalcTypeTrigger]
					   ,[RRPercentage]
					   ,[RRDays])					   		    
							select distinct COA_CNF_Account.COAAccountId, 
							   RR_DATA_REVENUE.RevenueRecognitionRuleId,	   
							   RR_DATA_REVENUE.RRCalcTypeWhere,
							   RR_DATA_REVENUE.RRCalcTypeMethod,	   
							   @AccountConfigID,
							   COA_CNF_Account.COAAccountTypeId,
							   RR_DATA_REVENUE.Transactionid as Transactionid,
							   RR_DATA_REVENUE.saleid as Saleid,
							   RR_DATA_REVENUE.Siteid as SiteID,
							   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
							   RR_DATA_REVENUE.Workstationid as Workstationid,
							   ISNULL(RR_DATA_REVENUE.UserGroupid, DATA_Transaction.usergroupid) as UserGroupID,
							   RR_DATA_REVENUE.UserId as userID,
							   @BatchDate as batchdate,
							   0 as Quantity,
							   0 as GrossAmount,
							   0 as NetAmount,
							   0 as Price,
							   100 as Percentage,
							   0 as RemainingValue, 	
							   abs(DATA_Transaction.Rounding),
							   case when data_payment.paymentamount &gt; 0 then case when DATA_Transaction.Rounding &lt; 0 then 1 else 2 end
								    when data_payment.paymentamount &lt; 0 then case when DATA_Transaction.Rounding &gt; 0 and data_transaction.transactiontype in (40) then 2 else 1 end
									when data_payment.paymentamount &lt; 0 then case when DATA_Transaction.Rounding &lt; 0 then 2 else 1 end									
								end,		
							    RR_DATA_REVENUE.RRCalcTypeTrigger,
							    RR_DATA_REVENUE.RRPercentage,
							    RR_DATA_REVENUE.RRDays

					from RR_DATA_REVENUE WITH(NOLOCK)
						INNER JOIN DATA_Transaction	WITH(NOLOCK)					on data_transaction.transactionid = rr_data_revenue.transactionid
						INNER JOIN data_payment	WITH(NOLOCK)						on data_payment.transactionid = rr_data_revenue.transactionid
						INNER JOIN CNF_Currency	WITH(NOLOCK)						on cnf_currency.CurrencyId = data_payment.CurrencyId
						INNER JOIN CNF_RoundingRule	WITH(NOLOCK)					on cnf_roundingrule.roundingruleid = cnf_currency.roundingruleid
						INNER JOIN COA_CNF_Account  WITH(NOLOCK) 					on COA_CNF_Account.COAAccountid = CNF_RoundingRule.COAAccountid

					where DATA_Transaction.Rounding &lt;&gt; 0
						and DATA_Transaction.TransactionType in (select transactionid
																	from #TransactionIDs)
						and RR_DATA_REVENUE.fcalcdate = @BatchDate
						and RR_DATA_REVENUE.RevenueRecognitionRuleId = @SuspendID 


----COA for Donations
	INSERT INTO [dbo].[RR_DATA_Revenue]
					   ([COAAccountId]
					   ,[RevenueRecognitionRuleId]
					   ,[RRCalcTypeWhere]
					   ,[RRCalcTypeMethod]
					   ,[COAAccountConfigId]
					   ,[COAAccountType]
					   ,[TransactionId]
					   ,[SaleId]
					   ,[SiteId]
					   ,[OperatingAreaId]
					   ,[WorkstationId]
					   ,[UserGroupId]
					   ,[UserId]
					   ,[FCalcDate]
					   ,[Quantity]
					   ,[GrossAmount]
					   ,[NetAmount]
					   ,[Price]
					   ,[Percentage]
					   ,[RemaningValues]
					   ,[RevenueAmount]
					    ,[AccountingType]
					   ,[RRCalcTypeTrigger]
					   ,[RRPercentage]
					   ,[RRDays])	
						select distinct COA_CNF_Account.COAAccountId, 
							   RR_DATA_REVENUE.RevenueRecognitionRuleId,	   
							   RR_DATA_REVENUE.RRCalcTypeWhere,
							   RR_DATA_REVENUE.RRCalcTypeMethod,	   
							   @AccountConfigID,
							   COA_CNF_Account.COAAccountTypeId,
							   RR_DATA_REVENUE.Transactionid as Transactionid,
							   RR_DATA_REVENUE.saleid as Saleid,
							   RR_DATA_REVENUE.Siteid as SiteID,
							   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
							   RR_DATA_REVENUE.Workstationid as Workstationid,
							   RR_DATA_REVENUE.UserGroupid as UserGroupID,
							   RR_DATA_REVENUE.UserId as userID,
							   @BatchDate as batchdate,
							   0 as Quantity,
							   0 as GrossAmount,
							   0 as NetAmount,
							   0 as Price,
							   100 as Percentage,
							   0 as RemainingValue, 	
							   abs(data_payment.donationamount),
							   case when data_payment.donationamount  &gt; 0 then 2
							        else 1
								end as accountingtype,		
							   RR_DATA_REVENUE.RRCalcTypeTrigger,
							   RR_DATA_REVENUE.RRPercentage,
							   RR_DATA_REVENUE.RRDays
							from RR_DATA_REVENUE
								INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
								INNER JOIN data_payment							on data_payment.transactionid = rr_data_revenue.transactionid
								INNER JOIN CNF_DonationForm						on CNF_DonationForm.donationformid = data_payment.donationformid
								INNER JOIN COA_CNF_Account   					on COA_CNF_Account.COAAccountid = CNF_DonationForm.COAAccountid

							where data_payment.donationamount &lt;&gt; 0
							and DATA_Transaction.TransactionType in (select transactionid
																	from #TransactionIDs)
								and RR_DATA_REVENUE.coaaccountid = 2
								and RR_DATA_REVENUE.fcalcdate = @BatchDate

		
		End



</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>sloporto</ADDEDBY><SQLVERSION>3320</SQLVERSION><RMTRACKLINK>IDBOS-4154</RMTRACKLINK><REASON>0)  Add the column "AttachedTicketByType"  to the table "CNF_DocTemplate"
1) Add the column "SinglePDF"  to the table "CNF_MatrixCell"</REASON><TABLENAMES>CNF_DocTemplate=DocTemplateId
CNF_MatrixCell=MatrixCellId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'AttachedTicketByType' 
                      AND OBJECT_ID = OBJECT_ID(N'CNF_DocTemplate'))
BEGIN
  ALTER TABLE CNF_DocTemplate 
  ADD AttachedTicketByType SmallInt NULL;     
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'SinglePDF' 
                      AND OBJECT_ID = OBJECT_ID(N'CNF_MatrixCell'))
BEGIN
  ALTER TABLE CNF_MatrixCell 
  ADD SinglePDF SmallInt NULL;     
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>3319</SQLVERSION><RMTRACKLINK>IDBOS-5080</RMTRACKLINK><REASON>New index on RR_DATA_Revenue</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                FROM sys.indexes 
            WHERE name='IDX_RR_DATA_Revenue_CoaAccountID' AND object_id = OBJECT_ID('RR_DATA_Revenue')
			)
BEGIN
	CREATE NONCLUSTERED INDEX [IDX_RR_DATA_Revenue_CoaAccountID]
	ON [dbo].[RR_DATA_Revenue] ([COAAccountId])
	INCLUDE ([RevenueRecognitionRuleId],[RRCalcTypeTrigger],[AccountingType])
END                 </SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>pchen</ADDEDBY><SQLVERSION>3318</SQLVERSION><RMTRACKLINK>IDBOS-4509</RMTRACKLINK><REASON>Add TipsAmount field in DATA_Payment</REASON><TABLENAMES>DATA_Payment=PaymentId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'TipsAmount' 
                      AND OBJECT_ID = OBJECT_ID(N'DATA_Payment'))
BEGIN
  ALTER TABLE DATA_Payment 
  ADD TipsAmount float NULL;     
END </SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>ecandido</ADDEDBY><SQLVERSION>3317</SQLVERSION><RMTRACKLINK>IDBOS-4624</RMTRACKLINK><REASON>Multiple Declaration on Gift Aid</REASON><TABLENAMES>DATA_AccountGiftAid=AccountGiftAidId
DATA_SaleItem2Gift=SaleItem2GiftId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.objects 
WHERE object_id = OBJECT_ID(N'[DATA_AccountGiftAid2]') AND type in (N'U'))
DROP TABLE DATA_AccountGiftAid2</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>CREATE TABLE DATA_AccountGiftAid2
(
	AccountGiftAidId int IDENTITY(1,1) NOT NULL,
	AccountId int NOT NULL,
	InsertDateTime datetime NOT NULL,
	UpdateDateTime datetime NOT NULL,
	DeclarationStartDate datetime NOT NULL,
	DeclarationEndDate datetime NOT NULL,
	Active int NOT NULL,
	SingleUse int NOT NULL,
        PRIMARY KEY (AccountGiftAidId)
)</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>ALTER TABLE DATA_AccountGiftAid2
ADD  CONSTRAINT FK_DATA_AccountGiftAid_DATA_Account FOREIGN KEY(AccountId)
REFERENCES [DATA_Account] ([AccountId])</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>DECLARE @AccountId INT
DECLARE @DeclarationStartDate DATETIME
DECLARE @DeclarationENDDate DATETIME

DECLARE cur_print CURSOR FOR select AccountId, DeclarationStartDate, DeclarationEndDate from DATA_AccountGiftAid

OPEN cur_print
FETCH NEXT FROM cur_print INTO @AccountId, @DeclarationStartDate, @DeclarationENDDate

WHILE @@FETCH_STATUS = 0
BEGIN
  insert into
    DATA_AccountGiftAid2(AccountId, InsertDateTime, UpdateDateTime, DeclarationStartDate, DeclarationEndDate, Active, SingleUse)
  values
    (@AccountId, GETDATE(), GETDATE(), @DeclarationStartDate, @DeclarationENDDate, 1, 0)
  
  FETCH NEXT FROM cur_print INTO @AccountId, @DeclarationStartDate, @DeclarationENDDate
END
CLOSE cur_print
DEALLOCATE cur_print</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>DROP TABLE DATA_AccountGiftAid</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>EXEC sp_rename 'DATA_AccountGiftAid2', 'DATA_AccountGiftAid'</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>ALTER TABLE DATA_SaleItem2Gift 
  ADD AccountGiftAidId Int NULL;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>ALTER TABLE DATA_SaleItem2Gift
ADD  CONSTRAINT FK_DATA_SaleItem2Gift_DATA_AccountGiftAid FOREIGN KEY(AccountGiftAidId)
REFERENCES [DATA_AccountGiftAid] ([AccountGiftAidId])</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>pchen</ADDEDBY><SQLVERSION>3316</SQLVERSION><RMTRACKLINK>IDBOS-4218</RMTRACKLINK><REASON>Extend ReferenceNumber to 60 chars</REASON><TABLENAMES>DATA_PaymentCard=PaymentId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'ReferenceNumber' 
                      AND OBJECT_ID = OBJECT_ID(N'DATA_PaymentCard'))
BEGIN
  ALTER TABLE DATA_PaymentCard
  ALTER COLUMN ReferenceNumber Nvarchar(60) NULL     
END </SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3315</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>0) Add MailTemplateId field</REASON><TABLENAMES>CNF_Event=EventId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
              WHERE Name = N'MailTemplateId'
              AND OBJECT_ID = OBJECT_ID(N'CNF_Event'))
BEGIN
  ALTER TABLE CNF_Event
  ADD MailTemplateId int NULL;
END
              </SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>scoluccia</ADDEDBY><SQLVERSION>3314</SQLVERSION><RMTRACKLINK>4943</RMTRACKLINK><REASON>The scenario is a transaction with multiple tickets linked to the same performance, change the performance to just one ticket all the other tickets lose the link to the performance

In DATA_SaleItem2Ticket before we created a record for each ticket sold,
when we changed the performance we added a new record with operationtype = 11, while the first item remain operationtyepe = 1 (Create)
The solution is to change this logic, now we set operationtype = 1 to the last and valid item, and  set 11 to all the previous items
in the DATA_Saleitem2Performance the field "active" remain = 1 so the other tickets continue to link to the performance,
previous

-- before executed script
SaleItem2TicketId	TicketId	SaleItemId	OperationType
98100	                 98475	102230	                         11    &lt;--- this is the last and valid item
98099	                 98475	102228	                        1    &lt;-- previous item not valid anymore
98098	                 98475	102226	                        1    &lt;-- previous item not valid anymore

-- After executed script
SaleItem2TicketId	TicketId	SaleItemId	OperationType
98100	                 98475	102230	                          1    &lt;--- this is the last and valid item
98099	                 98475	102228	                        11    &lt;-- previous item not valid anymore
98098	                 98475	102226	                        11    &lt;-- previous item not valid anymore
</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>-- Verify if exist at least a change performance and operationtype = 1 and DATA_SaleItem2Performance active = 0 
IF EXISTS(
          select Count(SI2T.TicketId) from DATA_SaleItem2Ticket SI2T 
                                      inner join DATA_SaleItem2Performance SI2P on (SI2P.SaleItemId = SI2T.SaleItemId) 
          where SI2T.TicketId in 
                           (select SI2T.TicketId from DATA_SaleItem2Ticket  SI2T
                                                 inner join DATA_SaleItem2Performance SI2P on ((SI2P.SaleItemId = SI2T.SaleItemId) and (SI2P.Active = 0)) 
	                               where (SI2T.OperationType in (1,11)) 
                    	   ) and  (SI2P.Active = 0) and (SI2T.OperationType = 1)
)
BEGIN
-- Step 1: check if there is at least a change performance and operationtype = 1 and DATA_SaleItem2Performance active = 0 update te current 11 to 111
	update DATA_SaleItem2Ticket set Operationtype = 111 where OperationType = 11 and TicketId in 
	  (select SI2T.TicketId from DATA_SaleItem2Ticket SI2T 
							inner join DATA_SaleItem2Performance SI2P on (SI2P.SaleItemId = SI2T.SaleItemId) 
		 where SI2T.TicketId in 
		   (select SI2T.TicketId from DATA_SaleItem2Ticket  SI2T
								inner join DATA_SaleItem2Performance SI2P on (SI2P.SaleItemId = SI2T.SaleItemId and SI2P.Active = 0) 
			where (SI2T.OperationType in (1,11)) 
		   ) and  (SI2P.Active = 0) and (SI2T.OperationType = 1)
	  ) 

-- Step 2: check if there is at least a operationtype = 111 (new temp value) and update DATA_SaleItem2Ticket operationtype from 1 to 11
	update DATA_SaleItem2Ticket set Operationtype = 11 where OperationType = 1 and TicketId in 
	  (select SI2T.TicketId from DATA_SaleItem2Ticket SI2T where SI2T.TicketId in 
		   (select SI2T.TicketId from DATA_SaleItem2Ticket  SI2T
								inner join DATA_SaleItem2Performance SI2P on (SI2P.SaleItemId = SI2T.SaleItemId) 
			where (SI2T.OperationType in (111)) 
		   )
	  )

-- Step 3: check if there is at least a operationtype = 111 (new temp value) and active = 0, if true update DATA_SaleItem2Ticket operationtype from 111 to 11 ( This case is only for multiple change performance on the same ticket)
	update DATA_SaleItem2Ticket set Operationtype = 11 where OperationType = 111 and SaleItemId in 
	  (select SI2T.SaleItemId from DATA_SaleItem2Ticket SI2T where SI2T.SaleItemId in 
		   (select SI2T.SaleItemId from DATA_SaleItem2Performance SI2P 
								inner join DATA_SaleItem2Ticket  SI2T on (SI2P.SaleItemId = SI2T.SaleItemId and SI2P.Active = 0) 
			where (SI2T.OperationType in (111)) 
		   )
	  )

-- Step 4: check if there is at least a operationtype = 111 (new temp value) and active = 1, if true update DATA_SaleItem2Ticket operationtype from 111 to 1
	update DATA_SaleItem2Ticket set Operationtype = 1 where OperationType = 111 and SaleItemId in 
	  (select SI2T.SaleItemId from DATA_SaleItem2Ticket SI2T where SI2T.SaleItemId in 
		   (select SI2T.SaleItemId from DATA_SaleItem2Performance SI2P 
								inner join DATA_SaleItem2Ticket  SI2T on (SI2P.SaleItemId = SI2T.SaleItemId and SI2P.Active = 1) 
			where (SI2T.OperationType in (111)) 
		   )
	  )

-- Step 5: check if there is at least a DATA_SaleItem2Performance active = 0 and a change performance operation, if true update DATA_SaleItem2Performance active from 0 to 1
	update DATA_SaleItem2Performance set Active = 1 where Active = 0 and SaleItemId in 
		   (select Distinct(SI2T.SaleItemId) from DATA_SaleItem2Performance SI2P 
								inner join DATA_SaleItem2Ticket  SI2T on (SI2P.SaleItemId = SI2T.SaleItemId and SI2P.Active = 0) 
			where (SI2T.OperationType in (11)) 
		   )
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3313</SQLVERSION><RMTRACKLINK>IDBOS-1732</RMTRACKLINK><REASON>0) Added the Column "LimitToQuantity" to the Table CNF_PromotionItemRule
</REASON><TABLENAMES>CNF_PromotionItemRule=PromotionItemRuleId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
          WHERE Name = N'LimitToQuantity' 
          AND OBJECT_ID = OBJECT_ID(N'CNF_PromotionItemRule'))
BEGIN
  ALTER TABLE CNF_PromotionItemRule
  ADD [LimitToQuantity] Integer DEFAULT 0 NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3312</SQLVERSION><RMTRACKLINK>IDBOS-4409</RMTRACKLINK><REASON>0) Added the Column "ShowExtInfoBefAddBask" to the Table CNF_MatrixCellInfo</REASON><TABLENAMES>CNF_MatrixCellInfo=MatrixCellInfoId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
	  WHERE Name = N'ShowExtInfoBefAddBask' 
	  AND OBJECT_ID = OBJECT_ID(N'CNF_MatrixCellInfo'))
BEGIN
  ALTER TABLE CNF_MatrixCellInfo
  ADD ShowExtInfoBefAddBask Integer DEFAULT 0 NOT NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>3311</SQLVERSION><RMTRACKLINK>IDBOS-4305</RMTRACKLINK><REASON>COA - Tax issue when you have 2 taxes with the same percentage used.</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
          WHERE Name = N'SaleItemTaxId' 
          AND OBJECT_ID = OBJECT_ID(N'RR_DATA_Revenue'))
BEGIN
  ALTER TABLE RR_DATA_Revenue
  ADD SaleItemTaxId Integer NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>ecandido</ADDEDBY><SQLVERSION>3310</SQLVERSION><RMTRACKLINK>IDBOS-2963</RMTRACKLINK><REASON>Add Field RequirementTypeIdRoot in Table RES_CNF_RequirementType</REASON><TABLENAMES>RES_CNF_RequirementType=RequirementTypeId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
          WHERE Name = N'RequirementTypeIdRoot' 
          AND OBJECT_ID = OBJECT_ID(N'RES_CNF_RequirementType'))
BEGIN
  ALTER TABLE RES_CNF_RequirementType
  ADD [RequirementTypeIdRoot] Integer DEFAULT 0 NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>ecandido</ADDEDBY><SQLVERSION>3309</SQLVERSION><RMTRACKLINK>IDBOS-2962</RMTRACKLINK><REASON>Add Field PriorityOrder into RES_CNF_Resource</REASON><TABLENAMES>RES_CNF_Resource=ResourceId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
          WHERE Name = N'PriorityOrder' 
          AND OBJECT_ID = OBJECT_ID(N'RES_CNF_Resource'))
BEGIN
  ALTER TABLE RES_CNF_Resource
  ADD [PriorityOrder] Integer DEFAULT 0 NOT NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>UPDATE
  RES_CNF_Resource
SET
  PriorityOrder = 0
WHERE
  PriorityOrder IS NULL</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3308</SQLVERSION><RMTRACKLINK>IDBOS-3686</RMTRACKLINK><REASON>0) Create Table CNF_Promotion2Account
1) Add Foreign Key on field PromotionId
2) Add Foreign Key on field AccountId
3) Add Foreign Key on field DmgCategoryId
4) Add Foreign Key on field Last_UserId_Log
5) Add Foreign Key on field WorkstationId_Log
6) Add First Index on PromotionId,AccountId,Enabled
7) Add Second Index on PromotionId,DmgCategoryId,Enabled
___________________________________________________________________
8) Create Table DATA_Promotion2Account
9) Add Foreign Key on field PromotionId
10) Add Foreign Key on field AccountId
11) Add Foreign Key on field SaleId
___________________________________________________________________
12) Added the Column "UseQuotaForAccounts" to the Table CNF_Promotion
13) Script to update UseQuotaForAccounts value to zero
</REASON><TABLENAMES>CNF_Promotion2Account=Promotion2AccountId
DATA_Promotion2Account=Promotion2AccountId
CNF_Promotion=PromotionId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND TABLE_NAME = 'CNF_Promotion2Account')
BEGIN
  CREATE TABLE CNF_Promotion2Account
  (
    Promotion2AccountId int IDENTITY(1,1) NOT NULL,
    PromotionId int NOT NULL,
    PromotionType smallint NULL,
    AccountId int NULL,
    DmgCategoryId int NULL,
    Quota int NOT NULL,
    Enabled smallint NOT NULL,
    Last_UserId_Log int NOT NULL,
    Last_WorkstationId_Log int NOT NULL,
    Last_DateTime_Log datetime NULL
    PRIMARY KEY (Promotion2AccountId)
  )
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Promotion2Account_PromotionId')
BEGIN
  ALTER TABLE CNF_Promotion2Account
  ADD  CONSTRAINT FK_CNF_Promotion2Account_PromotionId FOREIGN KEY(PromotionId)
  REFERENCES [CNF_Promotion] ([PromotionId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Promotion2Account_AccountId')
BEGIN
  ALTER TABLE CNF_Promotion2Account
  ADD  CONSTRAINT FK_CNF_Promotion2Account_AccountId FOREIGN KEY(AccountId)
  REFERENCES [DATA_Account] ([AccountId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Promotion2Account_DmgCategoryId')
BEGIN
  ALTER TABLE CNF_Promotion2Account
  ADD  CONSTRAINT FK_CNF_Promotion2Account_DmgCategoryId FOREIGN KEY(DmgCategoryId)
  REFERENCES [CNF_DmgCategory] ([DmgCategoryId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Promotion2Account_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_Promotion2Account
  ADD  CONSTRAINT FK_CNF_Promotion2Account_Last_UserId_Log FOREIGN KEY([Last_UserId_Log])
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Promotion2Account_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_Promotion2Account
  ADD  CONSTRAINT FK_CNF_Promotion2Account_Last_WorkstationId_Log FOREIGN KEY([Last_WorkstationId_Log])
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT object_id
               FROM sys.indexes
               WHERE Name = 'Idx_CNF_Promotion2Account_AccountId')
BEGIN
	CREATE NONCLUSTERED INDEX Idx_CNF_Promotion2Account_AccountId ON [dbo].CNF_Promotion2Account
	(
		[PromotionId] ASC,
		[AccountId] ASC,
                [Enabled]
	)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT object_id
               FROM sys.indexes
               WHERE Name = 'Idx_CNF_Promotion2Account_DmgCategoryId')
BEGIN
	CREATE NONCLUSTERED INDEX Idx_CNF_Promotion2Account_DmgCategoryId ON [dbo].CNF_Promotion2Account
	(
		[PromotionId] ASC,
		[DmgCategoryId] ASC,
                [Enabled]    
	)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND TABLE_NAME = 'DATA_Promotion2Account')
BEGIN
  CREATE TABLE DATA_Promotion2Account
  (
    Promotion2AccountId int IDENTITY(1,1) NOT NULL,
    PromotionId int NOT NULL,
    AccountId int NOT NULL,
    Used smallint NOT NULL,
    PromotionType smallint NOT NULL,
    SaleId int NOT NULL,
    Last_DateTime_Log datetime NULL
    
    PRIMARY KEY (Promotion2AccountId)  
  )
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_Promotion2Account_PromotionId')
BEGIN
  ALTER TABLE DATA_Promotion2Account
  ADD  CONSTRAINT FK_DATA_Promotion2Account_PromotionId FOREIGN KEY(PromotionId)
  REFERENCES [CNF_Promotion] ([PromotionId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_Promotion2Account_AccountId')
BEGIN
  ALTER TABLE DATA_Promotion2Account
  ADD  CONSTRAINT FK_DATA_Promotion2Account_AccountId FOREIGN KEY(AccountId)
  REFERENCES [DATA_Account] ([AccountId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_Promotion2Account_SaleId')
BEGIN
  ALTER TABLE DATA_Promotion2Account
  ADD  CONSTRAINT FK_DATA_Promotion2Account_SaleId FOREIGN KEY(SaleId)
  REFERENCES [DATA_Sale] ([SaleId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
          WHERE Name = N'UseQuotaForAccounts' 
          AND OBJECT_ID = OBJECT_ID(N'CNF_Promotion'))
BEGIN
  ALTER TABLE CNF_Promotion
  ADD [UseQuotaForAccounts] smallint DEFAULT 0 NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>UPDATE CNF_Promotion
SET UseQuotaForAccounts = 0</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>scoluccia</ADDEDBY><SQLVERSION>3307</SQLVERSION><RMTRACKLINK>3986</RMTRACKLINK><REASON>-  DATA_Batch2Reservation
0) Create Table DATA_Batch2Reservation
1) Add Foreign Key on field Last_UserId_Log
2) Add Foreign Key on field Last_WorkstationId_Log
3) Add Foreign Key on field SaleID
4) Add Foreign Key on field BatchId
- Table DATA_Batch 
added new fields
5)  BatchPrintCode  
dropped fields
6) BatchDate
7) BatchTask
8) BatchStatus
9) BatchPriority
10) drop contraint and index for BatckAK
11) BatchAK
12) Add Index on field PrintBatchCode</REASON><TABLENAMES>DATA_Batch2Reservation=Batch2ReservationId
DATA_Batch=BatchId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND TABLE_NAME = 'DATA_Batch2Reservation')
BEGIN

  CREATE TABLE DATA_Batch2Reservation
  (
	Batch2ReservationId int IDENTITY(1,1) NOT NULL,
        SaleID int NOT NULL,
	BatchId int NOT NULL,
	Last_UserId_Log int NOT NULL,
	Last_WorkstationId_Log int NOT NULL,
	Last_DateTime_Log datetime NULL

    PRIMARY KEY (Batch2ReservationId)
  )
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_Batch2Reservation_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_Batch2Reservation
  ADD  CONSTRAINT FK_DATA_Batch2Reservation_Last_UserId_Log FOREIGN KEY([Last_UserId_Log])
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_Batch2Reservation_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_Batch2Reservation
  ADD  CONSTRAINT FK_DATA_Batch2Reservation_Last_WorkstationId_Log FOREIGN KEY([Last_WorkstationId_Log])
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_Batch2Reservation_SaleId')
BEGIN
  ALTER TABLE DATA_Batch2Reservation
  ADD  CONSTRAINT FK_DATA_Batch2Reservation_SaleId FOREIGN KEY([SaleId])
  REFERENCES [DATA_Reservation] ([SaleId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_Batch2Reservation_BatchId')
BEGIN
  ALTER TABLE DATA_Batch2Reservation
  ADD  CONSTRAINT FK_DATA_Batch2Reservation_BatchId FOREIGN KEY([BatchId])
  REFERENCES [DATA_Batch] ([BatchId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
              WHERE Name = N'BatchPrintCode' AND OBJECT_ID = OBJECT_ID(N'DATA_Batch'))
BEGIN
  DECLARE @COUNT INT
  SET @COUNT = (SELECT Count(*) FROM DATA_Batch)
  IF @COUNT &gt; 0
  BEGIN
    ALTER TABLE DATA_Batch ADD BatchPrintCode Varchar(30) DEFAULT '-' NOT NULL
  END
  ELSE
  BEGIN
    ALTER TABLE DATA_Batch ADD BatchPrintCode Varchar(30) NOT NULL
  END
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF  EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'BatchDate' AND
                Object_ID  = Object_ID(N'DATA_Batch'))
BEGIN
  ALTER TABLE DATA_Batch drop column BatchDate 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF  EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'BatchTask' AND
                Object_ID  = Object_ID(N'DATA_Batch'))
BEGIN
  ALTER TABLE DATA_Batch drop column BatchTask
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF  EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'BatchStatus' AND
                Object_ID  = Object_ID(N'DATA_Batch'))
BEGIN
  ALTER TABLE DATA_Batch drop column BatchStatus
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF  EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'BatchPriority' AND
                Object_ID  = Object_ID(N'DATA_Batch'))
BEGIN
  ALTER TABLE DATA_Batch drop column BatchPriority
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>  DECLARE @index_name NVARCHAR(MAX), @table_name NVARCHAR(MAX), @field_name NVARCHAR(MAX)

-- search an index based on field BatchAK in the table DATA_Batch, I have to do this query because the index name changes in each DB
  SET @table_name = 'DATA_Batch'
  SET @field_name = 'BatchAK'

  SELECT TOP 1
    @index_name = sysindex.name
  FROM 
    sys.indexes AS SysIndex
    INNER JOIN sys.index_columns AS SysIndexCol ON SysIndex.object_id = SysIndexCol.object_id AND SysIndex.index_id = SysIndexCol.index_id 
    INNER JOIN sys.columns AS SysCols ON SysIndexCol.column_id = SysCols.column_id AND SysIndexCol.object_id = SysCols.object_id 
  WHERE 
     type &lt;&gt; 0 
     AND SysIndex.object_id in (Select systbl.object_id from sys.tables as systbl
     WHERE SysTbl.name = @table_name)
     AND SysCols.name = @field_name

  IF @index_name IS NOT NULL
  BEGIN
    DECLARE @sql1 NVARCHAR(MAX) = N'ALTER TABLE ' + @table_name + ' DROP CONSTRAINT ' + @index_name

    exec sp_executesql @sql1
  END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF  EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'BatchAK' AND
                Object_ID  = Object_ID(N'DATA_Batch'))
BEGIN
  ALTER TABLE DATA_Batch drop column BatchAK
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT * FROM sys.columns
		  WHERE Name = N'PrintBatchCode' 
		  AND OBJECT_ID = OBJECT_ID(N'DATA_Batch2Reservation'))
BEGIN
  IF NOT EXISTS (SELECT object_id
                 FROM sys.indexes
                 WHERE Name = 'Idx_DATA_Batch2Reservation_PrintBatchCode')
  BEGIN
   	CREATE NONCLUSTERED INDEX [Idx_DATA_Batch2Reservation_PrintBatchCode] ON [dbo].[DATA_Batch2Reservation]
	    (
		   [PrintBatchCode] ASC
	    )
  END
END
</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>scoluccia</ADDEDBY><SQLVERSION>3306</SQLVERSION><RMTRACKLINK>IDBOS-2564</RMTRACKLINK><REASON>- Added the Column "ValidityDateType" to the Table CNF_PromotionValidity
- Added the Column "AdditionalInfo" to the Table DATA_SaleItem2Performance
</REASON><TABLENAMES>CNF_PromotionValidity=PromotionValidityID
DATA_SaleItem2Performance=SaleItem2PerformanceID</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
          WHERE Name = N'ValidityDateType' 
          AND OBJECT_ID = OBJECT_ID(N'CNF_PromotionValidity'))
BEGIN
  ALTER TABLE CNF_PromotionValidity
  ADD [ValidityDateType] smallint DEFAULT 0 NOT NULL
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
          WHERE Name = N'AdditionalInfo' 
          AND OBJECT_ID = OBJECT_ID(N'DATA_SaleItem2Performance'))
BEGIN
  ALTER TABLE DATA_SaleItem2Performance
  ADD [AdditionalInfo] Integer DEFAULT 0 NOT NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>3305</SQLVERSION><RMTRACKLINK>4101</RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT  TOP 1 COUNT(*)
				FROM    sys.index_columns AS ic
						INNER JOIN sys.indexes AS i		            ON ic.[object_id] = i.[object_id]
																		AND ic.index_id = i.index_id
						INNER JOIN sys.columns AS c                 ON ic.[object_id] = c.[object_id]
																		AND ic.column_id = c.column_id

				WHERE   ic.[object_id] = OBJECT_ID(N'dbo.DATA_SaleItem2Ticket')
				  AND   i.[type] != 0
				  AND   ic.is_included_column = 0
				GROUP BY i.index_id
					HAVING  COUNT(CASE WHEN c.Name = 'OperationType' THEN 1 END) &gt; 0
				ORDER BY 1
			   )
BEGIN
	IF NOT EXISTS (SELECT * 
                 FROM sys.indexes 
                WHERE name='IDXDATA_SaleItem2Ticket_OperationType' AND object_id = OBJECT_ID('DATA_SaleItem2Ticket')
			  )
	BEGIN
			CREATE NONCLUSTERED INDEX [IDXDATA_SaleItem2Ticket_OperationType]
			ON [dbo].[DATA_SaleItem2Ticket] ([OperationType])
			INCLUDE ([TicketId],[SaleItemId])
	END;
END;

</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>
IF NOT EXISTS (SELECT  TOP 1 COUNT(*)
				FROM    sys.index_columns AS ic
						INNER JOIN sys.indexes AS i		            ON ic.[object_id] = i.[object_id]
																		AND ic.index_id = i.index_id
						INNER JOIN sys.columns AS c                 ON ic.[object_id] = c.[object_id]
																		AND ic.column_id = c.column_id

				WHERE   ic.[object_id] = OBJECT_ID(N'dbo.DATA_TicketStatus')
				  AND   i.[type] != 0
				  AND   ic.is_included_column = 0
				GROUP BY i.index_id
					HAVING  COUNT(CASE WHEN c.Name = 'VoidType' THEN 1 END) &gt; 0
				ORDER BY 1
			   )
BEGIN
	IF NOT EXISTS (SELECT * 
                 FROM sys.indexes 
                WHERE name='Idx_DATA_TicketStatus_VoidType' AND object_id = OBJECT_ID('DATA_TicketStatus')
			  )
	BEGIN
		CREATE NONCLUSTERED INDEX [Idx_DATA_TicketStatus_VoidType] ON [dbo].[DATA_TicketStatus]
		(
			[VoidType] ASC
		)
	END;
END;

</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>3304</SQLVERSION><RMTRACKLINK>IDBOS-4018</RMTRACKLINK><REASON>Modified the ObjectType in order to be compliant with the lookup that identify the MatrixCell

[0] Update ObjectType</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>update CNF_UpSell_Rule set ObjectType = 1 where ObjectType = 0</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>scoluccia</ADDEDBY><SQLVERSION>3303</SQLVERSION><RMTRACKLINK>2973</RMTRACKLINK><REASON>0) Create Table DATA_BOS2CRMEntity
1) Add Foreign Key on field Last_UserId_Log
2) Add Foreign Key on field Last_WorkstationId_Log</REASON><TABLENAMES>DATA_BOS2CRMEntity=BOS2CRMEntityId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND TABLE_NAME = 'DATA_BOS2CRMEntity')
BEGIN

  CREATE TABLE DATA_BOS2CRMEntity
  (
	BOS2CRMEntityId int IDENTITY(1,1) NOT NULL,
        CRMType int NOT NULL,
	BOSEntityTable smallint NOT NULL,
	BOSEntityId int NOT NULL,
	CRMEntityTable smallint NOT NULL,
	CRMEntityId varchar(100) NULL,
	InfoStr1 varchar(100) NULL,
	InfoInt1 int NULL,
	InfoFloat1 float NULL,
	InfoDateTime1 datetime NULL,
	Last_UserId_Log int NOT NULL,
	Last_WorkstationId_Log int NOT NULL,
	Last_DateTime_Log datetime NULL

    PRIMARY KEY (BOS2CRMEntityId)
  )
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_BOS2CRMEntity_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_BOS2CRMEntity
  ADD  CONSTRAINT FK_DATA_BOS2CRMEntity_Last_UserId_Log FOREIGN KEY([Last_UserId_Log])
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_BOS2CRMEntity_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_BOS2CRMEntity
  ADD  CONSTRAINT FK_DATA_BOS2CRMEntity_Last_WorkstationId_Log FOREIGN KEY([Last_WorkstationId_Log])
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3302</SQLVERSION><RMTRACKLINK>IDBOS-3731</RMTRACKLINK><REASON>Added the Column "Enabled" to the Table SIAE_Cards</REASON><TABLENAMES>SIAE_Card=CardId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
          WHERE Name = N'Enabled' 
          AND OBJECT_ID = OBJECT_ID(N'SIAE_Card'))
BEGIN
  ALTER TABLE SIAE_Card
  ADD [Enabled] smallint DEFAULT 1 NOT NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>3301</SQLVERSION><RMTRACKLINK>IDBOS-3399</RMTRACKLINK><REASON></REASON><TABLENAMES>CNF_Performance2MatrixCell=Performance2MatrixCellId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'Last_Worskstation_Log' 
                      AND OBJECT_ID = OBJECT_ID(N'CNF_Performance2MatrixCell'))
BEGIN
  ALTER TABLE CNF_Performance2MatrixCell 
  DROP COLUMN Last_Worskstation_Log;     
END </SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'Last_WorkstationId_Log' 
                      AND OBJECT_ID = OBJECT_ID(N'CNF_Performance2MatrixCell'))
BEGIN
  ALTER TABLE CNF_Performance2MatrixCell 
  ADD Last_WorkstationId_Log Integer NULL;     
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>3300</SQLVERSION><RMTRACKLINK>IDBOS-3399</RMTRACKLINK><REASON>New table: CNF_Performance2MatrixCell</REASON><TABLENAMES>CNF_Performance2MatrixCell=Performance2MatrixCellId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT *
               FROM INFORMATION_SCHEMA.TABLES
               WHERE TABLE_SCHEMA = 'dbo'
               AND TABLE_NAME = 'CNF_Performance2MatrixCell')
BEGIN
Create table CNF_Performance2MatrixCell
(
        [Performance2MatrixCellId] [int] IDENTITY(1,1) NOT NULL,
        [PerformanceId] [int] NULL,
        [MatrixCellId] [int] NULL,
        [Price] [float] NULL,
        [Last_UserId_Log] [int] NULL,
        [Last_Worskstation_Log] [int] NULL,
        [Last_Datetime_Log] [datetime] NULL
        
        
        Primary Key (Performance2MatrixCellId)
)
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3299</SQLVERSION><RMTRACKLINK>IDBOS-3726</RMTRACKLINK><REASON>0) Add Foreign Key on SIAE_Event.TaxPackageId
1) Add Foreign Key on SIAE_PerformanceCapacity.SeatCategoryId
2) Script created in order to update the field  BattelliActStatus of the table SIAE_Event
</REASON><TABLENAMES>SIAE_Event=EventId
SIAE_PerformanceCapacity=PerformanceId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_SIAE_Event_TaxPackageId')
BEGIN
  ALTER TABLE SIAE_Event
  ADD CONSTRAINT FK_SIAE_Event_TaxPackageId FOREIGN KEY([TaxPackageId]) 
  REFERENCES [CNF_TaxPackage] ([TaxPackageId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_SIAE_PerformanceCapacity_SeatCategoryId')
BEGIN
  ALTER TABLE SIAE_PerformanceCapacity
  ADD CONSTRAINT FK_SIAE_PerformanceCapacity_SeatCategoryId FOREIGN KEY([SeatCategoryId]) 
  REFERENCES [CNF_SeatCategory] ([SeatCategoryId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>UPDATE 
	SIAE_Event
SET 
	BattelliActStatus = 3
WHERE EventId in (
	SELECT 
		S_EV.EventId
	FROM 
		SIAE_Event AS S_EV with(nolock)
		inner join CNF_Event AS EV with(nolock) on (S_EV.EventId = EV.EventId)
	WHERE
		GETDATE() &lt;= CONVERT(Date, EV.EndDate, 120) AND
		EV.Status = 1 AND
		S_EV.BattelliActStatus = 0 AND
		NOT(S_EV.TipoGenere in (7,8,33,41,42,70,71,72,90,97,98,99) )
	)</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dchen</ADDEDBY><SQLVERSION>3298</SQLVERSION><RMTRACKLINK>IDBOS-2839</RMTRACKLINK><REASON>IDBOS-2839 and IDBOS-2840
Adding new field to control type of entitlement in Data_SaleItemRedeem.</REASON><TABLENAMES>DATA_SaleItemRedeem=SaleItemRedeemId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
          WHERE Name = N'EntitlementType' 
          AND OBJECT_ID = OBJECT_ID(N'DATA_SaleItemRedeem'))
BEGIN
  ALTER TABLE DATA_SaleItemRedeem
  ADD [EntitlementType] smallint NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fdipalma</ADDEDBY><SQLVERSION>3297</SQLVERSION><RMTRACKLINK>IDBOS-3785</RMTRACKLINK><REASON>Expo Indexes and with(NoLock)</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT object_id
               FROM sys.indexes
               WHERE Name = 'Idx_DATA_SaleItemRedeem_SaleItemId')
BEGIN
	CREATE NONCLUSTERED INDEX [Idx_DATA_SaleItemRedeem_SaleItemId] ON [dbo].[DATA_SaleItemRedeem]
	(
		[SaleItemId] DESC
	)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT object_id
               FROM sys.indexes
               WHERE Name = 'Idx_DATA_Payment_PaymentStatus_TransactionId')
BEGIN
	CREATE NONCLUSTERED INDEX [Idx_DATA_Payment_PaymentStatus_TransactionId] ON [dbo].[DATA_Payment]
	(
		[PaymentStatus] DESC,
		[TransactionId] DESC
	)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT object_id
               FROM sys.indexes
               WHERE Name = 'Idx_DATA_Payment_TransactionId')
BEGIN
	CREATE NONCLUSTERED INDEX [Idx_DATA_Payment_TransactionId] ON [dbo].[DATA_Payment]
	(
		[TransactionId] DESC
	)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT object_id
               FROM sys.indexes
               WHERE Name = 'Idx_DATA_Payment_TransactionId_PaymentType')
BEGIN
	CREATE NONCLUSTERED INDEX [Idx_DATA_Payment_TransactionId_PaymentType] ON [dbo].[DATA_Payment]
	(
		[TransactionId] DESC,
		[PaymentType] DESC
	)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT object_id
               FROM sys.indexes
               WHERE Name = 'Idx_DATA_Transaction_BoxId')
BEGIN
	CREATE NONCLUSTERED INDEX [Idx_DATA_Transaction_BoxId] ON [dbo].[DATA_Transaction]
	(
		[BoxId] DESC
	)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT object_id
               FROM sys.indexes
               WHERE Name = 'Idx_DATA_Payment_PaymentStatus_TransactionId_PaymentType')
BEGIN
	CREATE NONCLUSTERED INDEX [Idx_DATA_Payment_PaymentStatus_TransactionId_PaymentType] ON [dbo].[DATA_Payment]
	(
		[PaymentStatus] DESC,
		[TransactionId] DESC,
		[PaymentType] DESC
	)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT object_id
               FROM sys.indexes
               WHERE Name = 'Idx_DATA_SaleItem_TicketId')
BEGIN
	CREATE NONCLUSTERED INDEX [Idx_DATA_SaleItem_TicketId] ON [dbo].[DATA_SaleItem]
	(
		[TicketId] DESC
	)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT object_id
               FROM sys.indexes
               WHERE Name = 'Idx_CNF_MatrixCell_MatrixSheetId_Enabled')
BEGIN
	CREATE NONCLUSTERED INDEX [Idx_CNF_MatrixCell_MatrixSheetId_Enabled] ON [dbo].[CNF_MatrixCell]
	(
		[MatrixSheetId] DESC,
		[Enabled] DESC
	)
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>lfornaroli</ADDEDBY><SQLVERSION>3296</SQLVERSION><RMTRACKLINK>IDBOS-2819</RMTRACKLINK><REASON>[0] add field RenewType
[1] copy values from CNF_MatrixCell
[2] mark RenewType as notNull
[3] add field RenewDayLimit
[4] add field RenewAgeLimitMin
[5] add field RenewAgeLimitMax</REASON><TABLENAMES>CNF_MatrixCell_Renew=RenewId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
          WHERE Name = N'RenewType' 
          AND OBJECT_ID = OBJECT_ID(N'CNF_MatrixCell_Renew'))
BEGIN
  ALTER TABLE CNF_MatrixCell_Renew
  ADD [RenewType] smallint NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT * FROM sys.columns
          WHERE Name = N'RenewType' 
          AND OBJECT_ID = OBJECT_ID(N'CNF_MatrixCell_Renew'))
BEGIN
  UPDATE MCR
  SET 
    MCR.RenewType = MC.RenewType
  FROM CNF_MatrixCell_Renew MCR with(nolock) 
       INNER JOIN CNF_MatrixCell MC with(nolock) ON MC.MatrixCellId = MCR.MatrixCellId
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT * FROM sys.columns
          WHERE Name = N'RenewType' 
          AND OBJECT_ID = OBJECT_ID(N'CNF_MatrixCell_Renew'))
BEGIN
  ALTER TABLE CNF_MatrixCell_Renew
  alter column [RenewType] smallint NOT NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT> IF NOT EXISTS(SELECT * FROM sys.columns
          WHERE Name = N'RenewDayLimit' 
          AND OBJECT_ID = OBJECT_ID(N'CNF_MatrixCell_Renew'))
BEGIN
  ALTER TABLE CNF_MatrixCell_Renew
  ADD RenewDayLimit integer NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>  IF NOT EXISTS(SELECT * FROM sys.columns
          WHERE Name = N'RenewAgeLimitMin' 
          AND OBJECT_ID = OBJECT_ID(N'CNF_MatrixCell_Renew'))
BEGIN
  ALTER TABLE CNF_MatrixCell_Renew
  ADD RenewAgeLimitMin integer NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
          WHERE Name = N'RenewAgeLimitMax' 
          AND OBJECT_ID = OBJECT_ID(N'CNF_MatrixCell_Renew'))
BEGIN
  ALTER TABLE CNF_MatrixCell_Renew
  ADD RenewAgeLimitMax integer NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fdipalma</ADDEDBY><SQLVERSION>3295</SQLVERSION><RMTRACKLINK>IDBOS-3651</RMTRACKLINK><REASON>BOS - Production - High Database Usage</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT object_id
               FROM sys.indexes
               WHERE Name = 'idx_CNF_Performance_AptLoadData')
BEGIN
	CREATE NONCLUSTERED INDEX [idx_CNF_Performance_AptLoadData]
	ON [dbo].[CNF_Performance] ([Status],[OpeningTime],[ClosingTime])
	INCLUDE ([EventId],[PerformanceAK],[PerfDateTime],[AccessConfigurationId],[TimeOpening],[TimeLimit],[PerformanceEnd],[MoneyCardId],[MoneyCardCost],[PerformanceCode],[PerformanceName])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT object_id
           FROM sys.indexes
           WHERE Name = 'idx_CNF_Performance_AptLoadData')
BEGIN
	ALTER INDEX idx_CNF_Performance_AptLoadData ON CNF_Performance
	REBUILD;
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT object_id
               FROM sys.indexes
               WHERE Name = 'idx_CNF_Performance_AptLoadData_2')
BEGIN
	CREATE NONCLUSTERED INDEX [idx_CNF_Performance_AptLoadData_2]
	ON [dbo].[CNF_Performance] ([AccessConfigurationId],[OpeningTime],[ClosingTime])
	INCLUDE ([EventId],[PerformanceAK],[PerfDateTime],[Status],[TimeOpening],[TimeLimit],[PerformanceEnd],[MoneyCardId],[MoneyCardCost],[PerformanceCode],[PerformanceName])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT object_id
           FROM sys.indexes
           WHERE Name = 'idx_CNF_Performance_AptLoadData_2')
BEGIN
	ALTER INDEX idx_CNF_Performance_AptLoadData_2 ON CNF_Performance
	REBUILD;
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>pchen</ADDEDBY><SQLVERSION>3294</SQLVERSION><RMTRACKLINK>IDBOS-2827</RMTRACKLINK><REASON>increase the size of ItemCodeAdditional to 100 in CNF_MaskTableItem</REASON><TABLENAMES>CNF_MaskTableItem=MaskTableItemId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>alter table CNF_MaskTableItem
  alter column ItemCodeAdditional NVarChar(100) null</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fdipalma</ADDEDBY><SQLVERSION>3293</SQLVERSION><RMTRACKLINK>IDBOS-3552</RMTRACKLINK><REASON>BOS - Group ticket scan in offline mode</REASON><TABLENAMES>OFF_WhiteListTck=WhiteListTckId
OFF_TicketUsage=TicketUsageId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
          WHERE Name = N'PeopleCount' 
          AND OBJECT_ID = OBJECT_ID(N'OFF_WhiteListTck'))
BEGIN
  ALTER TABLE OFF_WhiteListTck
  ADD [PeopleCount] [int] DEFAULT 0 NOT NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
          WHERE Name = N'UsedPeopleCount' 
          AND OBJECT_ID = OBJECT_ID(N'OFF_WhiteListTck'))
BEGIN
  ALTER TABLE OFF_WhiteListTck
  ADD [UsedPeopleCount] [int] DEFAULT 0 NOT NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
          WHERE Name = N'UsedPeopleCount' 
          AND OBJECT_ID = OBJECT_ID(N'OFF_TicketUsage'))
BEGIN
  ALTER TABLE OFF_TicketUsage
  ADD [UsedPeopleCount] [int] DEFAULT 0 NOT NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT 1 FROM sys.procedures 
          WHERE Name = 'otn_sp_WhiteList_Import')
	DROP PROCEDURE otn_sp_WhiteList_Import</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>CREATE procedure [dbo].[otn_sp_WhiteList_Import]
	@IdentifierCode varchar(400),
    @IdentifierType smallint,
	@VoidType smallint,
	@MatrixCellId int,
	@ValidityXML ntext,
	@TicketId int,
	@ActiveFrom datetime,
	@ActiveTo datetime,
	@PeopleCount int,
	@UsedPeopleCount int
as
begin
	DECLARE @c int

	select @c = COUNT(IdentifierCode) from OFF_WhiteListTck where (IdentifierCode = @IdentifierCode) and (TicketId = @TicketId)

	IF (@c = 0)
	begin
		insert into OFF_WhiteListTck (
		IdentifierCode,
		IdentifierType,
		VoidType,
		MatrixCellId,
		ValidityXML,
		TicketId,
		ActiveFrom,
		ActiveTo,
		PeopleCount,
		UsedPeopleCount
		) values (
		@IdentifierCode,
		@IdentifierType,
		@VoidType,
		@MatrixCellId,
		@ValidityXML,
		@TicketId,
		@ActiveFrom,
		@ActiveTo,
		@PeopleCount,
		@UsedPeopleCount
		)
	end
	else
	begin
		update OFF_WhiteListTck
		set
		IdentifierType=@IdentifierType,
		VoidType=@VoidType,
		MatrixCellId=@MatrixCellId,
		ValidityXML=@ValidityXML,
		ActiveFrom=@ActiveFrom,
		ActiveTo=@ActiveTo,
		PeopleCount=@PeopleCount,
		UsedPeopleCount=@UsedPeopleCount
		where
		(IdentifierCode=@IdentifierCode) and
		(TicketId=@TicketId)
	end

end</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fesposito</ADDEDBY><SQLVERSION>3292</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>Error in releasing</REASON><TABLENAMES>DATA_SaleItem2Gift=SaleItem2GiftId</TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>3291</SQLVERSION><RMTRACKLINK>IDBOS-3519</RMTRACKLINK><REASON>New field on DATA_Transaction: Invoice</REASON><TABLENAMES>DATA_Transaction=TransactionId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS ( SELECT * FROM sys.columns
               WHERE Name = N'Invoice'
               AND OBJECT_ID = OBJECT_ID(N'DATA_Transaction'))
BEGIN
   ALTER Table DATA_Transaction
   ADD Invoice Smallint NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>lfornaroli</ADDEDBY><SQLVERSION>3290</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>DATA_SaleItem2Gift
[0] create table
[1] add FK on  CharityId
[2] add FK on SaleItemId
[3] add FK on AccountId</REASON><TABLENAMES>DATA_SaleItem2Gift=SaleItem2GiftId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND TABLE_NAME = 'DATA_SaleItem2Gift')
BEGIN
Create table DATA_SaleItem2Gift
(
	SaleItem2GiftId Integer IDENTITY(1,1) NOT NULL,
	CharityId int NOT NULL,
        SaleItemId int NOT NULL,
        AccountId int NULL,
        Amount float not null,
	Status smallInt Not null,
	InsertDateTime dateTime not null
	

	Primary Key (SaleItem2GiftId)
) 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>ALTER TABLE DATA_SaleItem2Gift  WITH CHECK ADD FOREIGN KEY(CharityId)
REFERENCES CNF_Charity (CharityId)</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>ALTER TABLE DATA_SaleItem2Gift  WITH CHECK ADD FOREIGN KEY(SaleItemId)
REFERENCES DATA_SaleItem (SaleItemId)</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>ALTER TABLE DATA_SaleItem2Gift  WITH CHECK ADD FOREIGN KEY(AccountId)
REFERENCES DATA_Account (AccountId)</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>3289</SQLVERSION><RMTRACKLINK>91085</RMTRACKLINK><REASON>Add new column to the CNF_UpSell_Rule in order to establish the relationship between ObjectFrom and ObjectTo in case of POS\TVM upsell type

[0] Add column ReferenceKey
[1] Evaluate properly the ReferenceKey only for the POS\TVM UpSells</REASON><TABLENAMES>CNF_UpSell_Rule=UpSellRuleId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'ReferenceKey' 
                      AND OBJECT_ID = OBJECT_ID(N'CNF_UpSell_Rule'))
BEGIN
  ALTER TABLE CNF_UpSell_Rule
  ADD ReferenceKey Integer NOT NULL DEFAULT '0';     
END </SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>declare @RefKey as int;
set @RefKey = 0;
declare @CurrUpSellId as int;
declare @OldUpSellId as int;
set @OldUpSellId = 0;
declare @Num as int;
declare @UpSellRuleId as int;

declare ItemsCur CURSOR FOR
	select UpSellRuleId, UpSellId, ROW_NUMBER() OVER (ORDER BY UpSellRuleId) AS rownum
	from CNF_UpSell_Rule
	where UpSellId in (
		select UpSellId
		from CNF_UpSell
		where UpSellType = 0)
	order by UpSellId, UpSellRuleId, RuleType

open ItemsCur
fetch next from ItemsCur into @UpSellRuleId, @CurrUpSellId, @Num

while (@@FETCH_STATUS=0)
begin
	if @OldUpSellId &lt;&gt; @CurrUpSellId
	begin
		set @OldUpSellId = @CurrUpSellId
		set @RefKey = 0
	end

	set @RefKey = @RefKey +
		case when @Num % 2 = 0 
			then 0
			else 1
		end 

	update CNF_UpSell_Rule set ReferenceKey = @RefKey where UpSellRuleId = @UpSellRuleId
	fetch next from ItemsCur into @UpSellRuleId, @CurrUpSellId, @Num
end

close ItemsCur
deallocate ItemsCur</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fdipalma</ADDEDBY><SQLVERSION>3288</SQLVERSION><RMTRACKLINK>IDBOS-3410</RMTRACKLINK><REASON>BOS - Offline - Scan Expired Ticket</REASON><TABLENAMES>OFF_WhiteListTck=WhiteListTckId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
          WHERE Name = N'ActiveFrom' 
          AND OBJECT_ID = OBJECT_ID(N'OFF_WhiteListTck'))
BEGIN
  ALTER TABLE OFF_WhiteListTck
  ADD [ActiveFrom] [datetime] NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
          WHERE Name = N'ActiveTo' 
          AND OBJECT_ID = OBJECT_ID(N'OFF_WhiteListTck'))
BEGIN
  ALTER TABLE OFF_WhiteListTck
  ADD [ActiveTo] [datetime] NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT 1 FROM sys.procedures 
          WHERE Name = 'otn_sp_WhiteList_Import')
	DROP PROCEDURE otn_sp_WhiteList_Import</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>CREATE procedure [dbo].[otn_sp_WhiteList_Import]
	@IdentifierCode varchar(400),
    @IdentifierType smallint,
	@VoidType smallint,
	@MatrixCellId int,
	@ValidityXML ntext,
	@TicketId int,
	@ActiveFrom datetime,
	@ActiveTo datetime
as
begin
	DECLARE @c int

	select @c = COUNT(IdentifierCode) from OFF_WhiteListTck where (IdentifierCode = @IdentifierCode) and (TicketId = @TicketId)

	IF (@c = 0)
	begin
		insert into OFF_WhiteListTck (
		IdentifierCode,
		IdentifierType,
		VoidType,
		MatrixCellId,
		ValidityXML,
		TicketId,
		ActiveFrom,
		ActiveTo
		) values (
		@IdentifierCode,
		@IdentifierType,
		@VoidType,
		@MatrixCellId,
		@ValidityXML,
		@TicketId,
		@ActiveFrom,
		@ActiveTo
		)
	end
	else
	begin
		update OFF_WhiteListTck
		set
		IdentifierType=@IdentifierType,
		VoidType=@VoidType,
		MatrixCellId=@MatrixCellId,
		ValidityXML=@ValidityXML,
		ActiveFrom=@ActiveFrom,
		ActiveTo=@ActiveTo
		where
		(IdentifierCode=@IdentifierCode) and
		(TicketId=@TicketId)
	end

end
</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>lfornaroli</ADDEDBY><SQLVERSION>3287</SQLVERSION><RMTRACKLINK>IDBOS-2862, IDBOS-2861, IDBOS-2860  </RMTRACKLINK><REASON>[0] add DATA_AccountGIftAid
[1] add FK on DATA_Account

[2] add field AllowGiftAid null
[3] set field value
[4] change AllowGiftAid to not null

[5] add new table CNF_Charity</REASON><TABLENAMES>DATA_AccountGiftAid=AccountId
CNF_PaymentMethod=PaymentMethodId
CNF_Charity=CharityId
</TABLENAMES><SQLSCRIPTLIST><SCRIPT> IF NOT EXISTS (SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND TABLE_NAME = 'DATA_AccountGiftAid')
BEGIN
Create table DATA_AccountGiftAid
(
	AccountId Integer  NOT NULL,
	AcceptanceStartDate DateTime NOT NULL,
	AcceptanceEndDate DateTime NOT NULL,
	DeclarationStartDate DateTime NOT NULL,
	DeclarationEndDate DateTime NOT NULL


	Primary Key (AccountId)
) 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>ALTER TABLE DATA_AccountGiftAid  WITH CHECK ADD FOREIGN KEY(AccountId)
REFERENCES DATA_Account (AccountId)    </SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>ALTER TABLE CNF_PaymentMethod
  ADD AllowGiftAid smallint null</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>update CNF_PaymentMethod set AllowGiftAid = 0    </SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>alter table CNF_PaymentMethod
  alter column AllowGiftAid smallint not null</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND TABLE_NAME = 'CNF_Charity')
BEGIN
Create table CNF_Charity
(
	CharityId Integer IDENTITY(1,1) NOT NULL,
	CharityAK nvarChar(32) NOT NULL,
	Enabled smallInt Not null,
	CharityCode nvarChar(10) not null,
	CharityName nvarChar(50) not null,
	CharityDescription nvarChar(100) not null,
	CharityRate float

	Primary Key (CharityId)
) 
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>vkoukin</ADDEDBY><SQLVERSION>3286</SQLVERSION><RMTRACKLINK>IDBOS-2939</RMTRACKLINK><REASON>delete sp that uses OPENJSON:
drop procedure WeatherInsertJson
drop procedure WeatherInsert</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT 1 FROM sys.procedures 
          WHERE Name = 'WeatherInsertJson')
		  BEGIN
		    DROP PROCEDURE WeatherInsertJson
		  END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT 1 FROM sys.procedures 
          WHERE Name = 'WeatherInsert')
		  BEGIN
		    DROP PROCEDURE WeatherInsert
		  END
</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>vkoukin</ADDEDBY><SQLVERSION>3285</SQLVERSION><RMTRACKLINK>IDBOS-2939</RMTRACKLINK><REASON>Location NVarChar(100) field added
Stored procedure for bulk json insert</REASON><TABLENAMES>DATA_Weather=WeatherID</TABLENAMES><SQLSCRIPTLIST><SCRIPT>           IF NOT EXISTS( SELECT * FROM sys.columns
                      WHERE Name = N'Location' 
                      AND OBJECT_ID = OBJECT_ID(N'Data_weather'))
BEGIN
  ALTER TABLE DATA_Weather 
  ADD Location nvarchar(100) NULL;     
END 
</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dchen</ADDEDBY><SQLVERSION>3284</SQLVERSION><RMTRACKLINK>IDBOS-2580</RMTRACKLINK><REASON>IDBOS-2580 add Ticket/product selection to Donations </REASON><TABLENAMES>CNF_Donation=DonationId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'UseProductList' 
                      AND OBJECT_ID = OBJECT_ID(N'CNF_Donation'))
BEGIN
  ALTER TABLE CNF_Donation 
  ADD UseProductList int NULL;     
END </SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3283</SQLVERSION><RMTRACKLINK>IDBOS-2921</RMTRACKLINK><REASON>0 ) New ApprovalStatus</REASON><TABLENAMES>DATA_Reservation=SaleId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'ApprovalStatus' 
                      AND OBJECT_ID = OBJECT_ID(N'DATA_Reservation'))
BEGIN
  ALTER TABLE DATA_Reservation 
  ADD ApprovalStatus smallint NULL;     
END 
</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>3282</SQLVERSION><RMTRACKLINK>IDBOS-3239</RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT> IF NOT EXISTS (SELECT * 
                FROM sys.indexes 
            WHERE name='Idx_DATA_ShopCartItemLimit_SaleID' AND object_id = OBJECT_ID('DATA_ShopCartItemLimit')
			)
BEGIN
 	CREATE NONCLUSTERED INDEX [Idx_DATA_ShopCartItemLimit_SaleID] ON [dbo].[DATA_ShopCartItemLimit]
	(
		[SaleID] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
end</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3281</SQLVERSION><RMTRACKLINK>IDBOS-2921</RMTRACKLINK><REASON>0 ) New MaxDailyResDelete
1 ) New MaxDailyTicketsDelete
2 ) New NumDaysAfterOrderCreation
3 ) New NumDaysBeforeEvent
4 ) New ResDelApprovalUserId</REASON><TABLENAMES>DATA_AccountFinancial=AccountId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'MaxDailyResDelete' 
                      AND OBJECT_ID = OBJECT_ID(N'DATA_AccountFinancial'))
BEGIN
  ALTER TABLE DATA_AccountFinancial 
  ADD MaxDailyResDelete int NULL;     
END 
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'MaxDailyTicketsDelete' 
                      AND OBJECT_ID = OBJECT_ID(N'DATA_AccountFinancial'))
BEGIN
  ALTER TABLE DATA_AccountFinancial 
  ADD MaxDailyTicketsDelete int NULL;     
END </SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'NumDaysAfterOrderCreation' 
                      AND OBJECT_ID = OBJECT_ID(N'DATA_AccountFinancial'))
BEGIN
  ALTER TABLE DATA_AccountFinancial 
  ADD NumDaysAfterOrderCreation int NULL;     
END </SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'NumDaysBeforeEvent' 
                      AND OBJECT_ID = OBJECT_ID(N'DATA_AccountFinancial'))
BEGIN
  ALTER TABLE DATA_AccountFinancial 
  ADD NumDaysBeforeEvent int NULL;     
END </SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'ResDelApprovalUserId' 
                      AND OBJECT_ID = OBJECT_ID(N'DATA_AccountFinancial'))
BEGIN
  ALTER TABLE DATA_AccountFinancial 
  ADD ResDelApprovalUserId int NULL;     
END </SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3280</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>************** SIAE RESERVED **************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3279</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>************** SIAE RESERVED **************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3278</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>************** SIAE RESERVED **************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3277</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>************** SIAE RESERVED **************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3276</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>************** SIAE RESERVED **************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3275</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>************** SIAE RESERVED **************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3274</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>************** SIAE RESERVED **************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3273</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>************** SIAE RESERVED **************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3272</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>************** SIAE RESERVED **************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3271</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>************** SIAE RESERVED **************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3270</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>************** SIAE RESERVED **************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3269</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>************** SIAE RESERVED **************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3268</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>************** SIAE RESERVED **************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3267</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>************** SIAE RESERVED **************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3266</SQLVERSION><RMTRACKLINK>IDBOS-3311</RMTRACKLINK><REASON>0) Script created in order to populate the new Table SIAE_PeformanceCapacity reading data from SIAE_CATEGORY, CNF_PERFORMANCE and CNF_SEATCATEGORY</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>DELETE SIAE_PerformanceCapacity

declare @SeatCategoryId		integer;
declare @Capienza		integer;
declare @EventId		integer;
declare @PerformanceId		integer;
declare @SearchSeatCategoryId	integer;
declare @SearchAttributeId      integer;

DECLARE SiaeCategoryCursor CURSOR FOR
	SELECT DISTINCT
		EventId,
		SeatCategoryId,
		Max(Capienza) As Capienza
	FROM SIAE_Category
	WHERE CAPIENZA &gt; 0
	GROUP BY EventId,SeatCategoryId
	ORDER BY EventId,SeatCategoryId,Capienza

  open SiaeCategoryCursor;

  fetch SiaeCategoryCursor into @EventId,@SeatCategoryId,@Capienza;
  WHILE @@FETCH_STATUS = 0 -- Loop on SIAE_Category Table
  begin
	DECLARE PerformanceCursor CURSOR FOR
		SELECT Performanceid
		FROM CNF_Performance with(nolock)
		WHERE EventId = @EventId
	
	open PerformanceCursor; 

	fetch PerformanceCursor into @PerformanceId; 
	WHILE @@FETCH_STATUS = 0 -- Loop on CNF_Performance Table using EventId recovered from SIAE_Category
	begin
		-- Searching a matching record in the CNF_SeatCategory
		-- If we found a record we can update the SIA_PerformanceCategory with all data..
		SET @SearchSeatCategoryId = NULL;
		
		SELECT 
			@SearchSeatCategoryId = SC.SeatCategoryId,
			@SearchAttributeId = SC.AttributeId
		FROM
			CNF_SeatCategory as SC with(nolock)
		WHERE
			SC.PerformanceId = @PerformanceId AND Temp_SeatCategoryId = @SeatCategoryId

		IF @SearchSeatCategoryId IS NOT NULL
		begin
			INSERT INTO [dbo].[SIAE_PerformanceCapacity]
					   ([PerformanceId]
					   ,[AttributeId]
					   ,[Capienza]
					   ,[SeatCategoryId])
				 VALUES
					   (@PerformanceId,
					    @SearchAttributeId,
					    @Capienza,
					    @SearchSeatCategoryId);
		end;
		
		fetch PerformanceCursor into @PerformanceId;
	end

	CLOSE PerformanceCursor;
	DEALLOCATE PerformanceCursor;

	fetch SiaeCategoryCursor into @EventId,@SeatCategoryId,@Capienza;
  end

CLOSE SiaeCategoryCursor;
DEALLOCATE SiaeCategoryCursor;</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3265</SQLVERSION><RMTRACKLINK>IDBOS-3311</RMTRACKLINK><REASON>0) Script created in order to populate Column TaxPackageId in table  SIAE_Event</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>DECLARE @SIAEGeneri TABLE (ftipogenere integer, fvalue float);
-- populating temporary table
insert into @SIAEGeneri values(77,10),(78,10),(53,10),(70,22),(56,10),(1,10),(45,10),(41,0),(71,0)

-- using cursor in order to loop in temporary table and update siae_event
declare @tipogenere integer
declare @Iva float

  DECLARE cur CURSOR FOR
	SELECT distinct(fvalue) from @SIAEGeneri

  open cur;

  fetch cur into @Iva;
  WHILE @@FETCH_STATUS = 0
  begin
	  -- Standard Update
		UPDATE 
			SIAE_EVENT
		SET 
			TaxPackageId = (
				SELECT
					TP.TaxPackageId
				FROM	
					CNF_TaxPackage AS TP With(nolock)
					inner join CNF_Tax2Package As T2P with(nolock) on (TP.TaxPackageId = T2p.TaxPackageId)
					inner join (
					  SELECT TOP(1) 
							Taxid
					  FROM CNF_Tax with(nolock) WHERE TaxValue = @Iva
					)  AS TA on (T2P.TaxId = ta.TaxId)
			)
		WHERE
			TipoGenere in ( SELECT ftipogenere FROM @SIAEGeneri WHERE fValue = @Iva)
	fetch cur into @Iva;
  end

  
  close cur;
  deallocate cur;</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3264</SQLVERSION><RMTRACKLINK>IDBOS-3311</RMTRACKLINK><REASON>0) Added Column SeatCategoryId to SIAE_PerformanceCapacity</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
              WHERE Name = N'SeatCategoryId' 
              AND OBJECT_ID = OBJECT_ID(N'SIAE_PerformanceCapacity'))
BEGIN
  ALTER TABLE SIAE_PerformanceCapacity
  ADD SeatCategoryId Integer 
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3263</SQLVERSION><RMTRACKLINK>IDBOS-3311</RMTRACKLINK><REASON>This patch has been  maden for a modify on Case-Studio with a fake  script.</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>SELECT 1</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3262</SQLVERSION><RMTRACKLINK>IDBOS-3311</RMTRACKLINK><REASON>0) Create Table SIAE_PerformanceCapacity
1) Add Foreign Key on field PerformanceId
2) Add Foreign Key on field AttributeId</REASON><TABLENAMES>SIAE_PerformanceCapacity=PerformanceId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND TABLE_NAME = 'SIAE_PerformanceCapacity')
BEGIN
Create table SIAE_PerformanceCapacity
(
	[PerformanceId] Integer NOT NULL,
	[AttributeId] Integer NOT NULL,
	[Capienza] Integer NULL,
	Primary Key ([PerformanceId],[AttributeId])
) 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_SIAE_SIAE_PerformanceCapacity_PerformanceId')
BEGIN
  ALTER TABLE SIAE_PerformanceCapacity
  ADD CONSTRAINT FK_SIAE_SIAE_PerformanceCapacity_PerformanceId FOREIGN KEY([PerformanceId]) 
  REFERENCES [CNF_Performance] ([PerformanceId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_SIAE_SIAE_PerformanceCapacity_AttributeId')
BEGIN
  ALTER TABLE SIAE_PerformanceCapacity
  ADD CONSTRAINT FK_SIAE_SIAE_PerformanceCapacity_AttributeId FOREIGN KEY([AttributeId]) 
  REFERENCES [CNF_Attribute] ([AttributeId])
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3261</SQLVERSION><RMTRACKLINK>IDBOS-3311</RMTRACKLINK><REASON>0) Added Column TaxPackageId to SIAE_Event table
1) Added in Tables Modified SIAE_SiaeLog=SiaeLogId in order to recreate Store Procedure ( for a previous forgetfulness ).</REASON><TABLENAMES>SIAE_Event=EventId
SIAE_SiaeLog=SiaeLogId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
              WHERE Name = N'TaxPackageId' 
              AND OBJECT_ID = OBJECT_ID(N'SIAE_Event'))
BEGIN
  ALTER TABLE SIAE_Event
  ADD TaxPackageId Integer 
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>3260</SQLVERSION><RMTRACKLINK>IDBOS-1885</RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.objects WHERE type = 'P' AND name = 'otn_sp_HIL_CreateHILTrigger')
begin
	exec otn_sp_HIL_CreateHILTrigger 'CNF_EnvelopeCapacity'
end</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>vkoukin</ADDEDBY><SQLVERSION>3259</SQLVERSION><RMTRACKLINK>IDBOS-2939</RMTRACKLINK><REASON>Historical flag Char(1) added</REASON><TABLENAMES>DATA_Weather=WeatherID</TABLENAMES><SQLSCRIPTLIST><SCRIPT>           IF NOT EXISTS( SELECT * FROM sys.columns
                      WHERE Name = N'Historical' 
                      AND OBJECT_ID = OBJECT_ID(N'Data_weather'))
BEGIN
  ALTER TABLE DATA_Weather 
  ADD Historical char(1) NULL;     
END 
</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dchen</ADDEDBY><SQLVERSION>3258</SQLVERSION><RMTRACKLINK>IDBOS-3009</RMTRACKLINK><REASON>change driver description name.</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>update cnf_driver
   set Description = 'Opera Reservation Import'
 where DriverAK ='TDrvJobBahaMarOperaImprot'  </SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>3257</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                FROM sys.indexes 
            WHERE name='Idx_DATA_ShopCartItemLimit' AND object_id = OBJECT_ID('DATA_ShopCartItemLimit')
			)
BEGIN
	CREATE INDEX Idx_DATA_ShopCartItemLimit on DATA_ShopCartItemLimit ([SHOPCARTGUID])	
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                FROM sys.indexes 
            WHERE name='Idx_DATA_AccountLimit_SaleID' AND object_id = OBJECT_ID('DATA_AccountLimit')
			)
BEGIN
	CREATE INDEX Idx_DATA_AccountLimit_SaleID on DATA_AccountLimit ([SaleId], [SaleItemId], [PerformanceId])	
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT *  
				FROM information_schema.table_constraints  
				WHERE constraint_type = 'PRIMARY KEY'   
				AND table_name = 'DATA_AccountLimit')
BEGIN
	ALTER TABLE DATA_AccountLimit
	ADD PRIMARY KEY (AccountLimitDataId);
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>3256</SQLVERSION><RMTRACKLINK>IDBOS-1885</RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>exec  otn_sp_HIL_CreateHILTrigger  'CNF_EnvelopeCapacity'</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>3255</SQLVERSION><RMTRACKLINK>IDBOS-2850</RMTRACKLINK><REASON>New column on CNF_Seat: LastStatus</REASON><TABLENAMES>CNF_Seat=SeatId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'LastStatus' 
                      AND OBJECT_ID = OBJECT_ID(N'CNF_Seat'))
BEGIN
  ALTER TABLE CNF_Seat 
  ADD LastStatus SmallInt NULL;     
END </SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>3254</SQLVERSION><RMTRACKLINK>IDBOS-2850</RMTRACKLINK><REASON>New field for CNF_Performance: NotTransferrable</REASON><TABLENAMES>CNF_Performance=PerformanceId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'NotTransferrable' 
                      AND OBJECT_ID = OBJECT_ID(N'CNF_Performance'))
BEGIN
  ALTER TABLE CNF_Performance 
  ADD NotTransferrable SmallInt NULL;     
END </SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>3253</SQLVERSION><RMTRACKLINK>idbos-3092</RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.objects WHERE [name] = N'data_sale_SalesRestriction' AND [type] = 'TR')
BEGIN
      DROP TRIGGER [dbo].[data_sale_SalesRestriction];
END;</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>ecandido</ADDEDBY><SQLVERSION>3252</SQLVERSION><RMTRACKLINK>IDBOS-369</RMTRACKLINK><REASON>Change Column Names for UserId and WorkstationId in Table CNF_PaymentMethod2MatrixCell</REASON><TABLENAMES>CNF_PaymentMethod2MatrixCell=PaymentMethod2MatricCellId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT *
          FROM   INFORMATION_SCHEMA.COLUMNS
          WHERE  TABLE_NAME = 'CNF_PaymentMethod2MatrixCell'
                 AND COLUMN_NAME = 'UserId')
BEGIN
  exec sp_rename 'CNF_PaymentMethod2MatrixCell.UserId', 'Last_UserId_Log', 'COLUMN';
END

IF EXISTS(SELECT *
          FROM   INFORMATION_SCHEMA.COLUMNS
          WHERE  TABLE_NAME = 'CNF_PaymentMethod2MatrixCell'
                 AND COLUMN_NAME = 'WorkstationId')
BEGIN
  exec sp_rename 'CNF_PaymentMethod2MatrixCell.WorkstationId', 'Last_WorkstationId_Log', 'COLUMN';
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>3251</SQLVERSION><RMTRACKLINK>IDBOS-3092</RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.objects WHERE [name] = N'data_sale_SalesRestriction' AND [type] = 'TR')
BEGIN
      DROP TRIGGER [dbo].[data_sale_SalesRestriction];
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>Create trigger [dbo].[data_sale_SalesRestriction] on [dbo].[DATA_Sale] FOR update
	 as
begin
	SET NOCOUNT ON;
    IF UPDATE(Approved) or Update(StatusCode)
    BEGIN

		Declare @NumberOfRestrictions Int = 0

		select @NumberOfRestrictions = Count(*)
		  from CNF_AccountRestriction
		 Where Enabled = 1

		if @NumberOfRestrictions &gt; 0
		BEGIN
			DECLARE @INS_SaleID int
			DECLARE @status int = 0 
			DECLARE @DR_status int

			DECLARE @RestrictionType int	
			
			DECLARE @CheckforRestraintOnly int = 0

			SELECT @status=1, @INS_SaleID = i.Saleid 
					FROM inserted i
						JOIN deleted d
								 ON i.SaleID = d.SaleID
								 AND i.statuscode = 1

			if @status = 0 
			begin
				SELECT @DR_status = CASE WHEN i.StatusCode = 2 then  1
										 else 0
									 end, 
					   @INS_SaleID = i.Saleid 
						FROM inserted i
							  JOIN deleted d
									  ON i.[SaleID] = d.[SaleID]
										 AND i.[StatusCode] &lt;&gt; d.[StatusCode]
			end


			if @status = 1
			begin
--Reservation Account
				Insert into data_shopcartitemlimit
				select  data_sale.saleid,
				        0 as B2B,
						0 as  Billing,
						ISNULL(data_reservation.accountid, ODR.AccountID) as ReservationAccountID,
						0 TicketAccountID,
						data_saleitem.Matrixcellid,
						data_saleitem.Quantity,
						case when cnf_performance.PerformanceID is not null then cnf_performance.PerformanceID
												 else 9999999
						end ,
						case when cnf_performance.Eventid is not null then cnf_performance.Eventid
												 else  9999999
						end,
						data_sale.saleid,
						data_saleitem.saleitemid,
						case when data_saleitem.Quantity &lt; 0 and (select top 1 1 
							                                        from data_accountlimit WITH(NOLOCK)
																	where data_accountlimit.saleid = ODS.Saleid
																	  and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId) = 1

															then ISNULL((select top 1 1
																			from data_transaction
																			where data_transaction.transactiontype in (17, 18, 20, 22, 40, 47)
																				and data_transaction.saleid = data_sale.saleid), 0)
							when data_saleitem.Quantity &lt; 0 and ISNULL((select top 1 1 
							                                        from data_accountlimit WITH(NOLOCK)
																	where data_accountlimit.saleid = ODS.Saleid
																	  and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId), 0) &lt;&gt; 1

															then 1
								else 0
							end as UsageCheck

				from data_sale WITH(NOLOCK)
					LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
					INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
					LEFT  JOIN data_saleitem2Performance WITH(NOLOCK)			on data_saleitem2performance.saleitemid = data_saleitem.saleitemid
					LEFT  JOIN cnf_performance WITH(NOLOCK)						on cnf_Performance.performanceid = data_saleitem2performance.performanceid
					left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
					left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

					where data_sale.saleid = @INS_SaleID

--B2B Account
				Insert into data_shopcartitemlimit
				select  data_sale.saleid,
				        ISNULL(data_reservation.B2BAccountID, ODR.B2BAccountID) as B2B,
						0 as  Billing,
						0 as ReservationAccountID,
						0 TicketAccountID,
						data_saleitem.Matrixcellid,
						data_saleitem.Quantity,
						case when cnf_performance.PerformanceID is not null then cnf_performance.PerformanceID
												 else 9999999
						end ,
						case when cnf_performance.Eventid is not null then cnf_performance.Eventid
												 else  9999999
						end,
						data_sale.saleid,
						data_saleitem.saleitemid,
						case when data_saleitem.Quantity &lt; 0 and (select top 1 1 
							                                        from data_accountlimit WITH(NOLOCK)
																	where data_accountlimit.saleid = ODS.Saleid
																	  and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId) = 1

															then ISNULL((select top 1 1
																			from data_transaction
																			where data_transaction.transactiontype in (17, 18, 20, 22, 40, 47)
																				and data_transaction.saleid = data_sale.saleid), 0)
							when data_saleitem.Quantity &lt; 0 and ISNULL((select top 1 1 
							                                        from data_accountlimit WITH(NOLOCK)
																	where data_accountlimit.saleid = ODS.Saleid
																	  and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId), 0) &lt;&gt; 1

															then 1
								else 0
							end as UsageCheck

				from data_sale WITH(NOLOCK)
					LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
					INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
					LEFT  JOIN data_saleitem2Performance WITH(NOLOCK)			on data_saleitem2performance.saleitemid = data_saleitem.saleitemid
					LEFT  JOIN cnf_performance WITH(NOLOCK)						on cnf_Performance.performanceid = data_saleitem2performance.performanceid
					left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
					left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

					where data_sale.saleid = @INS_SaleID
					  and ISNULL(data_reservation.B2BAccountID, ODR.B2BAccountID) is not null

--Billing Account
				Insert into data_shopcartitemlimit
				select  data_sale.saleid,
				        0 as B2B,
				        ISNULL(data_reservation.BillingAccountId, ODR.BillingAccountId) as BillingAccountId,
						0 as ReservationAccountID,
						0 TicketAccountID,
						data_saleitem.Matrixcellid,
						data_saleitem.Quantity,
						case when cnf_performance.PerformanceID is not null then cnf_performance.PerformanceID
												 else 9999999
						end ,
						case when cnf_performance.Eventid is not null then cnf_performance.Eventid
												 else  9999999
						end,
						data_sale.saleid,
						data_saleitem.saleitemid,
						case when data_saleitem.Quantity &lt; 0 and (select top 1 1 
							                                        from data_accountlimit WITH(NOLOCK)
																	where data_accountlimit.saleid = ODS.Saleid
																	  and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId) = 1

															then ISNULL((select top 1 1
																			from data_transaction
																			where data_transaction.transactiontype in (17, 18, 20, 22, 40, 47)
																				and data_transaction.saleid = data_sale.saleid), 0)
							when data_saleitem.Quantity &lt; 0 and ISNULL((select top 1 1 
							                                        from data_accountlimit WITH(NOLOCK)
																	where data_accountlimit.saleid = ODS.Saleid
																	  and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId), 0) &lt;&gt; 1

															then 1
								else 0
							end as UsageCheck

				from data_sale WITH(NOLOCK)
					LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
					INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
					LEFT  JOIN data_saleitem2Performance WITH(NOLOCK)			on data_saleitem2performance.saleitemid = data_saleitem.saleitemid
					LEFT  JOIN cnf_performance WITH(NOLOCK)						on cnf_Performance.performanceid = data_saleitem2performance.performanceid
					left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
					left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

					where data_sale.saleid = @INS_SaleID
					  and ISNULL(data_reservation.BillingAccountId, ODR.BillingAccountId) is not null

--Ticket Account
				Insert into data_shopcartitemlimit
				select  data_sale.saleid,
				        0 as B2B,
				        0 as BillingAccountId,
						0 as ReservationAccountID,
						data_ticket.accountid TicketAccountID,
						data_saleitem.Matrixcellid,
						case when data_ticket.ticketid is not null then case when data_saleitem.Quantity &lt; 0 then -1 else 1 end
										else data_saleitem.Quantity
									end Quantity,
						case when cnf_performance.PerformanceID is not null then cnf_performance.PerformanceID
												 else 9999999
						end ,
						case when cnf_performance.Eventid is not null then cnf_performance.Eventid
												 else  9999999
						end,
						data_sale.saleid,
						data_saleitem.saleitemid,
						case when data_saleitem.Quantity &lt; 0 and (select top 1 1 
							                                        from data_accountlimit WITH(NOLOCK)
																	where data_accountlimit.saleid = ODS.Saleid
																	  and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId) = 1

															then ISNULL((select top 1 1
																			from data_transaction
																			where data_transaction.transactiontype in (17, 18, 20, 22, 40, 47)
																				and data_transaction.saleid = data_sale.saleid), 0)
							when data_saleitem.Quantity &lt; 0 and ISNULL((select top 1 1 
							                                        from data_accountlimit WITH(NOLOCK)
																	where data_accountlimit.saleid = ODS.Saleid
																	  and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId), 0) &lt;&gt; 1

															then 1
								else 0
							end as UsageCheck

					from data_sale WITH(NOLOCK)
						LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
						INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
						LEFT  JOIN data_saleitem2ticket WITH(NOLOCK)				on data_saleitem2ticket.saleitemid = data_saleitem.saleitemid
						LEFT  JOIN data_saleitem2Performance WITH(NOLOCK)			on data_saleitem2performance.saleitemid = data_saleitem.saleitemid
						LEFT  JOIN cnf_performance WITH(NOLOCK)						on cnf_Performance.performanceid = data_saleitem2performance.performanceid
						LEFT  JOIN data_ticket WITH(NOLOCK)							on data_ticket.ticketid = data_saleitem2ticket.ticketid
						left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
						left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

					where data_sale.saleid = @INS_SaleID
					  and data_ticket.accountid is not null

--Reservation Account
				Insert into data_shopcartitemlimit
				select  data_sale.saleid,
				        0 as B2B,
						0 as  Billing,
						ISNULL(data_reservation.accountid, ODR.AccountID) as ReservationAccountID,
						0 TicketAccountID,
						data_saleitem.Matrixcellid,
						data_saleitem.Quantity,
						0,
						0,
						data_sale.saleid,
						data_saleitem.saleitemid,
						case when data_saleitem.Quantity &lt; 0 and (select top 1 1 
							                                        from data_accountlimit WITH(NOLOCK)
																	where data_accountlimit.saleid = ODS.Saleid
																	  and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId) = 1

															then ISNULL((select top 1 1
																			from data_transaction
																			where data_transaction.transactiontype in (17, 18, 20, 22, 40, 47)
																				and data_transaction.saleid = data_sale.saleid), 0)
							when data_saleitem.Quantity &lt; 0 and ISNULL((select top 1 1 
							                                        from data_accountlimit WITH(NOLOCK)
																	where data_accountlimit.saleid = ODS.Saleid
																	  and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId), 0) &lt;&gt; 1

															then 1
								else 0
							end as UsageCheck

				from data_sale WITH(NOLOCK)
					LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
					INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
					left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
					left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

					where data_sale.saleid = @INS_SaleID

--B2B Account
				Insert into data_shopcartitemlimit
				select  data_sale.saleid,
				        ISNULL(data_reservation.B2BAccountID, ODR.B2BAccountID) as B2B,
						0 as  Billing,
						0 as ReservationAccountID,
						0 TicketAccountID,
						data_saleitem.Matrixcellid,
						data_saleitem.Quantity,
						0,
						0,
						data_sale.saleid,
						data_saleitem.saleitemid,
						case when data_saleitem.Quantity &lt; 0 and (select top 1 1 
							                                        from data_accountlimit WITH(NOLOCK)
																	where data_accountlimit.saleid = ODS.Saleid
																	  and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId) = 1

															then ISNULL((select top 1 1
																			from data_transaction
																			where data_transaction.transactiontype in (17, 18, 20, 22, 40, 47)
																				and data_transaction.saleid = data_sale.saleid), 0)
							when data_saleitem.Quantity &lt; 0 and ISNULL((select top 1 1 
							                                        from data_accountlimit WITH(NOLOCK)
																	where data_accountlimit.saleid = ODS.Saleid
																	  and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId), 0) &lt;&gt; 1

															then 1
								else 0
							end as UsageCheck

				from data_sale WITH(NOLOCK)
					LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
					INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
					left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
					left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

					where data_sale.saleid = @INS_SaleID
					  and ISNULL(data_reservation.B2BAccountID, ODR.B2BAccountID) is not null

--Billing Account
				Insert into data_shopcartitemlimit
				select  data_sale.saleid,
				        0 as B2B,
				        ISNULL(data_reservation.BillingAccountId, ODR.BillingAccountId) as BillingAccountId,
						0 as ReservationAccountID,
						0 TicketAccountID,
						data_saleitem.Matrixcellid,
						data_saleitem.Quantity,
						0,
						0,
						data_sale.saleid,
						data_saleitem.saleitemid,
						case when data_saleitem.Quantity &lt; 0 and (select top 1 1 
							                                        from data_accountlimit WITH(NOLOCK)
																	where data_accountlimit.saleid = ODS.Saleid
																	  and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId) = 1

															then ISNULL((select top 1 1
																			from data_transaction
																			where data_transaction.transactiontype in (17, 18, 20, 22, 40, 47)
																				and data_transaction.saleid = data_sale.saleid), 0)
							when data_saleitem.Quantity &lt; 0 and ISNULL((select top 1 1 
							                                        from data_accountlimit WITH(NOLOCK)
																	where data_accountlimit.saleid = ODS.Saleid
																	  and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId), 0) &lt;&gt; 1

															then 1
								else 0
							end as UsageCheck

				from data_sale WITH(NOLOCK)
					LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
					INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
					left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
					left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

					where data_sale.saleid = @INS_SaleID
					  and ISNULL(data_reservation.BillingAccountId, ODR.BillingAccountId) is not null

--Ticket Account
				Insert into data_shopcartitemlimit
				select  data_sale.saleid,
				        0 as B2B,
				        0 as BillingAccountId,
						0 as ReservationAccountID,
						data_ticket.accountid TicketAccountID,
						data_saleitem.Matrixcellid,
						case when data_ticket.ticketid is not null then case when data_saleitem.Quantity &lt; 0 then -1 else 1 end
										else data_saleitem.Quantity
									end Quantity,
						0,
						0,
						data_sale.saleid,
						data_saleitem.saleitemid,
						case when data_saleitem.Quantity &lt; 0 and (select top 1 1 
							                                        from data_accountlimit WITH(NOLOCK)
																	where data_accountlimit.saleid = ODS.Saleid
																	  and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId) = 1

															then ISNULL((select top 1 1
																			from data_transaction
																			where data_transaction.transactiontype in (17, 18, 20, 22, 40, 47)
																				and data_transaction.saleid = data_sale.saleid), 0)
							when data_saleitem.Quantity &lt; 0 and ISNULL((select top 1 1 
							                                        from data_accountlimit WITH(NOLOCK)
																	where data_accountlimit.saleid = ODS.Saleid
																	  and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId), 0) &lt;&gt; 1

															then 1
								else 0
							end as UsageCheck

					from data_sale WITH(NOLOCK)
						LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
						INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
						LEFT  JOIN data_saleitem2ticket WITH(NOLOCK)				on data_saleitem2ticket.saleitemid = data_saleitem.saleitemid
						LEFT  JOIN data_ticket WITH(NOLOCK)							on data_ticket.ticketid = data_saleitem2ticket.ticketid
						left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
						left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

					where data_sale.saleid = @INS_SaleID
					  and data_ticket.accountid is not null	

			END

--Reservation Deletes
			if @DR_status = 1
			begin
			--Reservation Account
				Insert into data_shopcartitemlimit
				select  data_sale.saleid,
				        0 as B2B,
						0 as  Billing,
						ISNULL(data_reservation.accountid, ODR.AccountID) as ReservationAccountID,
						0 TicketAccountID,
						data_saleitem.Matrixcellid,
						data_saleitem.Quantity,
						case when cnf_performance.PerformanceID is not null then cnf_performance.PerformanceID
												 else 9999999
						end ,
						case when cnf_performance.Eventid is not null then cnf_performance.Eventid
												 else  9999999
						end,
						data_sale.saleid,
						data_saleitem.saleitemid,
						case when data_saleitem.Quantity &lt; 0 and (select top 1 1 
							                                        from data_accountlimit WITH(NOLOCK)
																	where data_accountlimit.saleid = ODS.Saleid
																	  and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId) = 1

															then ISNULL((select top 1 1
																			from data_transaction
																			where data_transaction.transactiontype in (17, 18, 20, 22, 40, 47)
																				and data_transaction.saleid = data_sale.saleid), 0)
							when data_saleitem.Quantity &lt; 0 and ISNULL((select top 1 1 
							                                        from data_accountlimit WITH(NOLOCK)
																	where data_accountlimit.saleid = ODS.Saleid
																	  and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId), 0) &lt;&gt; 1

															then 1
								else 0
							end as UsageCheck

				from data_sale WITH(NOLOCK)
					LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
					INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
					LEFT  JOIN data_saleitem2Performance WITH(NOLOCK)			on data_saleitem2performance.saleitemid = data_saleitem.saleitemid
					LEFT  JOIN cnf_performance WITH(NOLOCK)						on cnf_Performance.performanceid = data_saleitem2performance.performanceid
					left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
					left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

					where data_sale.saleid = @INS_SaleID
					  and data_saleitem.quantity &lt; 0

--B2B Account
				Insert into data_shopcartitemlimit
				select  data_sale.saleid,
				        ISNULL(data_reservation.B2BAccountID, ODR.B2BAccountID) as B2B,
						0 as  Billing,
						0 as ReservationAccountID,
						0 TicketAccountID,
						data_saleitem.Matrixcellid,
						data_saleitem.Quantity,
						case when cnf_performance.PerformanceID is not null then cnf_performance.PerformanceID
												 else 9999999
						end ,
						case when cnf_performance.Eventid is not null then cnf_performance.Eventid
												 else  9999999
						end,
						data_sale.saleid,
						data_saleitem.saleitemid,
						case when data_saleitem.Quantity &lt; 0 and (select top 1 1 
							                                        from data_accountlimit WITH(NOLOCK)
																	where data_accountlimit.saleid = ODS.Saleid
																	  and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId) = 1

															then ISNULL((select top 1 1
																			from data_transaction
																			where data_transaction.transactiontype in (17, 18, 20, 22, 40, 47)
																				and data_transaction.saleid = data_sale.saleid), 0)
							when data_saleitem.Quantity &lt; 0 and ISNULL((select top 1 1 
							                                        from data_accountlimit WITH(NOLOCK)
																	where data_accountlimit.saleid = ODS.Saleid
																	  and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId), 0) &lt;&gt; 1

															then 1
								else 0
							end as UsageCheck

				from data_sale WITH(NOLOCK)
					LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
					INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
					LEFT  JOIN data_saleitem2Performance WITH(NOLOCK)			on data_saleitem2performance.saleitemid = data_saleitem.saleitemid
					LEFT  JOIN cnf_performance WITH(NOLOCK)						on cnf_Performance.performanceid = data_saleitem2performance.performanceid
					left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
					left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

					where data_sale.saleid = @INS_SaleID
					  and ISNULL(data_reservation.B2BAccountID, ODR.B2BAccountID) is not null
					  and data_saleitem.quantity &lt; 0

--Billing Account
				Insert into data_shopcartitemlimit
				select  data_sale.saleid,
				        0 as B2B,
				        ISNULL(data_reservation.BillingAccountId, ODR.BillingAccountId) as BillingAccountId,
						0 as ReservationAccountID,
						0 TicketAccountID,
						data_saleitem.Matrixcellid,
						data_saleitem.Quantity,
						case when cnf_performance.PerformanceID is not null then cnf_performance.PerformanceID
												 else 9999999
						end ,
						case when cnf_performance.Eventid is not null then cnf_performance.Eventid
												 else  9999999
						end,
						data_sale.saleid,
						data_saleitem.saleitemid,
						case when data_saleitem.Quantity &lt; 0 and (select top 1 1 
							                                        from data_accountlimit WITH(NOLOCK)
																	where data_accountlimit.saleid = ODS.Saleid
																	  and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId) = 1

															then ISNULL((select top 1 1
																			from data_transaction
																			where data_transaction.transactiontype in (17, 18, 20, 22, 40, 47)
																				and data_transaction.saleid = data_sale.saleid), 0)
							when data_saleitem.Quantity &lt; 0 and ISNULL((select top 1 1 
							                                        from data_accountlimit WITH(NOLOCK)
																	where data_accountlimit.saleid = ODS.Saleid
																	  and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId), 0) &lt;&gt; 1

															then 1
								else 0
							end as UsageCheck

				from data_sale WITH(NOLOCK)
					LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
					INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
					LEFT  JOIN data_saleitem2Performance WITH(NOLOCK)			on data_saleitem2performance.saleitemid = data_saleitem.saleitemid
					LEFT  JOIN cnf_performance WITH(NOLOCK)						on cnf_Performance.performanceid = data_saleitem2performance.performanceid
					left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
					left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

					where data_sale.saleid = @INS_SaleID
					  and ISNULL(data_reservation.BillingAccountId, ODR.BillingAccountId) is not null
					  and data_saleitem.quantity &lt; 0

--Ticket Account
				Insert into data_shopcartitemlimit
				select  data_sale.saleid,
				        0 as B2B,
				        0 as BillingAccountId,
						0 as ReservationAccountID,
						data_ticket.accountid TicketAccountID,
						data_saleitem.Matrixcellid,
						case when data_ticket.ticketid is not null then case when data_saleitem.Quantity &lt; 0 then -1 else 1 end
										else data_saleitem.Quantity
									end Quantity,
						case when cnf_performance.PerformanceID is not null then cnf_performance.PerformanceID
												 else 9999999
						end ,
						case when cnf_performance.Eventid is not null then cnf_performance.Eventid
												 else  9999999
						end,
						data_sale.saleid,
						data_saleitem.saleitemid,
						case when data_saleitem.Quantity &lt; 0 and (select top 1 1 
							                                        from data_accountlimit WITH(NOLOCK)
																	where data_accountlimit.saleid = ODS.Saleid
																	  and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId) = 1

															then ISNULL((select top 1 1
																			from data_transaction
																			where data_transaction.transactiontype in (17, 18, 20, 22, 40, 47)
																				and data_transaction.saleid = data_sale.saleid), 0)
							when data_saleitem.Quantity &lt; 0 and ISNULL((select top 1 1 
							                                        from data_accountlimit WITH(NOLOCK)
																	where data_accountlimit.saleid = ODS.Saleid
																	  and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId), 0) &lt;&gt; 1

															then 1
								else 0
							end as UsageCheck

					from data_sale WITH(NOLOCK)
						LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
						INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
						LEFT  JOIN data_saleitem2ticket WITH(NOLOCK)				on data_saleitem2ticket.saleitemid = data_saleitem.saleitemid
						LEFT  JOIN data_saleitem2Performance WITH(NOLOCK)			on data_saleitem2performance.saleitemid = data_saleitem.saleitemid
						LEFT  JOIN cnf_performance WITH(NOLOCK)						on cnf_Performance.performanceid = data_saleitem2performance.performanceid
						LEFT  JOIN data_ticket WITH(NOLOCK)							on data_ticket.ticketid = data_saleitem2ticket.ticketid
						left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
						left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

					where data_sale.saleid = @INS_SaleID
					  and data_ticket.accountid is not null
					  and data_saleitem.quantity &lt; 0

--Reservation Account
				Insert into data_shopcartitemlimit
				select  data_sale.saleid,
				        0 as B2B,
						0 as  Billing,
						ISNULL(data_reservation.accountid, ODR.AccountID) as ReservationAccountID,
						0 TicketAccountID,
						data_saleitem.Matrixcellid,
						data_saleitem.Quantity,
						0,
						0,
						data_sale.saleid,
						data_saleitem.saleitemid,
						case when data_saleitem.Quantity &lt; 0 and (select top 1 1 
							                                        from data_accountlimit WITH(NOLOCK)
																	where data_accountlimit.saleid = ODS.Saleid
																	  and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId) = 1

															then ISNULL((select top 1 1
																			from data_transaction
																			where data_transaction.transactiontype in (17, 18, 20, 22, 40, 47)
																				and data_transaction.saleid = data_sale.saleid), 0)
							when data_saleitem.Quantity &lt; 0 and ISNULL((select top 1 1 
							                                        from data_accountlimit WITH(NOLOCK)
																	where data_accountlimit.saleid = ODS.Saleid
																	  and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId), 0) &lt;&gt; 1

															then 1
								else 0
							end as UsageCheck

				from data_sale WITH(NOLOCK)
					LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
					INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
					left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
					left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

					where data_sale.saleid = @INS_SaleID
					  and data_saleitem.quantity &lt; 0

--B2B Account
				Insert into data_shopcartitemlimit
				select  data_sale.saleid,
				        ISNULL(data_reservation.B2BAccountID, ODR.B2BAccountID) as B2B,
						0 as  Billing,
						0 as ReservationAccountID,
						0 TicketAccountID,
						data_saleitem.Matrixcellid,
						data_saleitem.Quantity,
						0,
						0,
						data_sale.saleid,
						data_saleitem.saleitemid,
						case when data_saleitem.Quantity &lt; 0 and (select top 1 1 
							                                        from data_accountlimit WITH(NOLOCK)
																	where data_accountlimit.saleid = ODS.Saleid
																	  and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId) = 1

															then ISNULL((select top 1 1
																			from data_transaction
																			where data_transaction.transactiontype in (17, 18, 20, 22, 40, 47)
																				and data_transaction.saleid = data_sale.saleid), 0)
							when data_saleitem.Quantity &lt; 0 and ISNULL((select top 1 1 
							                                        from data_accountlimit WITH(NOLOCK)
																	where data_accountlimit.saleid = ODS.Saleid
																	  and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId), 0) &lt;&gt; 1

															then 1
								else 0
							end as UsageCheck

				from data_sale WITH(NOLOCK)
					LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
					INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
					left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
					left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

					where data_sale.saleid = @INS_SaleID
					  and ISNULL(data_reservation.B2BAccountID, ODR.B2BAccountID) is not null
					  and data_saleitem.quantity &lt; 0

--Billing Account
				Insert into data_shopcartitemlimit
				select  data_sale.saleid,
				        0 as B2B,
				        ISNULL(data_reservation.BillingAccountId, ODR.BillingAccountId) as BillingAccountId,
						0 as ReservationAccountID,
						0 TicketAccountID,
						data_saleitem.Matrixcellid,
						data_saleitem.Quantity,
						0,
						0,
						data_sale.saleid,
						data_saleitem.saleitemid,
						case when data_saleitem.Quantity &lt; 0 and (select top 1 1 
							                                        from data_accountlimit WITH(NOLOCK)
																	where data_accountlimit.saleid = ODS.Saleid
																	  and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId) = 1

															then ISNULL((select top 1 1
																			from data_transaction
																			where data_transaction.transactiontype in (17, 18, 20, 22, 40, 47)
																				and data_transaction.saleid = data_sale.saleid), 0)
							when data_saleitem.Quantity &lt; 0 and ISNULL((select top 1 1 
							                                        from data_accountlimit WITH(NOLOCK)
																	where data_accountlimit.saleid = ODS.Saleid
																	  and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId), 0) &lt;&gt; 1

															then 1
								else 0
							end as UsageCheck

				from data_sale WITH(NOLOCK)
					LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
					INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
					left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
					left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

					where data_sale.saleid = @INS_SaleID
					  and ISNULL(data_reservation.BillingAccountId, ODR.BillingAccountId) is not null
					  and data_saleitem.quantity &lt; 0

--Ticket Account
				Insert into data_shopcartitemlimit
				select  data_sale.saleid,
				        0 as B2B,
				        0 as BillingAccountId,
						0 as ReservationAccountID,
						data_ticket.accountid TicketAccountID,
						data_saleitem.Matrixcellid,
						case when data_ticket.ticketid is not null then case when data_saleitem.Quantity &lt; 0 then -1 else 1 end
										else data_saleitem.Quantity
									end Quantity,
						0,
						0,
						data_sale.saleid,
						data_saleitem.saleitemid,
						case when data_saleitem.Quantity &lt; 0 and (select top 1 1 
							                                        from data_accountlimit WITH(NOLOCK)
																	where data_accountlimit.saleid = ODS.Saleid
																	  and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId) = 1

															then ISNULL((select top 1 1
																			from data_transaction
																			where data_transaction.transactiontype in (17, 18, 20, 22, 40, 47)
																				and data_transaction.saleid = data_sale.saleid), 0)
							when data_saleitem.Quantity &lt; 0 and ISNULL((select top 1 1 
							                                        from data_accountlimit WITH(NOLOCK)
																	where data_accountlimit.saleid = ODS.Saleid
																	  and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId), 0) &lt;&gt; 1

															then 1
								else 0
							end as UsageCheck

					from data_sale WITH(NOLOCK)
						LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
						INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
						LEFT  JOIN data_saleitem2ticket WITH(NOLOCK)				on data_saleitem2ticket.saleitemid = data_saleitem.saleitemid
						LEFT  JOIN data_ticket WITH(NOLOCK)							on data_ticket.ticketid = data_saleitem2ticket.ticketid
						left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
						left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

					where data_sale.saleid = @INS_SaleID
					  and data_ticket.accountid is not null	
					  and data_saleitem.quantity &lt; 0
			end

			delete from data_shopcartitemlimit where PerformanceID = 9999999
			delete from data_shopcartitemlimit where Quantity = 0
			--select * 		from data_shopcartitemlimit
			
			Exec otn_sp_CheckAccountRestrictions 0, @INS_SaleID


		end
	end
end</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>ALTER TABLE [dbo].[DATA_Sale] ENABLE TRIGGER [data_sale_SalesRestriction]</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dchen</ADDEDBY><SQLVERSION>3250</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>// adding columns: hotel_checkin, hotel_checkout</REASON><TABLENAMES>data_reservation=saleid</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'Hotel_CheckIn' 
                      AND OBJECT_ID = OBJECT_ID(N'DATA_Reservation'))
BEGIN
  ALTER TABLE DATA_Reservation ADD Hotel_CheckIn datetime;
  ALTER TABLE DATA_Reservation ADD Hotel_CheckOut datetime;      
END </SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fdipalma</ADDEDBY><SQLVERSION>3249</SQLVERSION><RMTRACKLINK>IDBOS-3108</RMTRACKLINK><REASON>BOS - Whitelist issues - Adding TicketId field</REASON><TABLENAMES>OFF_WhiteListTck=WhiteListTckId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'TicketId' 
                      AND OBJECT_ID = OBJECT_ID(N'OFF_WhiteListTck'))
BEGIN
  ALTER TABLE OFF_WhiteListTck 
  ADD TicketId Integer NOT NULL DEFAULT 0;     
END </SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT *  FROM sys.indexes  WHERE name='Idx_OFF_WhiteListTck_IdentifierCode' 
    AND object_id = OBJECT_ID('OFF_WhiteListTck'))
  begin
    DROP INDEX [Idx_OFF_WhiteListTck_IdentifierCode] ON OFF_WhiteListTck;
  end</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT object_id
               FROM sys.indexes
               WHERE Name = 'Idx_OFF_WhiteListTck_IdentifierCode')
BEGIN
	CREATE NONCLUSTERED INDEX [Idx_OFF_WhiteListTck_IdentifierCode] ON [dbo].[OFF_WhiteListTck]
	(
		[IdentifierCode] ASC,
		[TicketId] ASC
	)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT 1 FROM sys.procedures 
          WHERE Name = 'otn_sp_WhiteList_Import')
	DROP PROCEDURE otn_sp_WhiteList_Import</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>create procedure [dbo].[otn_sp_WhiteList_Import]
	@IdentifierCode varchar(400),
    @IdentifierType smallint,
	@VoidType smallint,
	@MatrixCellId int,
	@ValidityXML ntext,
	@TicketId int
as
begin
	DECLARE @c int

	select @c = COUNT(IdentifierCode) from OFF_WhiteListTck where (IdentifierCode = @IdentifierCode) and (TicketId = @TicketId)

	IF (@c = 0)
	begin
		insert into OFF_WhiteListTck (
		IdentifierCode,
		IdentifierType,
		VoidType,
		MatrixCellId,
		ValidityXML,
		TicketId
		) values (
		@IdentifierCode,
		@IdentifierType,
		@VoidType,
		@MatrixCellId,
		@ValidityXML,
		@TicketId
		)
	end
	else
	begin
		update OFF_WhiteListTck
		set
		IdentifierType=@IdentifierType,
		VoidType=@VoidType,
		MatrixCellId=@MatrixCellId,
		ValidityXML=@ValidityXML
		where
		(IdentifierCode=@IdentifierCode) and
		(TicketId=@TicketId)
	end

end</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>3248</SQLVERSION><RMTRACKLINK>IDBOS-2850</RMTRACKLINK><REASON>Added column TransferPerfMatrixCellId to CNF_MatrixCellInfo</REASON><TABLENAMES>CNF_MatrixCellInfo=MatrixCellInfoId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'TransferPerfMatrixCellId' 
                      AND OBJECT_ID = OBJECT_ID(N'CNF_MatrixCellInfo'))
BEGIN
  ALTER TABLE CNF_MatrixCellInfo 
  ADD TransferPerfMatrixCellId Integer NULL;     
END </SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_MatrixCellInfo_TransferPerfMatrixCellId')
BEGIN
  ALTER TABLE [CNF_MatrixCellInfo]
  WITH CHECK ADD CONSTRAINT FK_CNF_MatrixCellInfo_TransferPerfMatrixCellId FOREIGN KEY(TransferPerfMatrixCellId) 
  REFERENCES [CNF_MatrixCell] ([MatrixCellId])
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dchen</ADDEDBY><SQLVERSION>3247</SQLVERSION><RMTRACKLINK>IDBOS-2795</RMTRACKLINK><REASON>Adding new fields:
  * Note -&gt; NoteAK
  * Task Status -&gt; Name</REASON><TABLENAMES>CNF_User=UserId
DATA_Note=NoteId
CNF_TaskStatus=TaskStatusId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'UserEmail' 
                      AND OBJECT_ID = OBJECT_ID(N'CNF_User'))
BEGIN
  ALTER TABLE CNF_User ADD UserEmail NVarChar(200) null;     
END </SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'NoteAK' 
                      AND OBJECT_ID = OBJECT_ID(N'DATA_Note'))
BEGIN
  ALTER TABLE DATA_Note ADD NoteAK NVarChar(32) null;     
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'Name' 
                      AND OBJECT_ID = OBJECT_ID(N'CNF_TaskStatus'))
BEGIN
  ALTER TABLE CNF_TaskStatus ADD Name NVarChar(50) null;     
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'Description' 
                      AND OBJECT_ID = OBJECT_ID(N'CNF_TaskStatus'))
BEGIN
  ALTER TABLE CNF_TaskStatus ALTER COLUMN Description NVarChar(100) null;     
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'Completed' 
                      AND OBJECT_ID = OBJECT_ID(N'CNF_TaskStatus'))
BEGIN
  ALTER TABLE CNF_TaskStatus ADD Completed smallint not null default 0;     




END


</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'Completed' 
                      AND OBJECT_ID = OBJECT_ID(N'CNF_TaskStatus'))
BEGIN
  UPDATE CNF_TaskStatus SET Completed = 0 WHERE TaskStatusId &lt;&gt; 3
  
  UPDATE CNF_TaskStatus SET Completed = 1 WHERE TaskStatusId = 3

  UPDATE CNF_TaskStatus SET Name = Code 

END
</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>3246</SQLVERSION><RMTRACKLINK>IDBOS-2695</RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT  TOP 1 COUNT(*)
				FROM    sys.index_columns AS ic
						INNER JOIN sys.indexes AS i		            ON ic.[object_id] = i.[object_id]
																		AND ic.index_id = i.index_id
						INNER JOIN sys.columns AS c                 ON ic.[object_id] = c.[object_id]
																		AND ic.column_id = c.column_id

				WHERE   ic.[object_id] = OBJECT_ID(N'dbo.DATA_MediaIdentifier')
				  AND   i.[type] != 0
				  AND   ic.is_included_column = 0
				GROUP BY i.index_id
					HAVING  COUNT(CASE WHEN c.Name = 'AccountId' THEN 1 END) &gt; 0
				ORDER BY 1
			   )
BEGIN
	IF NOT EXISTS (SELECT * 
                 FROM sys.indexes 
                WHERE name='Idx_MediaIdentifier_AccountId' AND object_id = OBJECT_ID('DATA_MediaIdentifier')
			  )
	BEGIN
		CREATE INDEX Idx_MediaIdentifier_AccountId on [DATA_MediaIdentifier] ([AccountId])
	END;
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                FROM sys.indexes 
            WHERE name='Idx_MatrixDimension_PTId' AND object_id = OBJECT_ID('CNF_MatrixDimension')
			)
BEGIN
	CREATE INDEX Idx_MatrixDimension_PTId ON [CNF_MatrixDimension] ([PriceTableId])		
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                FROM sys.indexes 
            WHERE name='Idx_MatrixCell_SiaeAbb' AND object_id = OBJECT_ID('CNF_MatrixCell')
			)
BEGIN
	CREATE INDEX Idx_MatrixCell_SiaeAbb on [CNF_MatrixCell] ([AdditionalCode], [MatrixCellId])		
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                FROM sys.indexes 
            WHERE name='Idx_MatrixCell_MsId_PLId_Enabled' AND object_id = OBJECT_ID('CNF_MatrixCell')
			)
BEGIN
	CREATE INDEX Idx_MatrixCell_MsId_PLId_Enabled on [CNF_MatrixCell] ([MatrixSheetId], [Enabled]) INCLUDE ([AttributeSetId])		
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT  TOP 1 COUNT(*)
				FROM    sys.index_columns AS ic
						INNER JOIN sys.indexes AS i		            ON ic.[object_id] = i.[object_id]
																		AND ic.index_id = i.index_id
						INNER JOIN sys.columns AS c                 ON ic.[object_id] = c.[object_id]
																		AND ic.column_id = c.column_id

				WHERE   ic.[object_id] = OBJECT_ID(N'dbo.CNF_MatrixCell')
				  AND   i.[type] != 0
				  AND   ic.is_included_column = 0
				GROUP BY i.index_id
					HAVING  COUNT(CASE WHEN c.Name = 'MatrixCellAK' THEN 1 END) &gt; 0
				ORDER BY 1
			   )
BEGIN
	IF NOT EXISTS (SELECT * 
                 FROM sys.indexes 
                WHERE name='Idx_MatrixCell_MCAK' AND object_id = OBJECT_ID('CNF_MatrixCell')
			  )
	BEGIN
		CREATE INDEX Idx_MatrixCell_MCAK on [CNF_MatrixCell] ([MatrixCellAk])
	END;
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT  TOP 1 COUNT(*)
				FROM    sys.index_columns AS ic
						INNER JOIN sys.indexes AS i		            ON ic.[object_id] = i.[object_id]
																		AND ic.index_id = i.index_id
						INNER JOIN sys.columns AS c                 ON ic.[object_id] = c.[object_id]
																		AND ic.column_id = c.column_id

				WHERE   ic.[object_id] = OBJECT_ID(N'dbo.CNF_IncentiveTicket')
				  AND   i.[type] != 0
				  AND   ic.is_included_column = 0
				GROUP BY i.index_id
					HAVING  COUNT(CASE WHEN c.Name = 'MatrixCellId' THEN 1 END) &gt; 0
				ORDER BY 1
			   )
BEGIN
	IF NOT EXISTS (SELECT * 
                 FROM sys.indexes 
                WHERE name='Idx_IncentiveTck_McId' AND object_id = OBJECT_ID('CNF_IncentiveTicket')
			  )
	BEGIN
		CREATE INDEX Idx_IncentiveTck_McId on [CNF_IncentiveTicket] ([MatrixCellId])
	END;
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                FROM sys.indexes 
            WHERE name='Idx_HLMaster_RefId_DbTableId' AND object_id = OBJECT_ID('DATA_HL_Master')
			)
BEGIN
	CREATE INDEX Idx_HLMaster_RefId_DbTableId on [DATA_HL_Master] ([ReferenceId], [DBTableId])
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                FROM sys.indexes 
            WHERE name='Idx_HistoryLog_2' AND object_id = OBJECT_ID('CNF_DBColumn')
			)
BEGIN
	CREATE INDEX Idx_HistoryLog_2 on [CNF_DBColumn] ([DBTableId]) INCLUDE ([ColumnName])
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                FROM sys.indexes 
            WHERE name='Idx_HistoryLog_1' AND object_id = OBJECT_ID('CNF_DBColumn')
			)
BEGIN
	CREATE INDEX Idx_HistoryLog_1 on [CNF_DBColumn] ([DBTableId])
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT> IF NOT EXISTS (SELECT  TOP 1 COUNT(*)
				FROM    sys.index_columns AS ic
						INNER JOIN sys.indexes AS i		            ON ic.[object_id] = i.[object_id]
																		AND ic.index_id = i.index_id
						INNER JOIN sys.columns AS c                 ON ic.[object_id] = c.[object_id]
																		AND ic.column_id = c.column_id

				WHERE   ic.[object_id] = OBJECT_ID(N'dbo.DATA_PaymentFlex2SaleItem')
				  AND   i.[type] != 0
				  AND   ic.is_included_column = 0
				GROUP BY i.index_id
					HAVING  COUNT(CASE WHEN c.Name = 'SaleItemId' THEN 1 END) &gt; 0
				ORDER BY 1
			   )
BEGIN
	IF NOT EXISTS (SELECT * 
                 FROM sys.indexes 
                WHERE name='Idx_FlexToSaleItem_SIId' AND object_id = OBJECT_ID('DATA_PaymentFlex2SaleItem')
			  )
	BEGIN
		CREATE INDEX Idx_FlexToSaleItem_SIId ON [DATA_PaymentFlex2SaleItem] ([SaleItemId])		
	END;
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT  TOP 1 COUNT(*)
				FROM    sys.index_columns AS ic
						INNER JOIN sys.indexes AS i		            ON ic.[object_id] = i.[object_id]
																		AND ic.index_id = i.index_id
						INNER JOIN sys.columns AS c                 ON ic.[object_id] = c.[object_id]
																		AND ic.column_id = c.column_id

				WHERE   ic.[object_id] = OBJECT_ID(N'dbo.DATA_PaymentFlex2SaleItem')
				  AND   i.[type] != 0
				  AND   ic.is_included_column = 0
				GROUP BY i.index_id
					HAVING  COUNT(CASE WHEN c.Name = 'PaymentId' THEN 1 END) &gt; 0
				ORDER BY 1
			   )
BEGIN
	IF NOT EXISTS (SELECT * 
                 FROM sys.indexes 
                WHERE name='Idx_FlexToSaleItem_PaymentId' AND object_id = OBJECT_ID('DATA_PaymentFlex2SaleItem')
			  )
	BEGIN
		CREATE INDEX Idx_FlexToSaleItem_PaymentId ON [DATA_PaymentFlex2SaleItem] ([PaymentId])		
	END;
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                FROM sys.indexes 
            WHERE name='Idx_ExceptionLog_UserId_WksId' AND object_id = OBJECT_ID('DATA_ExceptionLog')
			)
BEGIN
	CREATE INDEX Idx_ExceptionLog_UserId_WksId on [DATA_ExceptionLog] ([UserId], [WorkstationId])		
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT  TOP 1 COUNT(*)
				FROM    sys.index_columns AS ic
						INNER JOIN sys.indexes AS i		            ON ic.[object_id] = i.[object_id]
																		AND ic.index_id = i.index_id
						INNER JOIN sys.columns AS c                 ON ic.[object_id] = c.[object_id]
																		AND ic.column_id = c.column_id

				WHERE   ic.[object_id] = OBJECT_ID(N'dbo.ARC_Document')
				  AND   i.[type] != 0
				  AND   ic.is_included_column = 0
				GROUP BY i.index_id
					HAVING  COUNT(CASE WHEN c.Name = 'DocumentAK' THEN 1 END) &gt; 0
				ORDER BY 1
			   )
BEGIN
	IF NOT EXISTS (SELECT * 
                 FROM sys.indexes 
                WHERE name='Idx_Document_Ak' AND object_id = OBJECT_ID('ARC_Document')
			  )
	BEGIN
		CREATE INDEX Idx_Document_Ak on [ARC_Document] ([DocumentAK])
	END;
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT> IF NOT EXISTS (SELECT  TOP 1 COUNT(*)
				FROM    sys.index_columns AS ic
						INNER JOIN sys.indexes AS i		            ON ic.[object_id] = i.[object_id]
																		AND ic.index_id = i.index_id
						INNER JOIN sys.columns AS c                 ON ic.[object_id] = c.[object_id]
																		AND ic.column_id = c.column_id

				WHERE   ic.[object_id] = OBJECT_ID(N'dbo.CNF_DocTemplate')
				  AND   i.[type] != 0
				  AND   ic.is_included_column = 0
				GROUP BY i.index_id
					HAVING  COUNT(CASE WHEN c.Name = 'DocDatasourceId' THEN 1 END) &gt; 0
				ORDER BY 1
			   )
BEGIN
	IF NOT EXISTS (SELECT * 
                 FROM sys.indexes 
                WHERE name='Idx_DocTemplate_DataSourceId' AND object_id = OBJECT_ID('CNF_DocTemplate')
			  )
	BEGIN
		CREATE INDEX Idx_DocTemplate_DataSourceId ON [CNF_DocTemplate] ([DocDatasourceId])		
	END;
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                FROM sys.indexes 
            WHERE name='Idx_DmgCat_Code_Type' AND object_id = OBJECT_ID('CNF_DmgCategory')
			)
BEGIN
	CREATE INDEX Idx_DmgCat_Code_Type on [CNF_DmgCategory] ([DmgCategoryCode], [DmgType])		
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>   IF NOT EXISTS (SELECT  TOP 1 COUNT(*)
				FROM    sys.index_columns AS ic
						INNER JOIN sys.indexes AS i		            ON ic.[object_id] = i.[object_id]
																		AND ic.index_id = i.index_id
						INNER JOIN sys.columns AS c                 ON ic.[object_id] = c.[object_id]
																		AND ic.column_id = c.column_id

				WHERE   ic.[object_id] = OBJECT_ID(N'dbo.CNF_DataMaskTranslation')
				  AND   i.[type] != 0
				  AND   ic.is_included_column = 0
				GROUP BY i.index_id
					HAVING  COUNT(CASE WHEN c.Name = 'DataMaskId' THEN 1 END) &gt; 0
				ORDER BY 1
			   )
BEGIN
	IF NOT EXISTS (SELECT * 
                 FROM sys.indexes 
                WHERE name='Idx_DataMaskTranslation_DataMaskId' AND object_id = OBJECT_ID('CNF_DataMaskTranslation')
			  )
	BEGIN
		CREATE INDEX Idx_DataMaskTranslation_DataMaskId on [CNF_DataMaskTranslation] ([DataMaskId])
	END;
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT  TOP 1 COUNT(*)
				FROM    sys.index_columns AS ic
						INNER JOIN sys.indexes AS i		            ON ic.[object_id] = i.[object_id]
																		AND ic.index_id = i.index_id
						INNER JOIN sys.columns AS c                 ON ic.[object_id] = c.[object_id]
																		AND ic.column_id = c.column_id

				WHERE   ic.[object_id] = OBJECT_ID(N'dbo.CNF_DataMask')
				  AND   i.[type] != 0
				  AND   ic.is_included_column = 0
				GROUP BY i.index_id
					HAVING  COUNT(CASE WHEN c.Name = 'MaskId' THEN 1 END) &gt; 0
				ORDER BY 1
			   )
BEGIN
	IF NOT EXISTS (SELECT * 
                 FROM sys.indexes 
                WHERE name='Idx_DataMask_Id' AND object_id = OBJECT_ID('CNF_DataMask')
			  )
	BEGIN
		CREATE INDEX Idx_DataMask_Id on [CNF_DataMask] ([MaskId])
	END;
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>   IF NOT EXISTS (SELECT * 
                FROM sys.indexes 
            WHERE name='Idx_Box_Full' AND object_id = OBJECT_ID('DATA_Box')
			)
BEGIN
	CREATE INDEX Idx_Box_Full on [DATA_Box] ([UserId], [OffLineImport], [CreationDate]) INCLUDE ([Status])		
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                FROM sys.indexes 
            WHERE name='Idx_Attribute_AttTemplateId_Enabled' AND object_id = OBJECT_ID('CNF_Attribute')
			)
BEGIN
	CREATE INDEX Idx_Attribute_AttTemplateId_Enabled ON [CNF_Attribute] ([AttributeTemplateId], [Enabled])
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                FROM sys.indexes 
            WHERE name='Idx_Attribute_AttTemplateId' AND object_id = OBJECT_ID('CNF_Attribute')
			)
BEGIN
	CREATE INDEX Idx_Attribute_AttTemplateId ON [CNF_Attribute] ([AttributeTemplateId])	
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT  TOP 1 COUNT(*)
				FROM    sys.index_columns AS ic
						INNER JOIN sys.indexes AS i		            ON ic.[object_id] = i.[object_id]
																		AND ic.index_id = i.index_id
						INNER JOIN sys.columns AS c                 ON ic.[object_id] = c.[object_id]
																		AND ic.column_id = c.column_id

				WHERE   ic.[object_id] = OBJECT_ID(N'dbo.DATA_Account')
				  AND   i.[type] != 0
				  AND   ic.is_included_column = 0
				GROUP BY i.index_id
					HAVING  COUNT(CASE WHEN c.Name = 'EmailAddress1' THEN 1 END) &gt; 0
				ORDER BY 1
			   )
BEGIN
	IF NOT EXISTS (SELECT * 
                 FROM sys.indexes 
                WHERE name='Idx_Account_Login' AND object_id = OBJECT_ID('DATA_Account')
			  )
	BEGIN
		CREATE INDEX Idx_Account_Login on [DATA_Account] ([EmailAddress1])
	END;
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT> IF NOT EXISTS (SELECT * 
                FROM sys.indexes 
            WHERE name='Idx_TriggerItem_TriggerManagerFull' AND object_id = OBJECT_ID('DATA_TriggerItem')
			)
BEGIN
	CREATE INDEX Idx_TriggerItem_TriggerManagerFull ON [DATA_TriggerItem] ([TriggerType], [EntityTable], [EntityId], [ListenerType])	
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT  TOP 1 COUNT(*)
				FROM    sys.index_columns AS ic
						INNER JOIN sys.indexes AS i		            ON ic.[object_id] = i.[object_id]
																		AND ic.index_id = i.index_id
						INNER JOIN sys.columns AS c                 ON ic.[object_id] = c.[object_id]
																		AND ic.column_id = c.column_id

				WHERE   ic.[object_id] = OBJECT_ID(N'dbo.DATA_TriggerItem')
				  AND   i.[type] != 0
				  AND   ic.is_included_column = 0
				GROUP BY i.index_id
					HAVING  COUNT(CASE WHEN c.Name = 'DocTemplateId' THEN 1 END) &gt; 0
				ORDER BY 1
			   )
BEGIN
	IF NOT EXISTS (SELECT * 
                 FROM sys.indexes 
                WHERE name='Idx_TriggerItem_DocTemplateId' AND object_id = OBJECT_ID('DATA_TriggerItem')
			  )
	BEGIN
		CREATE INDEX Idx_TriggerItem_DocTemplateId ON [DATA_TriggerItem] ([DocTemplateId])	
	END;
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>  IF NOT EXISTS (SELECT  TOP 1 COUNT(*)
				FROM    sys.index_columns AS ic
						INNER JOIN sys.indexes AS i		            ON ic.[object_id] = i.[object_id]
																		AND ic.index_id = i.index_id
						INNER JOIN sys.columns AS c                 ON ic.[object_id] = c.[object_id]
																		AND ic.column_id = c.column_id

				WHERE   ic.[object_id] = OBJECT_ID(N'dbo.DATA_TransactionItemRule')
				  AND   i.[type] != 0
				  AND   ic.is_included_column = 0
				GROUP BY i.index_id
					HAVING  COUNT(CASE WHEN c.Name = 'PromotionItemRuleId' THEN 1 END) &gt; 0
				ORDER BY 1
			   )
BEGIN
	IF NOT EXISTS (SELECT * 
                 FROM sys.indexes 
                WHERE name='Idx_TransItemRule_PromoItemRuleId' AND object_id = OBJECT_ID('DATA_TransactionItemRule')
			  )
	BEGIN
		CREATE INDEX Idx_TransItemRule_PromoItemRuleId ON [DATA_TransactionItemRule] ([PromotionItemRuleId])	
	END;
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                FROM sys.indexes 
            WHERE name='Idx_Transaction_WksId_Completed' AND object_id = OBJECT_ID('DATA_Transaction')
			)
BEGIN
	CREATE INDEX Idx_Transaction_WksId_Completed on [DATA_Transaction] ([WorkstationId], [Completed]) INCLUDE ([SaleId])		
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT  TOP 1 COUNT(*)
				FROM    sys.index_columns AS ic
						INNER JOIN sys.indexes AS i		            ON ic.[object_id] = i.[object_id]
																		AND ic.index_id = i.index_id
						INNER JOIN sys.columns AS c                 ON ic.[object_id] = c.[object_id]
																		AND ic.column_id = c.column_id

				WHERE   ic.[object_id] = OBJECT_ID(N'dbo.CNF_StatisticalGroupValidity')
				  AND   i.[type] != 0
				  AND   ic.is_included_column = 0
				GROUP BY i.index_id
					HAVING  COUNT(CASE WHEN c.Name = 'MatrixCellId' THEN 1 END) &gt; 0
				ORDER BY 1
			   )
BEGIN
	IF NOT EXISTS (SELECT * 
                 FROM sys.indexes 
                WHERE name='idx_StatGroupVal_MCId' AND object_id = OBJECT_ID('CNF_StatisticalGroupValidity')
			  )
	BEGIN
		CREATE INDEX idx_StatGroupVal_MCId on [CNF_StatisticalGroupValidity] ([MatrixCellId])
	END;
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT  TOP 1 COUNT(*)
				FROM    sys.index_columns AS ic
						INNER JOIN sys.indexes AS i		            ON ic.[object_id] = i.[object_id]
																		AND ic.index_id = i.index_id
						INNER JOIN sys.columns AS c                 ON ic.[object_id] = c.[object_id]
																		AND ic.column_id = c.column_id

				WHERE   ic.[object_id] = OBJECT_ID(N'dbo.CNF_StatisticalGroupValidity')
				  AND   i.[type] != 0
				  AND   ic.is_included_column = 0
				GROUP BY i.index_id
					HAVING  COUNT(CASE WHEN c.Name = 'StatisticalGroupId' THEN 1 END) &gt; 0
				ORDER BY 1
			   )
BEGIN
	IF NOT EXISTS (SELECT * 
                 FROM sys.indexes 
                WHERE name='idx_StatGroupVal_Id' AND object_id = OBJECT_ID('CNF_StatisticalGroupValidity')
			  )
	BEGIN
		CREATE INDEX idx_StatGroupVal_Id on [CNF_StatisticalGroupValidity] ([StatisticalGroupId]) INCLUDE ([MatrixCellId])
	END;
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                FROM sys.indexes 
            WHERE name='idx_SpaceStructure_Type' AND object_id = OBJECT_ID('CNF_SpaceStructure')
			)
BEGIN
	CREATE INDEX idx_SpaceStructure_Type on [CNF_SpaceStructure] ([SpaceStructureType]) INCLUDE ([PerformanceId])		
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT  TOP 1 COUNT(*)
				FROM    sys.index_columns AS ic
						INNER JOIN sys.indexes AS i		            ON ic.[object_id] = i.[object_id]
																		AND ic.index_id = i.index_id
						INNER JOIN sys.columns AS c                 ON ic.[object_id] = c.[object_id]
																		AND ic.column_id = c.column_id

				WHERE   ic.[object_id] = OBJECT_ID(N'dbo.CNF_SpaceStructure')
				  AND   i.[type] != 0
				  AND   ic.is_included_column = 0
				GROUP BY i.index_id
					HAVING  COUNT(CASE WHEN c.Name = 'ParentId' THEN 1 END) &gt; 0
				ORDER BY 1
			   )
BEGIN
	IF NOT EXISTS (SELECT * 
                 FROM sys.indexes 
                WHERE name='idx_SpaceStructure_ParentId' AND object_id = OBJECT_ID('CNF_SpaceStructure')
			  )
	BEGIN
		CREATE INDEX idx_SpaceStructure_ParentId on [CNF_SpaceStructure] ([ParentId])
	END;
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>  IF NOT EXISTS (SELECT  TOP 1 COUNT(*)
				FROM    sys.index_columns AS ic
						INNER JOIN sys.indexes AS i		            ON ic.[object_id] = i.[object_id]
																		AND ic.index_id = i.index_id
						INNER JOIN sys.columns AS c                 ON ic.[object_id] = c.[object_id]
																		AND ic.column_id = c.column_id

				WHERE   ic.[object_id] = OBJECT_ID(N'dbo.CNF_SpaceStructure')
				  AND   i.[type] != 0
				  AND   ic.is_included_column = 0
				GROUP BY i.index_id
					HAVING  COUNT(CASE WHEN c.Name = 'IsSeat' THEN 1 END) &gt; 0
				ORDER BY 1
			   )
BEGIN
	IF NOT EXISTS (SELECT * 
                 FROM sys.indexes 
                WHERE name='idx_SpaceStructure_IsSeat' AND object_id = OBJECT_ID('CNF_SpaceStructure')
			  )
	BEGIN
		CREATE INDEX idx_SpaceStructure_IsSeat on [CNF_SpaceStructure] ([IsSeat])
	END;
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT  TOP 1 COUNT(*)
				FROM    sys.index_columns AS ic
						INNER JOIN sys.indexes AS i		            ON ic.[object_id] = i.[object_id]
																		AND ic.index_id = i.index_id
						INNER JOIN sys.columns AS c                 ON ic.[object_id] = c.[object_id]
																		AND ic.column_id = c.column_id

				WHERE   ic.[object_id] = OBJECT_ID(N'dbo.CNF_SpaceStructure')
				  AND   i.[type] != 0
				  AND   ic.is_included_column = 0
				GROUP BY i.index_id
					HAVING  COUNT(CASE WHEN c.Name = 'SpaceStructureAK' THEN 1 END) &gt; 0
				ORDER BY 1
			   )
BEGIN
	IF NOT EXISTS (SELECT * 
                 FROM sys.indexes 
                WHERE name='idx_SpaceStructure_Ak' AND object_id = OBJECT_ID('CNF_SpaceStructure')
			  )
	BEGIN
		CREATE INDEX idx_SpaceStructure_Ak on [CNF_SpaceStructure] ([SpaceStructureAK])
	END;
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                FROM sys.indexes 
            WHERE name='idx_SeatCategory_AttId_TempId' AND object_id = OBJECT_ID('CNF_SeatCategory')
			)
BEGIN
	CREATE INDEX idx_SeatCategory_AttId_TempId on [CNF_SeatCategory] ([AttributeId], [Temp_SeatCategoryId])		
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT  TOP 1 COUNT(*)
				FROM    sys.index_columns AS ic
						INNER JOIN sys.indexes AS i		            ON ic.[object_id] = i.[object_id]
																		AND ic.index_id = i.index_id
						INNER JOIN sys.columns AS c                 ON ic.[object_id] = c.[object_id]
																		AND ic.column_id = c.column_id

				WHERE   ic.[object_id] = OBJECT_ID(N'dbo.RES_ScheduleDetail')
				  AND   i.[type] != 0
				  AND   ic.is_included_column = 0
				GROUP BY i.index_id
					HAVING  COUNT(CASE WHEN c.Name = 'ScheduleId' THEN 1 END) &gt; 0
				ORDER BY 1
			   )
BEGIN
	IF NOT EXISTS (SELECT * 
                 FROM sys.indexes 
                WHERE name='Idx_ScheduleDetail_ScheduleId' AND object_id = OBJECT_ID('RES_ScheduleDetail')
			  )
	BEGIN
		CREATE INDEX Idx_ScheduleDetail_ScheduleId on [RES_ScheduleDetail] ([ScheduleId])
	END;
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT  TOP 1 COUNT(*)
				FROM    sys.index_columns AS ic
						INNER JOIN sys.indexes AS i		            ON ic.[object_id] = i.[object_id]
																		AND ic.index_id = i.index_id
						INNER JOIN sys.columns AS c                 ON ic.[object_id] = c.[object_id]
																		AND ic.column_id = c.column_id

				WHERE   ic.[object_id] = OBJECT_ID(N'dbo.RES_ScheduleDetail')
				  AND   i.[type] != 0
				  AND   ic.is_included_column = 0
				GROUP BY i.index_id
					HAVING  COUNT(CASE WHEN c.Name = 'PerformanceId' THEN 1 END) &gt; 0
				ORDER BY 1
			   )
BEGIN
	IF NOT EXISTS (SELECT * 
                 FROM sys.indexes 
                WHERE name='Idx_ScheduleDetail_PerfId' AND object_id = OBJECT_ID('RES_ScheduleDetail')
			  )
	BEGIN
		CREATE INDEX Idx_ScheduleDetail_PerfId on [RES_ScheduleDetail] ([PerformanceId])
	END;
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT  TOP 1 COUNT(*)
				FROM    sys.index_columns AS ic
						INNER JOIN sys.indexes AS i		            ON ic.[object_id] = i.[object_id]
																		AND ic.index_id = i.index_id
						INNER JOIN sys.columns AS c                 ON ic.[object_id] = c.[object_id]
																		AND ic.column_id = c.column_id

				WHERE   ic.[object_id] = OBJECT_ID(N'dbo.DATA_SaleItem2Performance')
				  AND   i.[type] != 0
				  AND   ic.is_included_column = 0
				GROUP BY i.index_id
					HAVING  COUNT(CASE WHEN c.Name = 'EnvelopeCapacityId' THEN 1 END) &gt; 0
				ORDER BY 1
			   )
BEGIN
	IF NOT EXISTS (SELECT * 
                 FROM sys.indexes 
                WHERE name='Idx_SaleItem2Perf_EnvCapId' AND object_id = OBJECT_ID('DATA_SaleItem2Performance')
			  )
	BEGIN
		CREATE INDEX Idx_SaleItem2Perf_EnvCapId ON [DATA_SaleItem2Performance] ([EnvelopeCapacityId])	
	END;
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT  TOP 1 COUNT(*)
				FROM    sys.index_columns AS ic
						INNER JOIN sys.indexes AS i		            ON ic.[object_id] = i.[object_id]
																		AND ic.index_id = i.index_id
						INNER JOIN sys.columns AS c                 ON ic.[object_id] = c.[object_id]
																		AND ic.column_id = c.column_id

				WHERE   ic.[object_id] = OBJECT_ID(N'dbo.DATA_SaleItem2CostCenter')
				  AND   i.[type] != 0
				  AND   ic.is_included_column = 0
				GROUP BY i.index_id
					HAVING  COUNT(CASE WHEN c.Name = 'TransactionId' THEN 1 END) &gt; 0
				ORDER BY 1
			   )
BEGIN
	IF NOT EXISTS (SELECT * 
                 FROM sys.indexes 
                WHERE name='Idx_SaleItem2CostCenter_TransId' AND object_id = OBJECT_ID('DATA_SaleItem2CostCenter')
			  )
	BEGIN
		CREATE INDEX Idx_SaleItem2CostCenter_TransId on [DATA_SaleItem2CostCenter] ([TransactionId])
	END;
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT  TOP 1 COUNT(*)
				FROM    sys.index_columns AS ic
						INNER JOIN sys.indexes AS i		            ON ic.[object_id] = i.[object_id]
																		AND ic.index_id = i.index_id
						INNER JOIN sys.columns AS c                 ON ic.[object_id] = c.[object_id]
																		AND ic.column_id = c.column_id

				WHERE   ic.[object_id] = OBJECT_ID(N'dbo.DATA_SaleCoupon')
				  AND   i.[type] != 0
				  AND   ic.is_included_column = 0
				GROUP BY i.index_id
					HAVING  COUNT(CASE WHEN c.Name = 'SaleItemId' THEN 1 END) &gt; 0
				ORDER BY 1
			   )
BEGIN
	IF NOT EXISTS (SELECT * 
                 FROM sys.indexes 
                WHERE name='Idx_SaleCoupon_SaleItemId' AND object_id = OBJECT_ID('DATA_SaleCoupon')
			  )
	BEGIN
		CREATE INDEX Idx_SaleCoupon_SaleItemId ON [DATA_SaleCoupon] ([SaleItemId])		
	END;
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                FROM sys.indexes 
            WHERE name='Idx_SaleCoupon_Id' AND object_id = OBJECT_ID('DATA_SaleCoupon')
			)
BEGIN
	CREATE INDEX Idx_SaleCoupon_Id ON [DATA_SaleCoupon] ([CouponId])		
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                FROM sys.indexes 
            WHERE name='Idx_SaleCoupon_CouponId_SaleItemId' AND object_id = OBJECT_ID('DATA_SaleCoupon')
			)
BEGIN
	CREATE INDEX Idx_SaleCoupon_CouponId_SaleItemId ON [DATA_SaleCoupon] ([CouponId], [SaleItemId])	
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT  TOP 1 COUNT(*)
				FROM    sys.index_columns AS ic
						INNER JOIN sys.indexes AS i		            ON ic.[object_id] = i.[object_id]
																		AND ic.index_id = i.index_id
						INNER JOIN sys.columns AS c                 ON ic.[object_id] = c.[object_id]
																		AND ic.column_id = c.column_id

				WHERE   ic.[object_id] = OBJECT_ID(N'dbo.DATA_Sale')
				  AND   i.[type] != 0
				  AND   ic.is_included_column = 0
				GROUP BY i.index_id
					HAVING  COUNT(CASE WHEN c.Name = 'UserId' THEN 1 END) &gt; 0
				ORDER BY 1
			   )
BEGIN
	IF NOT EXISTS (SELECT * 
                 FROM sys.indexes 
                WHERE name='Idx_Sale_UserId' AND object_id = OBJECT_ID('DATA_Sale')
			  )
	BEGIN
		CREATE INDEX Idx_Sale_UserId on [DATA_Sale] ([UserId])
	END;
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT> IF NOT EXISTS (SELECT  TOP 1 COUNT(*)
				FROM    sys.index_columns AS ic
						INNER JOIN sys.indexes AS i		            ON ic.[object_id] = i.[object_id]
																		AND ic.index_id = i.index_id
						INNER JOIN sys.columns AS c                 ON ic.[object_id] = c.[object_id]
																		AND ic.column_id = c.column_id

				WHERE   ic.[object_id] = OBJECT_ID(N'dbo.DATA_Sale')
				  AND   i.[type] != 0
				  AND   ic.is_included_column = 0
				GROUP BY i.index_id
					HAVING  COUNT(CASE WHEN c.Name = 'RefAccountId' THEN 1 END) &gt; 0
				ORDER BY 1
			   )
BEGIN
	IF NOT EXISTS (SELECT * 
                 FROM sys.indexes 
                WHERE name='Idx_Sale_RefAccId' AND object_id = OBJECT_ID('DATA_Sale')
			  )
	BEGIN
		CREATE INDEX Idx_Sale_RefAccId on [DATA_Sale] ([RefAccountId])
	END;
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                FROM sys.indexes 
            WHERE name='Idx_Right_SourceTyte_SourceId' AND object_id = OBJECT_ID('DATA_Right')
			)
BEGIN
	CREATE INDEX Idx_Right_SourceTyte_SourceId on [DATA_Right] ([SourceType], [SourceId])		
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT> IF NOT EXISTS (SELECT * 
                FROM sys.indexes 
            WHERE name='Idx_Right_Full' AND object_id = OBJECT_ID('DATA_Right')
			)
BEGIN
	CREATE INDEX Idx_Right_Full on [DATA_Right] ([SourceType], [SourceId]) INCLUDE ([RightId], [DestType], [StrValue], [DestId])		
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                FROM sys.indexes 
            WHERE name='Idx_Right_DestType_DestId' AND object_id = OBJECT_ID('DATA_Right')
			)
BEGIN
	CREATE INDEX Idx_Right_DestType_DestId on [DATA_Right] ([DestType], [DestId])		
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT> IF NOT EXISTS (SELECT  TOP 1 COUNT(*)
				FROM    sys.index_columns AS ic
						INNER JOIN sys.indexes AS i		            ON ic.[object_id] = i.[object_id]
																		AND ic.index_id = i.index_id
						INNER JOIN sys.columns AS c                 ON ic.[object_id] = c.[object_id]
																		AND ic.column_id = c.column_id

				WHERE   ic.[object_id] = OBJECT_ID(N'dbo.SIAE_Riepiloghi')
				  AND   i.[type] != 0
				  AND   ic.is_included_column = 0
				GROUP BY i.index_id
					HAVING  COUNT(CASE WHEN c.Name = 'Nome' THEN 1 END) &gt; 0
				ORDER BY 1
			   )
BEGIN
	IF NOT EXISTS (SELECT * 
                 FROM sys.indexes 
                WHERE name='Idx_Riepiloghi_Nome' AND object_id = OBJECT_ID('SIAE_Riepiloghi')
			  )
	BEGIN
		CREATE INDEX Idx_Riepiloghi_Nome ON [SIAE_Riepiloghi] ([Nome])	
	END;
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                FROM sys.indexes 
            WHERE name='Idx_Riepiloghi_Data_Tipo_Stato' AND object_id = OBJECT_ID('SIAE_Riepiloghi')
			)
BEGIN
	CREATE INDEX Idx_Riepiloghi_Data_Tipo_Stato ON [SIAE_Riepiloghi] ([DataRiferimento], [Tipo], [Stato])	
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                FROM sys.indexes 
            WHERE name='Idx_Riepiloghi_Data_Tipo' AND object_id = OBJECT_ID('SIAE_Riepiloghi')
			)
BEGIN
	CREATE INDEX Idx_Riepiloghi_Data_Tipo ON [SIAE_Riepiloghi] ([DataRiferimento], [Tipo])	
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                FROM sys.indexes 
            WHERE name='Idx_Res_Transaction_TransId_WksId' AND object_id = OBJECT_ID('RES_Data_Transaction')
			)
BEGIN
	CREATE INDEX Idx_Res_Transaction_TransId_WksId ON [RES_Data_Transaction] ([TransactionId], [WorkstationId])	
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT  TOP 1 COUNT(*)
				FROM    sys.index_columns AS ic
						INNER JOIN sys.indexes AS i		            ON ic.[object_id] = i.[object_id]
																		AND ic.index_id = i.index_id
						INNER JOIN sys.columns AS c                 ON ic.[object_id] = c.[object_id]
																		AND ic.column_id = c.column_id

				WHERE   ic.[object_id] = OBJECT_ID(N'dbo.CNF_MatrixCell_Renew')
				  AND   i.[type] != 0
				  AND   ic.is_included_column = 0
				GROUP BY i.index_id
					HAVING  COUNT(CASE WHEN c.Name = 'MatrixCellId' THEN 1 END) &gt; 0
				ORDER BY 1
			   )
BEGIN
	IF NOT EXISTS (SELECT * 
                 FROM sys.indexes 
                WHERE name='idx_Renew_McId' AND object_id = OBJECT_ID('CNF_MatrixCell_Renew')
			  )
	BEGIN
		CREATE INDEX idx_Renew_McId on [CNF_MatrixCell_Renew] ([MatrixCellId])
	END;
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT> IF NOT EXISTS (SELECT  TOP 1 COUNT(*)
				FROM    sys.index_columns AS ic
						INNER JOIN sys.indexes AS i		            ON ic.[object_id] = i.[object_id]
																		AND ic.index_id = i.index_id
						INNER JOIN sys.columns AS c                 ON ic.[object_id] = c.[object_id]
																		AND ic.column_id = c.column_id

				WHERE   ic.[object_id] = OBJECT_ID(N'dbo.CNF_PromotionItem')
				  AND   i.[type] != 0
				  AND   ic.is_included_column = 0
				GROUP BY i.index_id
					HAVING  COUNT(CASE WHEN c.Name = 'PromotionId' THEN 1 END) &gt; 0
				ORDER BY 1
			   )
BEGIN
	IF NOT EXISTS (SELECT * 
                 FROM sys.indexes 
                WHERE name='Idx_PromotionItem_PromoId' AND object_id = OBJECT_ID('CNF_PromotionItem')
			  )
	BEGIN
		CREATE INDEX Idx_PromotionItem_PromoId ON [CNF_PromotionItem] ([PromotionId])	
	END;
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT  TOP 1 COUNT(*)
				FROM    sys.index_columns AS ic
						INNER JOIN sys.indexes AS i		            ON ic.[object_id] = i.[object_id]
																		AND ic.index_id = i.index_id
						INNER JOIN sys.columns AS c                 ON ic.[object_id] = c.[object_id]
																		AND ic.column_id = c.column_id

				WHERE   ic.[object_id] = OBJECT_ID(N'dbo.CNF_PromotionProduct')
				  AND   i.[type] != 0
				  AND   ic.is_included_column = 0
				GROUP BY i.index_id
					HAVING  COUNT(CASE WHEN c.Name = 'PromotionItemRuleId' THEN 1 END) &gt; 0
				ORDER BY 1
			   )
BEGIN
	IF NOT EXISTS (SELECT * 
                 FROM sys.indexes 
                WHERE name='Idx_PromoProduct_ItemRuleId' AND object_id = OBJECT_ID('CNF_PromotionProduct')
			  )
	BEGIN
		CREATE INDEX Idx_PromoProduct_ItemRuleId on [CNF_PromotionProduct] ([PromotionItemRuleId])
	END;
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                FROM sys.indexes 
            WHERE name='Idx_ProductValidity_Full' AND object_id = OBJECT_ID('CNF_ProductValidity')
			)
BEGIN
	CREATE INDEX Idx_ProductValidity_Full on [CNF_ProductValidity] ([ReferenceTable]) INCLUDE ([ReferenceId], [ValidityXML])
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT> IF NOT EXISTS (SELECT * 
                FROM sys.indexes 
            WHERE name='Idx_PerfSaleValidity_PerfId_WksId' AND object_id = OBJECT_ID('CNF_Performance_SaleValidity')
			)
BEGIN
	CREATE INDEX Idx_PerfSaleValidity_PerfId_WksId on [CNF_Performance_SaleValidity] ([PerformanceId], [WorkstationId])
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                FROM sys.indexes 
            WHERE name='Idx_Performance_PerfDateTime' AND object_id = OBJECT_ID('CNF_Performance')
			)
BEGIN
	CREATE INDEX Idx_Performance_PerfDateTime on [CNF_Performance] ([PerfDateTime])
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                FROM sys.indexes 
            WHERE name='idx_Performance_EventId_AccConfigId' AND object_id = OBJECT_ID('CNF_Performance')
			)
BEGIN
	CREATE INDEX idx_Performance_EventId_AccConfigId on [CNF_Performance] ([EventId], [AccessConfigurationId])
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>  IF NOT EXISTS (SELECT * 
                FROM sys.indexes 
            WHERE name='idx_Performance_aptCache' AND object_id = OBJECT_ID('CNF_Performance')
			)
BEGIN
	CREATE INDEX idx_Performance_aptCache on [CNF_Performance] ([AccessConfigurationId], [OpeningTime], [ClosingTime]) INCLUDE ([EventId], [PerformanceAK], [PerfDateTime], [Status], [TimeOpening], [TimeLimit], [PerformanceEnd], [MoneyCardId], [MoneyCardCost], [PerformanceCode], [PerformanceName])		
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT  TOP 1 COUNT(*)
				FROM    sys.index_columns AS ic
						INNER JOIN sys.indexes AS i		            ON ic.[object_id] = i.[object_id]
																		AND ic.index_id = i.index_id
						INNER JOIN sys.columns AS c                 ON ic.[object_id] = c.[object_id]
																		AND ic.column_id = c.column_id

				WHERE   ic.[object_id] = OBJECT_ID(N'dbo.CNF_PerformanceCategoryValidity')
				  AND   i.[type] != 0
				  AND   ic.is_included_column = 0
				GROUP BY i.index_id
					HAVING  COUNT(CASE WHEN c.Name = 'PerformanceId' THEN 1 END) &gt; 0
				ORDER BY 1
			   )
BEGIN
	IF NOT EXISTS (SELECT * 
                 FROM sys.indexes 
                WHERE name='Idx_PerfCatValidity_PerfId' AND object_id = OBJECT_ID('CNF_PerformanceCategoryValidity')
			  )
	BEGIN
		CREATE INDEX Idx_PerfCatValidity_PerfId on [CNF_PerformanceCategoryValidity] ([PerformanceId])
	END;
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                FROM sys.indexes 
            WHERE name='Idx_PerfCatValidity_EventId_PerfId' AND object_id = OBJECT_ID('CNF_PerformanceCategoryValidity')
			)
BEGIN
	CREATE INDEX Idx_PerfCatValidity_EventId_PerfId on [CNF_PerformanceCategoryValidity] ([EventId], [PerformanceId])
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>	IF NOT EXISTS (SELECT * 
                 FROM sys.indexes 
                WHERE name='Idx_Note_Type_Key' AND object_id = OBJECT_ID('DATA_Note')
			  )
	BEGIN
		CREATE INDEX Idx_Note_Type_Key on [DATA_Note] ([NoteType]) INCLUDE ([NoteKey])
	END;</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dchen</ADDEDBY><SQLVERSION>3245</SQLVERSION><RMTRACKLINK>IDBOS-2795</RMTRACKLINK><REASON>Adding field UserEmail</REASON><TABLENAMES>CNF_User=UserId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'UserEmail' 
                      AND OBJECT_ID = OBJECT_ID(N'CNF_User'))
BEGIN
  ALTER TABLE CNF_User 
  ADD UserEmail NVarChar(200) null;     
END </SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3244</SQLVERSION><RMTRACKLINK>IDBOS-165</RMTRACKLINK><REASON>0 - Created New Table DATA_AccountTemporaryPasswords
1 - Added Foreign Key on AccountId</REASON><TABLENAMES>DATA_AccountTemporaryPasswords=PasswordId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND TABLE_NAME = 'DATA_AccountTemporaryPasswords')
BEGIN
	CREATE TABLE [DATA_AccountTemporaryPasswords]
	(
		[PasswordId] Integer IDENTITY(1,1) NOT NULL,
		[AccountId] Integer NOT NULL,
		[PasswordType] Integer NOT NULL,
		[Password] Nvarchar(100) NOT NULL,
		[Expiry] Datetime NOT NULL,
		[Counter] Integer NOT NULL,
		Primary Key ([PasswordId])
     )
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_AccountTemporaryPasswords_AccountId')
BEGIN
  ALTER TABLE [DATA_AccountTemporaryPasswords]
  WITH CHECK ADD CONSTRAINT FK_DATA_AccountTemporaryPasswords_AccountId FOREIGN KEY(AccountId) 
  REFERENCES [DATA_ACCOUNT] ([AccountId])
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dchen</ADDEDBY><SQLVERSION>3243</SQLVERSION><RMTRACKLINK>IDBOS-2795</RMTRACKLINK><REASON>Need ability to add a Task to an Account
  * Add TaskStatus Table: Customizeable Task Status List
  * Insert Default Status</REASON><TABLENAMES>CNF_TaskStatus=TaskStatusId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID('CNF_TaskStatus') AND type in ('U'))
BEGIN
  CREATE TABLE [dbo].[CNF_TaskStatus](
	[TaskStatusId] [int] IDENTITY(1,1) NOT NULL, UNIQUE (TaskStatusId),
	[Code] [nchar](20) NOT NULL,
	[Description] [nchar](50) NULL,
	[Notify] [smallint] NULL,
	[SortOrder] [int] NOT NULL, 
	[Enabled] [smallint] NULL,
	[IsSystem] [smallint] NULL,
  PRIMARY KEY (TaskStatusId)
  )

  CREATE INDEX IX_CNF_TaskStatus_SortOrder ON CNF_TaskStatus (SortOrder, Code)

  CREATE UNIQUE INDEX IX_CNF_TaskStatus_Code ON CNF_TaskStatus (Code)
  
  INSERT INTO CNF_TaskStatus(Code, Description, Notify, SortOrder, Enabled, IsSystem) VALUES ('Open', 'Open', 1, 1, 1, 1)

  INSERT INTO CNF_TaskStatus(Code, Description, Notify, SortOrder, Enabled, IsSystem) VALUES ('In Progress', 'In Progress', 1, 50, 1, 1)

  INSERT INTO CNF_TaskStatus(Code, Description, Notify, SortOrder, Enabled, IsSystem) VALUES ('Completed', 'Completed', 0, 100, 1, 1)  
END


</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>ecandido</ADDEDBY><SQLVERSION>3242</SQLVERSION><RMTRACKLINK>IDBOS-369</RMTRACKLINK><REASON>Create New table "PaymentMethod2MatrixCell

[0] Create Table CNF_PaymentMethod2MatrixCell
[1] Create Index
[2] Delete trigger for History Log
[3] Create trigger for History Log</REASON><TABLENAMES>CNF_PaymentMethod2MatrixCell=PaymentMethod2MatricCellId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID('CNF_PaymentMethod2MatrixCell') AND type in ('U'))
BEGIN
	Create table CNF_PaymentMethod2MatrixCell
        (
          PaymentMethod2MatricCellId Integer Identity(1,1) NOT NULL,
          PaymentMethodId Integer NOT NULL,
          MatrixCellId Integer NOT NULL,
          UserId Integer NULL,
          WorkstationId Integer NULL,
          Last_DateTime_Log Datetime NULL,
          Primary Key (PaymentMethod2MatricCellId)
        )
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT 1
            FROM sys.indexes I
                INNER JOIN sys.tables T
                    ON I.object_id = T.object_id
                INNER JOIN sys.schemas S
                    ON S.schema_id = T.schema_id
            WHERE I.Name = 'Idx_PayMet2MatrixCell_MetId_MatrixCellId' -- Index name
                AND T.Name = 'CNF_PaymentMethod2MatrixCell' -- Table name
                AND S.Name = 'dbo') --Schema Name
BEGIN
    create Index Idx_PayMet2MatrixCell_MetId_MatrixCellId ON CNF_PaymentMethod2MatrixCell (PaymentMethodId ,MatrixCellId )
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[CNF_PaymentMethod2MatrixCell_CT]'))
  DROP TRIGGER [dbo].[CNF_PaymentMethod2MatrixCell_CT]</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>create trigger [dbo].[CNF_PaymentMethod2MatrixCell_CT] on [dbo].[CNF_PaymentMethod2MatrixCell] FOR insert, update, delete
        		as
        		declare @TName varchar(128),
        		        @TID nvarchar(max),
        				@TLog int,  
        				@PKC varchar(max),
        				@PKV varchar(max),  
        				@sql nvarchar(max), 
        				@Type nvarchar(1),
        				@MId nvarchar(max) = '0', 
        				@ColumnID nvarchar(max) = '0',
        				@CName varchar(128),
        				@CValue1 nvarchar(max),
        				@CValue2 nvarchar(max)
        
        		if exists(select top 1 1 from cnf_system where ISNULL(BOSHistoryLogEnabled, 1) = 1 and offlinemode = 0)
        		BEGIN
        			select @TName = 'CNF_PaymentMethod2MatrixCell', @TID=dbtableid, @TLog = (case when Active = 1 and Logged = 1 then 1 else 0 end) from cnf_dbtable WITH(NOLOCK) where TableName='CNF_PaymentMethod2MatrixCell'
        
        			if @TLog = 1
        			begin
        				if exists (select * from inserted)
        				if exists (select * from deleted)
        				select @Type = '2'      --Update
        				else
        				select @Type = '3'      --Insert
        				else
        				select @Type = '1'      --Delete
        
        				select * into #ins from inserted
        				select * into #del from deleted
        
        				select @PKC = coalesce(@PKC + ' and', ' on') + ' i.' + c.COLUMN_NAME + ' = d.' + c.COLUMN_NAME, @PKV = coalesce(@PKV+'+','') + 'convert(varchar(100), coalesce(i.' + COLUMN_NAME + ',d.' + COLUMN_NAME + '))'
        				  from INFORMATION_SCHEMA.TABLE_CONSTRAINTS p WITH(NOLOCK)
        					   INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE c WITH(NOLOCK) on c.CONSTRAINT_NAME = p.CONSTRAINT_NAME and c.TABLE_NAME = p.TABLE_NAME
        				 where p.TABLE_NAME=@TName and CONSTRAINT_TYPE='PRIMARY KEY'
        
        				DECLARE TCursor CURSOR LOCAL FOR
        								select columnName,
        									   dbcolumnid
        								from(
        								select CNF_DBColumn.ColumnName,
        									CNF_DBColumn.DBColumnId,
        									(case when cnf_dbcolumn.Active = 1 and cnf_dbcolumn.Logged = 1 then 1 else 0 end) Active
        									from sys.tables AS t WITH(NOLOCK)				
        										INNER JOIN sys.columns c WITH(NOLOCK)				ON t.OBJECT_ID = c.OBJECT_ID 
        										INNER JOIN cnf_dbtable WITH(NOLOCK)					on cnf_dbtable.tablename = t.name
        										INNER JOIN cnf_dbcolumn WITH(NOLOCK)				on cnf_dbcolumn.dbtableid = cnf_dbtable.dbtableid and cnf_dbcolumn.columnname = c.name
        								where cnf_dbcolumn.dbtableid = @TID
        								)p
        								where Active = 1
        
        				OPEN TCursor
        
        				FETCH NEXT FROM TCursor INTO
        					@CName, @ColumnID
        					
        				WHILE @@FETCH_STATUS = 0
        				BEGIN
        
        					set @sql ='Select @CValue1 = ' + @CName +' from #ins '
        					EXEC sp_executesql @sql, N'@CValue1 nvarchar(max) OUTPUT', @CValue1 OUTPUT
        
        					set @sql ='Select @CValue2 = ' + @CName +' from #del '
        					EXEC sp_executesql @sql, N'@CValue2 nvarchar(max) OUTPUT', @CValue2 OUTPUT
        
        					if ISNULL(@CValue1, '&amp;*()_2') &lt;&gt; ISNULL(@CValue2, '&amp;*()_2')
        					begin
        						if @MId = 0
        						begin
        							set @sql = 'insert DATA_HL_Master (OperationType, dbtableid, ReferenceId, UserId, WorkstationId, InsDateTime, DelDateTime)'
        							set @sql = @sql + ' select ''' + @Type + ''''												
        							set @sql = @sql + ', ''' + @TID + ''''		
        							set @sql = @sql + ',' + @PKV		
        							set @sql = @sql + ', i.Last_UserId_Log, i.Last_WorkstationId_Log, i.Last_DateTime_Log, getdate()'
        							set @sql = @sql + ' from #ins i full outer join #del d '
        							set @sql = @sql + @PKC 
        							set @sql = @sql + ' SELECT @MId = SCOPE_IDENTITY()'
        							EXEC sp_executesql @sql, N'@MId nvarchar(max) OUTPUT', @MId OUTPUT
        						end
        						if @Type &lt;&gt; '3'
        						BEGIN
        							set @sql = 'insert data_HL_Detail (MasterId, OriginalValue, ModifiedValue, DBColumnID)'						
        							set @sql = @sql + ' select convert(varchar(1000),' + @MId + '), convert(varchar(1000),d.' + @CName + '), convert(varchar(1000),i.' + @CName + ')'				
        							set @sql = @sql + ', convert(varchar(1000),' + @ColumnID + ')  '
        							set @sql = @sql + ' from #ins i full outer join #del d ' + @PKC				
        							EXEC sp_executesql @sql 																	
        						END		
        						
        					END
        					FETCH NEXT FROM TCursor INTO
        					   @CName, @ColumnID
        				END  --While loop
        				CLOSE TCursor;
        				DEALLOCATE TCursor; 
        			END    --Table Check
        		END	-- System Check</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>3241</SQLVERSION><RMTRACKLINK>IDBOS-2721</RMTRACKLINK><REASON>New field on DATA_Payment: ForeignCurrencyPriceDiff</REASON><TABLENAMES>DATA_Payment=PaymentId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'ForeignCurrencyPriceDiff' 
                      AND OBJECT_ID = OBJECT_ID(N'DATA_Payment'))
BEGIN
  ALTER TABLE DATA_Payment 
  ADD ForeignCurrencyPriceDiff Float null;     
END  </SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dchen</ADDEDBY><SQLVERSION>3240</SQLVERSION><RMTRACKLINK>2795</RMTRACKLINK><REASON>IDBOS-2795 - Need ability to add a Task to an Account</REASON><TABLENAMES>DATA_Note=NoteId
DATA_NoteTask=TaskId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
          WHERE Name = N'IsTask' 
          AND OBJECT_ID = OBJECT_ID(N'DATA_Note'))
BEGIN
  ALTER TABLE DATA_Note
  ADD IsTask [smallint] NULL DEFAULT 0 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT 1
            FROM sys.indexes I
                INNER JOIN sys.tables T
                    ON I.object_id = T.object_id
                INNER JOIN sys.schemas S
                    ON S.schema_id = T.schema_id
            WHERE I.Name = 'Idx_Data_Note_IsTask' -- Index name
                AND T.Name = 'Data_Note' -- Table name
                AND S.Name = 'dbo') --Schema Name
BEGIN
    create Index Idx_Data_Note_IsTask ON Data_Note (IsTask desc, NoteId)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                  AND  TABLE_NAME = 'DATA_NoteTask'))
BEGIN
  CREATE TABLE [DATA_NoteTask](
	[TaskId] [int] IDENTITY(1,1) NOT NULL, UNIQUE (TaskId),
	[NoteId] [int] NOT NULL,
	[UserId] [int] NOT NULL,
	[DateTimeStart] [datetime] NULL,
	[DateTimeEnd] [datetime] NULL,
	[DateTimeLastUpdate] [datetime] NULL,
	[Status] [int] NOT NULL,
	[Reminder] [smallint] NULL,
	[ReminderDaysBeforeDue] [int] NULL,
	[ReminderRepeat] [int] NULL,
	[ReminderDurationMinutes] [int] NULL,
	[icsUID] [nvarchar](100) NULL,
	[icsSequence] [int] NULL,
  Primary Key (TaskId)
  )

  ALTER TABLE Data_NoteTask WITH CHECK ADD CONSTRAINT [FK_Data_Note_NoteId] FOREIGN KEY([NoteId]) REFERENCES DATA_Note ([NoteId])

  ALTER TABLE Data_NoteTask WITH CHECK ADD CONSTRAINT [FK_Data_Note_UserId] FOREIGN KEY([UserId]) REFERENCES CNF_User ([UserId])

  CREATE INDEX Idx_Data_NoteTask ON Data_NoteTask (NoteId asc)

  CREATE INDEX Idx_Data_NoteTask_DateStart ON Data_NoteTask (DateTimeStart, NoteId)

  CREATE INDEX Idx_Data_NoteTask_DateEnd ON Data_NoteTask (DateTimeEnd desc, NoteId)

  CREATE INDEX Idx_Data_NoteTask_Status ON Data_NoteTask (Status, DateTimeEnd desc)

  CREATE INDEX Idx_Data_NoteTask_User ON Data_NoteTask (UserId, Status, DateTimeEnd desc)

  CREATE INDEX Idx_Data_NoteTask_UID ON Data_NoteTask (icsUID)

END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fdipalma</ADDEDBY><SQLVERSION>3239</SQLVERSION><RMTRACKLINK>IDBOS-2958</RMTRACKLINK><REASON>Imported Voucher Enhancement</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT object_id
               FROM sys.indexes
               WHERE Name = 'Idx_IMP_MediaIdentifier_Status_ExternalCode')
BEGIN
	CREATE NONCLUSTERED INDEX [Idx_IMP_MediaIdentifier_Status_ExternalCode] ON [dbo].[IMP_MediaIdentifier]
	(
		[Status] DESC,
		[ExternalCode] DESC
	)
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>scoluccia</ADDEDBY><SQLVERSION>3238</SQLVERSION><RMTRACKLINK>IDBOS-2953</RMTRACKLINK><REASON>Added a new field Preferred in DATA_DmgDataDetails in order to manage the preferred record</REASON><TABLENAMES>DATA_DmgDataDetails=DmgDataDetailsId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
          WHERE Name = N'Preferred' 
          AND OBJECT_ID = OBJECT_ID(N'DATA_DmgDataDetails'))
BEGIN
  ALTER TABLE DATA_DmgDataDetails
  ADD Preferred [smallint] NULL 
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>3237</SQLVERSION><RMTRACKLINK>IDBOS-2721</RMTRACKLINK><REASON>New table: CNF_MatrixCell2Currency</REASON><TABLENAMES>CNF_MatrixCell2Currency=MatrixCell2CurrencyId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                  AND  TABLE_NAME = 'CNF_MatrixCell2Currency'))

BEGIN
Create table [CNF_MatrixCell2Currency]
(
	[MatrixCell2CurrencyId] Integer Identity(1,1) NOT NULL,
	[MatrixCellId] Integer NOT NULL,
	[CurrencyId] Integer NOT NULL,
	[Price] Float NULL,
	[Last_UserId_Log] Integer NULL,
	[Last_WorkstationId_Log] Integer NULL,
	[Last_DateTime_Log] Datetime NULL,
Primary Key ([MatrixCell2CurrencyId])
) 
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>3236</SQLVERSION><RMTRACKLINK>IDBOS-2939</RMTRACKLINK><REASON></REASON><TABLENAMES>DATA_Weather=WeatherId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID('DATA_Weather') AND type in ('U'))
BEGIN
	CREATE TABLE [dbo].[DATA_Weather](
		[WeatherId] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
		[Name] [nvarchar](100) NOT NULL,
		[Date_time] [datetime] NOT NULL,
		[Maximum_Temperature] [float] NULL,
		[Minimum_Temperature] [float] NULL,
		[Temperature] [float] NULL,
		[Wind_Chill] [float] NULL,
		[Heat_Index] [float] NULL,
		[Precipitation] [float] NULL,
		[Snow] [float] NULL,
		[Snow_Depth] [float] NULL,
		[Wind_Speed] [float] NULL,
		[Wind_Direction] [float] NULL,
		[Wind_Gust] [float] NULL,
		[Visibility] [float] NULL,
		[Cloud_Cover] [float] NULL,
		[Relative_Humidity] [float] NULL,
		[Conditions] [nvarchar](250) NULL
	) ON [PRIMARY]
END


</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3235</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>Regenerated stored procedure for table SIAE_SiaeLog</REASON><TABLENAMES>SIAE_SiaeLog=SiaeLogId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>select 1 from SIAE_SiaeLog with(nolock)</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3234</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>0 - Add HeldByfather To CNF_EnvelopeCapacity
1 - Set 0 to HeldByfather</REASON><TABLENAMES>CNF_EnvelopeCapacity=EnvelopeCapacityId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'HeldByFather' 
                      AND OBJECT_ID = OBJECT_ID(N'CNF_EnvelopeCapacity'))
BEGIN
alter table CNF_EnvelopeCapacity
 add HeldByFather int null
end</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT> update CNF_EnvelopeCapacity set HeldByFather = 0 where HeldByFather is Null; 
        
 alter table CNF_EnvelopeCapacity 
    alter column  HeldByFather int not null;</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>3233</SQLVERSION><RMTRACKLINK>IDBOS-2937</RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT> IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_AccountRestrictionsConversion]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_AccountRestrictionsConversion</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>pchen</ADDEDBY><SQLVERSION>3232</SQLVERSION><RMTRACKLINK>IDBOS-2770</RMTRACKLINK><REASON>Add a field named "SubscriptionName" in CNF_Performance</REASON><TABLENAMES>CNF_Performance=PerformanceId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'SubscriptionName' 
                      AND OBJECT_ID = OBJECT_ID(N'CNF_Performance'))
BEGIN
  alter table CNF_Performance 
    add SubscriptionName nvarchar(100) null;     
END    </SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>3231</SQLVERSION><RMTRACKLINK>IDBOS-2878</RMTRACKLINK><REASON></REASON><TABLENAMES>CNF_AccountRestriction2matrixcell=AccountRestriction2MatrixcellID</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'IncludeAllTickets' 
                      AND OBJECT_ID = OBJECT_ID(N'CNF_AccountRestriction2matrixcell'))
BEGIN
		INSERT INTO [dbo].[CNF_AccountRestriction2MatrixCell]
				   ([AccountRestrictionId]
				   ,[MatrixCellId]
				   ,[Last_UserId_Log]
				   ,[Last_WorkstationId_Log]
				   ,[Last_DateTime_Log]
				   ,[IncludeAllTickets])
			select AccountRestrictionid,
				   null,
				   1,
				   1,
				   getdate(),
				   1
			from CNF_AccountRestriction
			where restrictiontype = 2
			  and enabled = 1
END

</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.objects WHERE [name] = N'data_sale_SalesRestriction' AND [type] = 'TR')
BEGIN
      DROP TRIGGER [dbo].[data_sale_SalesRestriction];
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>Create trigger [dbo].[data_sale_SalesRestriction] on [dbo].[DATA_Sale] FOR update
	 as
begin
	SET NOCOUNT ON;
    IF UPDATE(Approved) or Update(StatusCode)
    BEGIN

		Declare @NumberOfRestrictions Int = 0

		select @NumberOfRestrictions = Count(*)
		  from CNF_AccountRestriction
		 Where Enabled = 1

		if @NumberOfRestrictions &gt; 0
		BEGIN
			DECLARE @INS_SaleID int
			DECLARE @status int = 0 
			DECLARE @DR_status int

			DECLARE @RestrictionType int	
			
			DECLARE @CheckforRestraintOnly int = 0

			SELECT @status=i.Approved, @INS_SaleID = i.Saleid 
					FROM inserted i
						JOIN deleted d
								 ON i.SaleID = d.SaleID
								 AND ((d.paid = 0) or (i.paid &lt;&gt; d.Paid))
								 AND i.statuscode = 1

			if @status = 0 
			begin
				SELECT @DR_status = CASE WHEN i.StatusCode = 2 then  1
										 else 0
									 end, 
					   @INS_SaleID = i.Saleid 
						FROM inserted i
							  JOIN deleted d
									  ON i.[SaleID] = d.[SaleID]
										 AND i.[StatusCode] &lt;&gt; d.[StatusCode]
			end


			if @status = 1
			begin
--Reservation Account
				Insert into data_shopcartitemlimit
				select  data_sale.saleid,
				        0 as B2B,
						0 as  Billing,
						ISNULL(data_reservation.accountid, ODR.AccountID) as ReservationAccountID,
						0 TicketAccountID,
						data_saleitem.Matrixcellid,
						data_saleitem.Quantity,
						case when cnf_performance.PerformanceID is not null then cnf_performance.PerformanceID
												 else 9999999
						end ,
						case when cnf_performance.Eventid is not null then cnf_performance.Eventid
												 else  9999999
						end,
						data_sale.saleid,
						data_saleitem.saleitemid,
						case when data_saleitem.Quantity &lt; 0 and (select top 1 1 
							                                        from data_accountlimit WITH(NOLOCK)
																	where data_accountlimit.saleid = ODS.Saleid
																	  and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId) = 1

															then ISNULL((select top 1 1
																			from data_transaction
																			where data_transaction.transactiontype in (17, 18, 20, 22, 40, 47)
																				and data_transaction.saleid = data_sale.saleid), 0)
							when data_saleitem.Quantity &lt; 0 and ISNULL((select top 1 1 
							                                        from data_accountlimit WITH(NOLOCK)
																	where data_accountlimit.saleid = ODS.Saleid
																	  and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId), 0) &lt;&gt; 1

															then 1
								else 0
							end as UsageCheck

				from data_sale WITH(NOLOCK)
					LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
					INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
					LEFT  JOIN data_saleitem2Performance WITH(NOLOCK)			on data_saleitem2performance.saleitemid = data_saleitem.saleitemid
					LEFT  JOIN cnf_performance WITH(NOLOCK)						on cnf_Performance.performanceid = data_saleitem2performance.performanceid
					left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
					left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

					where data_sale.saleid = @INS_SaleID

--B2B Account
				Insert into data_shopcartitemlimit
				select  data_sale.saleid,
				        ISNULL(data_reservation.B2BAccountID, ODR.B2BAccountID) as B2B,
						0 as  Billing,
						0 as ReservationAccountID,
						0 TicketAccountID,
						data_saleitem.Matrixcellid,
						data_saleitem.Quantity,
						case when cnf_performance.PerformanceID is not null then cnf_performance.PerformanceID
												 else 9999999
						end ,
						case when cnf_performance.Eventid is not null then cnf_performance.Eventid
												 else  9999999
						end,
						data_sale.saleid,
						data_saleitem.saleitemid,
						case when data_saleitem.Quantity &lt; 0 and (select top 1 1 
							                                        from data_accountlimit WITH(NOLOCK)
																	where data_accountlimit.saleid = ODS.Saleid
																	  and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId) = 1

															then ISNULL((select top 1 1
																			from data_transaction
																			where data_transaction.transactiontype in (17, 18, 20, 22, 40, 47)
																				and data_transaction.saleid = data_sale.saleid), 0)
							when data_saleitem.Quantity &lt; 0 and ISNULL((select top 1 1 
							                                        from data_accountlimit WITH(NOLOCK)
																	where data_accountlimit.saleid = ODS.Saleid
																	  and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId), 0) &lt;&gt; 1

															then 1
								else 0
							end as UsageCheck

				from data_sale WITH(NOLOCK)
					LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
					INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
					LEFT  JOIN data_saleitem2Performance WITH(NOLOCK)			on data_saleitem2performance.saleitemid = data_saleitem.saleitemid
					LEFT  JOIN cnf_performance WITH(NOLOCK)						on cnf_Performance.performanceid = data_saleitem2performance.performanceid
					left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
					left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

					where data_sale.saleid = @INS_SaleID
					  and ISNULL(data_reservation.B2BAccountID, ODR.B2BAccountID) is not null

--Billing Account
				Insert into data_shopcartitemlimit
				select  data_sale.saleid,
				        0 as B2B,
				        ISNULL(data_reservation.BillingAccountId, ODR.BillingAccountId) as BillingAccountId,
						0 as ReservationAccountID,
						0 TicketAccountID,
						data_saleitem.Matrixcellid,
						data_saleitem.Quantity,
						case when cnf_performance.PerformanceID is not null then cnf_performance.PerformanceID
												 else 9999999
						end ,
						case when cnf_performance.Eventid is not null then cnf_performance.Eventid
												 else  9999999
						end,
						data_sale.saleid,
						data_saleitem.saleitemid,
						case when data_saleitem.Quantity &lt; 0 and (select top 1 1 
							                                        from data_accountlimit WITH(NOLOCK)
																	where data_accountlimit.saleid = ODS.Saleid
																	  and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId) = 1

															then ISNULL((select top 1 1
																			from data_transaction
																			where data_transaction.transactiontype in (17, 18, 20, 22, 40, 47)
																				and data_transaction.saleid = data_sale.saleid), 0)
							when data_saleitem.Quantity &lt; 0 and ISNULL((select top 1 1 
							                                        from data_accountlimit WITH(NOLOCK)
																	where data_accountlimit.saleid = ODS.Saleid
																	  and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId), 0) &lt;&gt; 1

															then 1
								else 0
							end as UsageCheck

				from data_sale WITH(NOLOCK)
					LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
					INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
					LEFT  JOIN data_saleitem2Performance WITH(NOLOCK)			on data_saleitem2performance.saleitemid = data_saleitem.saleitemid
					LEFT  JOIN cnf_performance WITH(NOLOCK)						on cnf_Performance.performanceid = data_saleitem2performance.performanceid
					left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
					left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

					where data_sale.saleid = @INS_SaleID
					  and ISNULL(data_reservation.BillingAccountId, ODR.BillingAccountId) is not null

--Ticket Account
				Insert into data_shopcartitemlimit
				select  data_sale.saleid,
				        0 as B2B,
				        0 as BillingAccountId,
						0 as ReservationAccountID,
						data_ticket.accountid TicketAccountID,
						data_saleitem.Matrixcellid,
						case when data_ticket.ticketid is not null then case when data_saleitem.Quantity &lt; 0 then -1 else 1 end
										else data_saleitem.Quantity
									end Quantity,
						case when cnf_performance.PerformanceID is not null then cnf_performance.PerformanceID
												 else 9999999
						end ,
						case when cnf_performance.Eventid is not null then cnf_performance.Eventid
												 else  9999999
						end,
						data_sale.saleid,
						data_saleitem.saleitemid,
						case when data_saleitem.Quantity &lt; 0 and (select top 1 1 
							                                        from data_accountlimit WITH(NOLOCK)
																	where data_accountlimit.saleid = ODS.Saleid
																	  and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId) = 1

															then ISNULL((select top 1 1
																			from data_transaction
																			where data_transaction.transactiontype in (17, 18, 20, 22, 40, 47)
																				and data_transaction.saleid = data_sale.saleid), 0)
							when data_saleitem.Quantity &lt; 0 and ISNULL((select top 1 1 
							                                        from data_accountlimit WITH(NOLOCK)
																	where data_accountlimit.saleid = ODS.Saleid
																	  and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId), 0) &lt;&gt; 1

															then 1
								else 0
							end as UsageCheck

					from data_sale WITH(NOLOCK)
						LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
						INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
						LEFT  JOIN data_saleitem2ticket WITH(NOLOCK)				on data_saleitem2ticket.saleitemid = data_saleitem.saleitemid
						LEFT  JOIN data_saleitem2Performance WITH(NOLOCK)			on data_saleitem2performance.saleitemid = data_saleitem.saleitemid
						LEFT  JOIN cnf_performance WITH(NOLOCK)						on cnf_Performance.performanceid = data_saleitem2performance.performanceid
						LEFT  JOIN data_ticket WITH(NOLOCK)							on data_ticket.ticketid = data_saleitem2ticket.ticketid
						left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
						left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

					where data_sale.saleid = @INS_SaleID
					  and data_ticket.accountid is not null

--Reservation Account
				Insert into data_shopcartitemlimit
				select  data_sale.saleid,
				        0 as B2B,
						0 as  Billing,
						ISNULL(data_reservation.accountid, ODR.AccountID) as ReservationAccountID,
						0 TicketAccountID,
						data_saleitem.Matrixcellid,
						data_saleitem.Quantity,
						0,
						0,
						data_sale.saleid,
						data_saleitem.saleitemid,
						case when data_saleitem.Quantity &lt; 0 and (select top 1 1 
							                                        from data_accountlimit WITH(NOLOCK)
																	where data_accountlimit.saleid = ODS.Saleid
																	  and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId) = 1

															then ISNULL((select top 1 1
																			from data_transaction
																			where data_transaction.transactiontype in (17, 18, 20, 22, 40, 47)
																				and data_transaction.saleid = data_sale.saleid), 0)
							when data_saleitem.Quantity &lt; 0 and ISNULL((select top 1 1 
							                                        from data_accountlimit WITH(NOLOCK)
																	where data_accountlimit.saleid = ODS.Saleid
																	  and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId), 0) &lt;&gt; 1

															then 1
								else 0
							end as UsageCheck

				from data_sale WITH(NOLOCK)
					LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
					INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
					left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
					left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

					where data_sale.saleid = @INS_SaleID

--B2B Account
				Insert into data_shopcartitemlimit
				select  data_sale.saleid,
				        ISNULL(data_reservation.B2BAccountID, ODR.B2BAccountID) as B2B,
						0 as  Billing,
						0 as ReservationAccountID,
						0 TicketAccountID,
						data_saleitem.Matrixcellid,
						data_saleitem.Quantity,
						0,
						0,
						data_sale.saleid,
						data_saleitem.saleitemid,
						case when data_saleitem.Quantity &lt; 0 and (select top 1 1 
							                                        from data_accountlimit WITH(NOLOCK)
																	where data_accountlimit.saleid = ODS.Saleid
																	  and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId) = 1

															then ISNULL((select top 1 1
																			from data_transaction
																			where data_transaction.transactiontype in (17, 18, 20, 22, 40, 47)
																				and data_transaction.saleid = data_sale.saleid), 0)
							when data_saleitem.Quantity &lt; 0 and ISNULL((select top 1 1 
							                                        from data_accountlimit WITH(NOLOCK)
																	where data_accountlimit.saleid = ODS.Saleid
																	  and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId), 0) &lt;&gt; 1

															then 1
								else 0
							end as UsageCheck

				from data_sale WITH(NOLOCK)
					LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
					INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
					left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
					left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

					where data_sale.saleid = @INS_SaleID
					  and ISNULL(data_reservation.B2BAccountID, ODR.B2BAccountID) is not null

--Billing Account
				Insert into data_shopcartitemlimit
				select  data_sale.saleid,
				        0 as B2B,
				        ISNULL(data_reservation.BillingAccountId, ODR.BillingAccountId) as BillingAccountId,
						0 as ReservationAccountID,
						0 TicketAccountID,
						data_saleitem.Matrixcellid,
						data_saleitem.Quantity,
						0,
						0,
						data_sale.saleid,
						data_saleitem.saleitemid,
						case when data_saleitem.Quantity &lt; 0 and (select top 1 1 
							                                        from data_accountlimit WITH(NOLOCK)
																	where data_accountlimit.saleid = ODS.Saleid
																	  and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId) = 1

															then ISNULL((select top 1 1
																			from data_transaction
																			where data_transaction.transactiontype in (17, 18, 20, 22, 40, 47)
																				and data_transaction.saleid = data_sale.saleid), 0)
							when data_saleitem.Quantity &lt; 0 and ISNULL((select top 1 1 
							                                        from data_accountlimit WITH(NOLOCK)
																	where data_accountlimit.saleid = ODS.Saleid
																	  and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId), 0) &lt;&gt; 1

															then 1
								else 0
							end as UsageCheck

				from data_sale WITH(NOLOCK)
					LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
					INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
					left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
					left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

					where data_sale.saleid = @INS_SaleID
					  and ISNULL(data_reservation.BillingAccountId, ODR.BillingAccountId) is not null

--Ticket Account
				Insert into data_shopcartitemlimit
				select  data_sale.saleid,
				        0 as B2B,
				        0 as BillingAccountId,
						0 as ReservationAccountID,
						data_ticket.accountid TicketAccountID,
						data_saleitem.Matrixcellid,
						case when data_ticket.ticketid is not null then case when data_saleitem.Quantity &lt; 0 then -1 else 1 end
										else data_saleitem.Quantity
									end Quantity,
						0,
						0,
						data_sale.saleid,
						data_saleitem.saleitemid,
						case when data_saleitem.Quantity &lt; 0 and (select top 1 1 
							                                        from data_accountlimit WITH(NOLOCK)
																	where data_accountlimit.saleid = ODS.Saleid
																	  and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId) = 1

															then ISNULL((select top 1 1
																			from data_transaction
																			where data_transaction.transactiontype in (17, 18, 20, 22, 40, 47)
																				and data_transaction.saleid = data_sale.saleid), 0)
							when data_saleitem.Quantity &lt; 0 and ISNULL((select top 1 1 
							                                        from data_accountlimit WITH(NOLOCK)
																	where data_accountlimit.saleid = ODS.Saleid
																	  and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId), 0) &lt;&gt; 1

															then 1
								else 0
							end as UsageCheck

					from data_sale WITH(NOLOCK)
						LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
						INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
						LEFT  JOIN data_saleitem2ticket WITH(NOLOCK)				on data_saleitem2ticket.saleitemid = data_saleitem.saleitemid
						LEFT  JOIN data_ticket WITH(NOLOCK)							on data_ticket.ticketid = data_saleitem2ticket.ticketid
						left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
						left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

					where data_sale.saleid = @INS_SaleID
					  and data_ticket.accountid is not null	

			END

--Reservation Deletes
			if @DR_status = 1
			begin
			--Reservation Account
				Insert into data_shopcartitemlimit
				select  data_sale.saleid,
				        0 as B2B,
						0 as  Billing,
						ISNULL(data_reservation.accountid, ODR.AccountID) as ReservationAccountID,
						0 TicketAccountID,
						data_saleitem.Matrixcellid,
						data_saleitem.Quantity,
						case when cnf_performance.PerformanceID is not null then cnf_performance.PerformanceID
												 else 9999999
						end ,
						case when cnf_performance.Eventid is not null then cnf_performance.Eventid
												 else  9999999
						end,
						data_sale.saleid,
						data_saleitem.saleitemid,
						case when data_saleitem.Quantity &lt; 0 and (select top 1 1 
							                                        from data_accountlimit WITH(NOLOCK)
																	where data_accountlimit.saleid = ODS.Saleid
																	  and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId) = 1

															then ISNULL((select top 1 1
																			from data_transaction
																			where data_transaction.transactiontype in (17, 18, 20, 22, 40, 47)
																				and data_transaction.saleid = data_sale.saleid), 0)
							when data_saleitem.Quantity &lt; 0 and ISNULL((select top 1 1 
							                                        from data_accountlimit WITH(NOLOCK)
																	where data_accountlimit.saleid = ODS.Saleid
																	  and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId), 0) &lt;&gt; 1

															then 1
								else 0
							end as UsageCheck

				from data_sale WITH(NOLOCK)
					LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
					INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
					LEFT  JOIN data_saleitem2Performance WITH(NOLOCK)			on data_saleitem2performance.saleitemid = data_saleitem.saleitemid
					LEFT  JOIN cnf_performance WITH(NOLOCK)						on cnf_Performance.performanceid = data_saleitem2performance.performanceid
					left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
					left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

					where data_sale.saleid = @INS_SaleID
					  and data_saleitem.quantity &lt; 0

--B2B Account
				Insert into data_shopcartitemlimit
				select  data_sale.saleid,
				        ISNULL(data_reservation.B2BAccountID, ODR.B2BAccountID) as B2B,
						0 as  Billing,
						0 as ReservationAccountID,
						0 TicketAccountID,
						data_saleitem.Matrixcellid,
						data_saleitem.Quantity,
						case when cnf_performance.PerformanceID is not null then cnf_performance.PerformanceID
												 else 9999999
						end ,
						case when cnf_performance.Eventid is not null then cnf_performance.Eventid
												 else  9999999
						end,
						data_sale.saleid,
						data_saleitem.saleitemid,
						case when data_saleitem.Quantity &lt; 0 and (select top 1 1 
							                                        from data_accountlimit WITH(NOLOCK)
																	where data_accountlimit.saleid = ODS.Saleid
																	  and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId) = 1

															then ISNULL((select top 1 1
																			from data_transaction
																			where data_transaction.transactiontype in (17, 18, 20, 22, 40, 47)
																				and data_transaction.saleid = data_sale.saleid), 0)
							when data_saleitem.Quantity &lt; 0 and ISNULL((select top 1 1 
							                                        from data_accountlimit WITH(NOLOCK)
																	where data_accountlimit.saleid = ODS.Saleid
																	  and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId), 0) &lt;&gt; 1

															then 1
								else 0
							end as UsageCheck

				from data_sale WITH(NOLOCK)
					LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
					INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
					LEFT  JOIN data_saleitem2Performance WITH(NOLOCK)			on data_saleitem2performance.saleitemid = data_saleitem.saleitemid
					LEFT  JOIN cnf_performance WITH(NOLOCK)						on cnf_Performance.performanceid = data_saleitem2performance.performanceid
					left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
					left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

					where data_sale.saleid = @INS_SaleID
					  and ISNULL(data_reservation.B2BAccountID, ODR.B2BAccountID) is not null
					  and data_saleitem.quantity &lt; 0

--Billing Account
				Insert into data_shopcartitemlimit
				select  data_sale.saleid,
				        0 as B2B,
				        ISNULL(data_reservation.BillingAccountId, ODR.BillingAccountId) as BillingAccountId,
						0 as ReservationAccountID,
						0 TicketAccountID,
						data_saleitem.Matrixcellid,
						data_saleitem.Quantity,
						case when cnf_performance.PerformanceID is not null then cnf_performance.PerformanceID
												 else 9999999
						end ,
						case when cnf_performance.Eventid is not null then cnf_performance.Eventid
												 else  9999999
						end,
						data_sale.saleid,
						data_saleitem.saleitemid,
						case when data_saleitem.Quantity &lt; 0 and (select top 1 1 
							                                        from data_accountlimit WITH(NOLOCK)
																	where data_accountlimit.saleid = ODS.Saleid
																	  and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId) = 1

															then ISNULL((select top 1 1
																			from data_transaction
																			where data_transaction.transactiontype in (17, 18, 20, 22, 40, 47)
																				and data_transaction.saleid = data_sale.saleid), 0)
							when data_saleitem.Quantity &lt; 0 and ISNULL((select top 1 1 
							                                        from data_accountlimit WITH(NOLOCK)
																	where data_accountlimit.saleid = ODS.Saleid
																	  and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId), 0) &lt;&gt; 1

															then 1
								else 0
							end as UsageCheck

				from data_sale WITH(NOLOCK)
					LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
					INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
					LEFT  JOIN data_saleitem2Performance WITH(NOLOCK)			on data_saleitem2performance.saleitemid = data_saleitem.saleitemid
					LEFT  JOIN cnf_performance WITH(NOLOCK)						on cnf_Performance.performanceid = data_saleitem2performance.performanceid
					left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
					left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

					where data_sale.saleid = @INS_SaleID
					  and ISNULL(data_reservation.BillingAccountId, ODR.BillingAccountId) is not null
					  and data_saleitem.quantity &lt; 0

--Ticket Account
				Insert into data_shopcartitemlimit
				select  data_sale.saleid,
				        0 as B2B,
				        0 as BillingAccountId,
						0 as ReservationAccountID,
						data_ticket.accountid TicketAccountID,
						data_saleitem.Matrixcellid,
						case when data_ticket.ticketid is not null then case when data_saleitem.Quantity &lt; 0 then -1 else 1 end
										else data_saleitem.Quantity
									end Quantity,
						case when cnf_performance.PerformanceID is not null then cnf_performance.PerformanceID
												 else 9999999
						end ,
						case when cnf_performance.Eventid is not null then cnf_performance.Eventid
												 else  9999999
						end,
						data_sale.saleid,
						data_saleitem.saleitemid,
						case when data_saleitem.Quantity &lt; 0 and (select top 1 1 
							                                        from data_accountlimit WITH(NOLOCK)
																	where data_accountlimit.saleid = ODS.Saleid
																	  and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId) = 1

															then ISNULL((select top 1 1
																			from data_transaction
																			where data_transaction.transactiontype in (17, 18, 20, 22, 40, 47)
																				and data_transaction.saleid = data_sale.saleid), 0)
							when data_saleitem.Quantity &lt; 0 and ISNULL((select top 1 1 
							                                        from data_accountlimit WITH(NOLOCK)
																	where data_accountlimit.saleid = ODS.Saleid
																	  and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId), 0) &lt;&gt; 1

															then 1
								else 0
							end as UsageCheck

					from data_sale WITH(NOLOCK)
						LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
						INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
						LEFT  JOIN data_saleitem2ticket WITH(NOLOCK)				on data_saleitem2ticket.saleitemid = data_saleitem.saleitemid
						LEFT  JOIN data_saleitem2Performance WITH(NOLOCK)			on data_saleitem2performance.saleitemid = data_saleitem.saleitemid
						LEFT  JOIN cnf_performance WITH(NOLOCK)						on cnf_Performance.performanceid = data_saleitem2performance.performanceid
						LEFT  JOIN data_ticket WITH(NOLOCK)							on data_ticket.ticketid = data_saleitem2ticket.ticketid
						left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
						left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

					where data_sale.saleid = @INS_SaleID
					  and data_ticket.accountid is not null
					  and data_saleitem.quantity &lt; 0

--Reservation Account
				Insert into data_shopcartitemlimit
				select  data_sale.saleid,
				        0 as B2B,
						0 as  Billing,
						ISNULL(data_reservation.accountid, ODR.AccountID) as ReservationAccountID,
						0 TicketAccountID,
						data_saleitem.Matrixcellid,
						data_saleitem.Quantity,
						0,
						0,
						data_sale.saleid,
						data_saleitem.saleitemid,
						case when data_saleitem.Quantity &lt; 0 and (select top 1 1 
							                                        from data_accountlimit WITH(NOLOCK)
																	where data_accountlimit.saleid = ODS.Saleid
																	  and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId) = 1

															then ISNULL((select top 1 1
																			from data_transaction
																			where data_transaction.transactiontype in (17, 18, 20, 22, 40, 47)
																				and data_transaction.saleid = data_sale.saleid), 0)
							when data_saleitem.Quantity &lt; 0 and ISNULL((select top 1 1 
							                                        from data_accountlimit WITH(NOLOCK)
																	where data_accountlimit.saleid = ODS.Saleid
																	  and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId), 0) &lt;&gt; 1

															then 1
								else 0
							end as UsageCheck

				from data_sale WITH(NOLOCK)
					LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
					INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
					left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
					left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

					where data_sale.saleid = @INS_SaleID
					  and data_saleitem.quantity &lt; 0

--B2B Account
				Insert into data_shopcartitemlimit
				select  data_sale.saleid,
				        ISNULL(data_reservation.B2BAccountID, ODR.B2BAccountID) as B2B,
						0 as  Billing,
						0 as ReservationAccountID,
						0 TicketAccountID,
						data_saleitem.Matrixcellid,
						data_saleitem.Quantity,
						0,
						0,
						data_sale.saleid,
						data_saleitem.saleitemid,
						case when data_saleitem.Quantity &lt; 0 and (select top 1 1 
							                                        from data_accountlimit WITH(NOLOCK)
																	where data_accountlimit.saleid = ODS.Saleid
																	  and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId) = 1

															then ISNULL((select top 1 1
																			from data_transaction
																			where data_transaction.transactiontype in (17, 18, 20, 22, 40, 47)
																				and data_transaction.saleid = data_sale.saleid), 0)
							when data_saleitem.Quantity &lt; 0 and ISNULL((select top 1 1 
							                                        from data_accountlimit WITH(NOLOCK)
																	where data_accountlimit.saleid = ODS.Saleid
																	  and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId), 0) &lt;&gt; 1

															then 1
								else 0
							end as UsageCheck

				from data_sale WITH(NOLOCK)
					LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
					INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
					left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
					left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

					where data_sale.saleid = @INS_SaleID
					  and ISNULL(data_reservation.B2BAccountID, ODR.B2BAccountID) is not null
					  and data_saleitem.quantity &lt; 0

--Billing Account
				Insert into data_shopcartitemlimit
				select  data_sale.saleid,
				        0 as B2B,
				        ISNULL(data_reservation.BillingAccountId, ODR.BillingAccountId) as BillingAccountId,
						0 as ReservationAccountID,
						0 TicketAccountID,
						data_saleitem.Matrixcellid,
						data_saleitem.Quantity,
						0,
						0,
						data_sale.saleid,
						data_saleitem.saleitemid,
						case when data_saleitem.Quantity &lt; 0 and (select top 1 1 
							                                        from data_accountlimit WITH(NOLOCK)
																	where data_accountlimit.saleid = ODS.Saleid
																	  and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId) = 1

															then ISNULL((select top 1 1
																			from data_transaction
																			where data_transaction.transactiontype in (17, 18, 20, 22, 40, 47)
																				and data_transaction.saleid = data_sale.saleid), 0)
							when data_saleitem.Quantity &lt; 0 and ISNULL((select top 1 1 
							                                        from data_accountlimit WITH(NOLOCK)
																	where data_accountlimit.saleid = ODS.Saleid
																	  and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId), 0) &lt;&gt; 1

															then 1
								else 0
							end as UsageCheck

				from data_sale WITH(NOLOCK)
					LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
					INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
					left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
					left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

					where data_sale.saleid = @INS_SaleID
					  and ISNULL(data_reservation.BillingAccountId, ODR.BillingAccountId) is not null
					  and data_saleitem.quantity &lt; 0

--Ticket Account
				Insert into data_shopcartitemlimit
				select  data_sale.saleid,
				        0 as B2B,
				        0 as BillingAccountId,
						0 as ReservationAccountID,
						data_ticket.accountid TicketAccountID,
						data_saleitem.Matrixcellid,
						case when data_ticket.ticketid is not null then case when data_saleitem.Quantity &lt; 0 then -1 else 1 end
										else data_saleitem.Quantity
									end Quantity,
						0,
						0,
						data_sale.saleid,
						data_saleitem.saleitemid,
						case when data_saleitem.Quantity &lt; 0 and (select top 1 1 
							                                        from data_accountlimit WITH(NOLOCK)
																	where data_accountlimit.saleid = ODS.Saleid
																	  and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId) = 1

															then ISNULL((select top 1 1
																			from data_transaction
																			where data_transaction.transactiontype in (17, 18, 20, 22, 40, 47)
																				and data_transaction.saleid = data_sale.saleid), 0)
							when data_saleitem.Quantity &lt; 0 and ISNULL((select top 1 1 
							                                        from data_accountlimit WITH(NOLOCK)
																	where data_accountlimit.saleid = ODS.Saleid
																	  and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId), 0) &lt;&gt; 1

															then 1
								else 0
							end as UsageCheck

					from data_sale WITH(NOLOCK)
						LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
						INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
						LEFT  JOIN data_saleitem2ticket WITH(NOLOCK)				on data_saleitem2ticket.saleitemid = data_saleitem.saleitemid
						LEFT  JOIN data_ticket WITH(NOLOCK)							on data_ticket.ticketid = data_saleitem2ticket.ticketid
						left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
						left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

					where data_sale.saleid = @INS_SaleID
					  and data_ticket.accountid is not null	
					  and data_saleitem.quantity &lt; 0
			end

			delete from data_shopcartitemlimit where PerformanceID = 9999999
			delete from data_shopcartitemlimit where Quantity = 0
			--select * 		from data_shopcartitemlimit
			
			Exec otn_sp_CheckAccountRestrictions 0, @INS_SaleID


		end
	end
end</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>ALTER TABLE [dbo].[DATA_Sale] ENABLE TRIGGER [data_sale_SalesRestriction]</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>lfornaroli</ADDEDBY><SQLVERSION>3230</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>CNF_SeatObject
[0] add NumRow smallint not null
[1] add NumCol smallint not null
[2] add LabelText nvarchar(200) null </REASON><TABLENAMES>CNF_SeatObject=SeatObjectId</TABLENAMES><SQLSCRIPTLIST><SCRIPT> IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'NumRow' 
                      AND OBJECT_ID = OBJECT_ID(N'CNF_SeatObject'))
BEGIN
alter table CNF_SeatObject
 add NumRow smallint not null  default 1
end</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'NumCol' 
                      AND OBJECT_ID = OBJECT_ID(N'CNF_SeatObject'))
BEGIN
alter table CNF_SeatObject
 add NumCol smallint not null  default 1
end</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'LabelText' 
                      AND OBJECT_ID = OBJECT_ID(N'CNF_SeatObject'))
BEGIN
alter table CNF_SeatObject
 add LabelText nvarchar(200) null 
end</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>3229</SQLVERSION><RMTRACKLINK>IDBOS-2878</RMTRACKLINK><REASON></REASON><TABLENAMES>CNF_AccountRestriction2matrixcell=AccountRestriction2MatrixcellID</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'IncludeAllTickets' 
                      AND OBJECT_ID = OBJECT_ID(N'CNF_AccountRestriction2matrixcell'))
BEGIN
alter table CNF_AccountRestriction2matrixcell
 add IncludeAllTickets smallint null
end</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'MatrixCellid' 
                      AND OBJECT_ID = OBJECT_ID(N'CNF_AccountRestriction2matrixcell'))
BEGIN
	ALTER TABLE
	  CNF_AccountRestriction2matrixcell
	ALTER COLUMN
	  MatrixCellid Integer NULL;
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dchen</ADDEDBY><SQLVERSION>3228</SQLVERSION><RMTRACKLINK>89352</RMTRACKLINK><REASON>Allow Installment Payment to apply amount from Upgraded Tickets</REASON><TABLENAMES>DATA_PaymentFlex=PaymentId
DATA_PaymentFlexInfo=PaymentFlexInfoId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'OwnedAmount' 
                      AND OBJECT_ID = OBJECT_ID(N'DATA_PaymentFlex'))
BEGIN
alter table DATA_PaymentFlex
 add OwnedAmount float null
end</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'OwnedAmount' 
                      AND OBJECT_ID = OBJECT_ID(N'DATA_PaymentFlexInfo'))
BEGIN
alter table DATA_PaymentFlexInfo
 add OwnedAmount float null
end</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3227</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>0 - add PriorityType To CNF_Performance
1 - Add HeldByChild To CNF_EnvelopeCapacity
2 - Set 0 to HeldBychild
3 - add row to CNF_SeatObject
4 - add col to CNF_SeatObject</REASON><TABLENAMES>CNF_Performance=PerformanceId
CNF_EnvelopeCapacity=EnvelopeCapacityId
CNF_SeatObject=SeatObjectId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'PriorityType' 
                      AND OBJECT_ID = OBJECT_ID(N'CNF_Performance'))
BEGIN
alter table CNF_Performance
 add PriorityType smallint null
end</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'HeldByChild' 
                      AND OBJECT_ID = OBJECT_ID(N'CNF_EnvelopeCapacity'))
BEGIN
alter table CNF_EnvelopeCapacity
 add HeldByChild int null
end</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT> update CNF_EnvelopeCapacity set HeldByChild = 0 where HeldByChild is Null; 
        
 alter table CNF_EnvelopeCapacity 
    alter column  HeldByChild int not null;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'Row' 
                      AND OBJECT_ID = OBJECT_ID(N'CNF_SeatObject'))
BEGIN
alter table CNF_SeatObject
 add Row int not null
end</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'Col' 
                      AND OBJECT_ID = OBJECT_ID(N'CNF_SeatObject'))
BEGIN
alter table CNF_SeatObject
 add Col int not null
end</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>lfornaroli</ADDEDBY><SQLVERSION>3226</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>[0] add table CNF_SeatObject
[1] add fileds on CNF_Seat</REASON><TABLENAMES>CNF_SeatObject=SeatObjectId
CNF_Seat=SeatId
CNF_Performance=PerformanceId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID('CNF_SeatObject') AND type in ('U'))
BEGIN
  create table CNF_SeatObject(
    SeatObjectId Integer Identity(1,1) NOT NULL, UNIQUE (SeatObjectId),
    SpaceStructureId integer not null,
    PerformanceId integer null,
    SeatObjectType smallint not null,
    BackgroundColor nvarchar(10) null,
    TextColor nvarchar(10) null,
    Last_UserId_Log Integer NULL,
    Last_WorkstationId_Log Integer NULL,
    Last_DateTime_Log Datetime NULL
  Primary Key (SeatObjectId)
  )
  

  ALTER TABLE CNF_SeatObject  WITH CHECK ADD  CONSTRAINT [FK_CNF_SeatObject_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log])
	REFERENCES CNF_User ([UserId])

  ALTER TABLE CNF_SeatObject  WITH CHECK ADD  CONSTRAINT [FK_CNF_SeatObject_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log])
	REFERENCES CNF_Workstation ([WorkstationId])

  ALTER TABLE CNF_SeatObject  WITH CHECK ADD  CONSTRAINT [FK_CNF_SeatObject_PerformanceId] FOREIGN KEY(PerformanceId)
	REFERENCES CNF_Performance (PerformanceId)

  ALTER TABLE CNF_SeatObject  WITH CHECK ADD  CONSTRAINT [FK_CNF_SeatObject_SpaceStructureId] FOREIGN KEY(SpaceStructureId)
	REFERENCES CNF_SpaceStructure (SpaceStructureId)

end</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'WarningType' 
                      AND OBJECT_ID = OBJECT_ID(N'CNF_Seat'))
BEGIN
  alter table CNF_Seat 
    add  WarningType smallInt null;
    
end    



</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT> update CNF_Seat set WarningType = 0 where WarningType is Null; 
        
 alter table CNF_Seat 
    alter column  WarningType smallInt not null;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF  EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'[HoldDateTime]' 
                     AND OBJECT_ID = OBJECT_ID(N'CNF_Seat'))
BEGIN
alter table CNF_Seat
  drop column [HoldDateTime]
end

IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'PriorityHeldDateTime' 
                      AND OBJECT_ID = OBJECT_ID(N'CNF_Seat'))
BEGIN
alter table CNF_Seat
 add PriorityHeldDateTime dateTime null
end</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'PriorityPerformanceId' 
                      AND OBJECT_ID = OBJECT_ID(N'CNF_Performance'))
BEGIN
alter table CNF_Performance
 add PriorityPerformanceId Integer null
 
 
  ALTER TABLE CNF_Performance  WITH CHECK ADD  CONSTRAINT [FK_CNF_Performance_PriorityPerfId] FOREIGN KEY([PriorityPerformanceId])
	REFERENCES CNF_Performance ([PerformanceId])
end</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>3225</SQLVERSION><RMTRACKLINK>IDBOS-2548</RMTRACKLINK><REASON>Update the table CNF_UpSell in order to set all the already existing records as per the POS/TVM by default

[0] Update table</REASON><TABLENAMES>CNF_UpSell=UpSellId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>UPDATE CNF_UpSell SET UpSellType=0</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fdipalma</ADDEDBY><SQLVERSION>3224</SQLVERSION><RMTRACKLINK>IDBOS-2581</RMTRACKLINK><REASON>Food Vouchers- ticket to be imported</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT 1 FROM sys.procedures 
          WHERE Name = 'otn_sp_MediaIdentifier_Import')
	DROP PROCEDURE otn_sp_MediaIdentifier_Import</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>create procedure [otn_sp_MediaIdentifier_Import]
	@IdentifierCode varchar(400),
	@ExternalCode varchar(100),
	@Status smallint
as
begin
	DECLARE @result smallint;
	SET @result = 0;
	DECLARE @c int;
	select @c = COUNT(IdentifierCode) from IMP_MediaIdentifier where IdentifierCode = @IdentifierCode

	IF (@c = 0)
	begin
		insert into IMP_MediaIdentifier (
		IdentifierCode,
		ExternalCode,
		Status
		) values (
		@IdentifierCode,
		@ExternalCode,
		@Status
		)
		SET @result = 1;
	end;
	RETURN @result;
end</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>3223</SQLVERSION><RMTRACKLINK>IDBOS-2548</RMTRACKLINK><REASON>Managed the new UpSell rules in order to have multiple tickets

[0] Create Table CNF_UpSell_Rule
[1] Create Index
[2] Drop existing trigger if exists
[3] Create trigger for History Log
[4] Create column Link to CNF_UpSell
[5] Populate CNF_UpSell_Rule from CNF_UpSell2MatrixCell
[6] Drop the trigger of the CNF_UpSell2MatrixCell table
[7] Drop the table CNF_UpSell2MatrixCell</REASON><TABLENAMES>CNF_UpSell=UpSellId
CNF_UpSell_Rule=UpSellRuleId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID('CNF_UpSell_Rule') AND type in ('U'))
BEGIN
	Create table CNF_UpSell_Rule
	(
		[UpSellRuleId] Integer Identity(1,1) NOT NULL, UNIQUE ([UpSellRuleId]),
		[UpSellId] Integer NOT NULL,
		[ObjectId] Integer NOT NULL,
		[ObjectType] Smallint NULL,
		[RuleType] Smallint NULL,
		[Quantity] Integer NULL,
		[Last_UserId_Log] Integer NULL,
		[Last_WorkstationId_Log] Integer NULL,
		[Last_DateTime_Log] Datetime NULL,
	Primary Key ([UpSellRuleId])
	) 

	ALTER TABLE CNF_UpSell_Rule  WITH CHECK ADD  CONSTRAINT [FK_CNF_UpSell_Rule_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log])
	REFERENCES CNF_User ([UserId])

	ALTER TABLE CNF_UpSell_Rule  WITH CHECK ADD  CONSTRAINT [FK_CNF_UpSell_Rule_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log])
	REFERENCES CNF_Workstation ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT 1
            FROM sys.indexes I
                INNER JOIN sys.tables T
                    ON I.object_id = T.object_id
                INNER JOIN sys.schemas S
                    ON S.schema_id = T.schema_id
            WHERE I.Name = 'Idx_UpSellRules_ObjIdType' -- Index name
                AND T.Name = 'CNF_UpSell_Rule' -- Table name
                AND S.Name = 'dbo') --Schema Name
BEGIN
    create Index Idx_UpSellRules_ObjIdType ON CNF_UpSell_Rule (UpSellId ,ObjectId ,ObjectType )
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT 1 FROM sys.triggers 
           WHERE Name = 'CNF_UpSell_Rule_CT')
BEGIN
    DROP TRIGGER CNF_UpSell_Rule_CT
END

</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>create trigger [dbo].[CNF_UpSell_Rule_CT] on [dbo].[CNF_UpSell_Rule] FOR insert, update, delete
		as
		declare @TName varchar(128),
		        @TID nvarchar(max),
				@TLog int,  
				@PKC varchar(max),
				@PKV varchar(max),  
				@sql nvarchar(max), 
				@Type nvarchar(1),
				@MId nvarchar(max) = '0', 
				@ColumnID nvarchar(max) = '0',
				@CName varchar(128),
				@CValue1 nvarchar(max),
				@CValue2 nvarchar(max)

		if exists(select top 1 1 from cnf_system where ISNULL(BOSHistoryLogEnabled, 1) = 1 and offlinemode = 0)
		BEGIN
			select @TName = 'CNF_UpSell_Rule', @TID=dbtableid, @TLog = (case when Active = 1 and Logged = 1 then 1 else 0 end) from cnf_dbtable WITH(NOLOCK) where TableName='CNF_UpSell_Rule'

			if @TLog = 1
			begin
				if exists (select * from inserted)
				if exists (select * from deleted)
				select @Type = '2'      --Update
				else
				select @Type = '3'      --Insert
				else
				select @Type = '1'      --Delete

				select * into #ins from inserted
				select * into #del from deleted

				select @PKC = coalesce(@PKC + ' and', ' on') + ' i.' + c.COLUMN_NAME + ' = d.' + c.COLUMN_NAME, @PKV = coalesce(@PKV+'+','') + 'convert(varchar(100), coalesce(i.' + COLUMN_NAME + ',d.' + COLUMN_NAME + '))'
				  from INFORMATION_SCHEMA.TABLE_CONSTRAINTS p WITH(NOLOCK)
					   INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE c WITH(NOLOCK) on c.CONSTRAINT_NAME = p.CONSTRAINT_NAME and c.TABLE_NAME = p.TABLE_NAME
				 where p.TABLE_NAME=@TName and CONSTRAINT_TYPE='PRIMARY KEY'

				DECLARE TCursor CURSOR LOCAL FOR
								select columnName,
									   dbcolumnid
								from(
								select CNF_DBColumn.ColumnName,
									CNF_DBColumn.DBColumnId,
									(case when cnf_dbcolumn.Active = 1 and cnf_dbcolumn.Logged = 1 then 1 else 0 end) Active
									from sys.tables AS t WITH(NOLOCK)				
										INNER JOIN sys.columns c WITH(NOLOCK)				ON t.OBJECT_ID = c.OBJECT_ID 
										INNER JOIN cnf_dbtable WITH(NOLOCK)					on cnf_dbtable.tablename = t.name
										INNER JOIN cnf_dbcolumn WITH(NOLOCK)				on cnf_dbcolumn.dbtableid = cnf_dbtable.dbtableid and cnf_dbcolumn.columnname = c.name
								where cnf_dbcolumn.dbtableid = @TID
								)p
								where Active = 1

				OPEN TCursor

				FETCH NEXT FROM TCursor INTO
					@CName, @ColumnID
					
				WHILE @@FETCH_STATUS = 0
				BEGIN

					set @sql ='Select @CValue1 = ' + @CName +' from #ins '
					EXEC sp_executesql @sql, N'@CValue1 nvarchar(max) OUTPUT', @CValue1 OUTPUT

					set @sql ='Select @CValue2 = ' + @CName +' from #del '
					EXEC sp_executesql @sql, N'@CValue2 nvarchar(max) OUTPUT', @CValue2 OUTPUT

					if ISNULL(@CValue1, '&amp;*()_2') &lt;&gt; ISNULL(@CValue2, '&amp;*()_2')
					begin
						if @MId = 0
						begin
							set @sql = 'insert DATA_HL_Master (OperationType, dbtableid, ReferenceId, UserId, WorkstationId, InsDateTime, DelDateTime)'
							set @sql = @sql + ' select ''' + @Type + ''''												
							set @sql = @sql + ', ''' + @TID + ''''		
							set @sql = @sql + ',' + @PKV		
							set @sql = @sql + ', i.Last_UserId_Log, i.Last_WorkstationId_Log, i.Last_DateTime_Log, getdate()'
							set @sql = @sql + ' from #ins i full outer join #del d '
							set @sql = @sql + @PKC 
							set @sql = @sql + ' SELECT @MId = SCOPE_IDENTITY()'
							EXEC sp_executesql @sql, N'@MId nvarchar(max) OUTPUT', @MId OUTPUT
						end
						if @Type &lt;&gt; '3'
						BEGIN
							set @sql = 'insert data_HL_Detail (MasterId, OriginalValue, ModifiedValue, DBColumnID)'						
							set @sql = @sql + ' select convert(varchar(1000),' + @MId + '), convert(varchar(1000),d.' + @CName + '), convert(varchar(1000),i.' + @CName + ')'				
							set @sql = @sql + ', convert(varchar(1000),' + @ColumnID + ')  '
							set @sql = @sql + ' from #ins i full outer join #del d ' + @PKC				
							EXEC sp_executesql @sql 																	
						END		
						
					END
					FETCH NEXT FROM TCursor INTO
					   @CName, @ColumnID
				END  --While loop
				CLOSE TCursor;
				DEALLOCATE TCursor; 
			END    --Table Check
		END	-- System Check
		

ALTER TABLE CNF_UpSell_Rule ENABLE TRIGGER [CNF_UpSell_Rule_CT]</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Link' AND
                Object_ID  = Object_ID(N'CNF_UpSell'))
BEGIN
  ALTER TABLE CNF_UpSell ADD Link nvarchar(100) NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF  EXISTS (SELECT * 
            FROM sys.objects 
            WHERE object_id = OBJECT_ID('CNF_Upsell2MatrixCell') AND 
                  type in ('U'))
BEGIN

DECLARE @UpSellId integer;
DECLARE @FromMC integer;
DECLARE @ToMC integer;
DECLARE @UserId integer;
DECLARE @WksId integer;
DECLARE @Date datetime;
DECLARE @Link nvarchar(100);

DECLARE UpSellCursor CURSOR FOR 
	SELECT 
		UpSellId, 
		FromMatrixCellId, 
		ToMatrixCellId,
		Link,
		Last_UserId_Log, 
		Last_WorkstationId_Log, 
		Last_DateTime_Log 
	FROM 
		CNF_Upsell2MatrixCell

OPEN UpSellCursor;
FETCH NEXT FROM UpSellCursor INTO @UpSellId, @FromMC, @ToMC, @Link, @UserId, @WksId, @Date

WHILE @@FETCH_STATUS = 0
BEGIN
	INSERT INTO CNF_UpSell_Rule (UpSellId, ObjectId, ObjectType, RuleType, Quantity, Last_UserId_Log, Last_WorkstationId_Log, Last_DateTime_Log) VALUES (@UpSellId, @FromMC, 1, 0, 1, @UserId, @WksId, @Date);
	INSERT INTO CNF_UpSell_Rule (UpSellId, ObjectId, ObjectType, RuleType, Quantity, Last_UserId_Log, Last_WorkstationId_Log, Last_DateTime_Log) VALUES (@UpSellId, @ToMC, 1, 1, 1, @UserId, @WksId, @Date);
	UPDATE CNF_UpSell SET Link = @Link WHERE UpSellId = @UpSellId;

	FETCH NEXT FROM UpSellCursor INTO @UpSellId, @FromMC, @ToMC, @Link, @UserId, @WksId, @Date;
END

CLOSE UpSellCursor;
DEALLOCATE UpSellCursor;

END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT 1 FROM sys.triggers 
           WHERE Name = 'CNF_Upsell2MatrixCell_CT')
BEGIN
    DROP TRIGGER CNF_Upsell2MatrixCell_CT
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF  EXISTS (SELECT * 
            FROM sys.objects 
            WHERE object_id = OBJECT_ID('CNF_Upsell2MatrixCell') AND 
                  type in ('U'))
BEGIN
   DROP TABLE CNF_Upsell2MatrixCell
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>scoluccia</ADDEDBY><SQLVERSION>3222</SQLVERSION><RMTRACKLINK>IDBOS-2568</RMTRACKLINK><REASON>- Added a new field MaskIdDetail in CNF_DataMask in order to manage the detail mask
- Created a new table DATA_DmgDataDetails in order to manage the detail records of the Dmg_Data.
- Added a new field DATA_DmgDataDetails in DATA_DmgData in order to group all the details data
</REASON><TABLENAMES>CNF_DataMask=DataMaskId
DATA_DmgDataDetails=DmgDataDetailsId
DATA_DmgData=DmgDataId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
          WHERE Name = N'MaskIdDetail' 
          AND OBJECT_ID = OBJECT_ID(N'CNF_DataMask'))
BEGIN
  ALTER TABLE CNF_DataMask
  ADD MaskIdDetail [int] NULL 
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_CNF_DataMask_MaskIdDetail')
BEGIN                                                                              
   ALTER TABLE [CNF_DataMask]  WITH CHECK ADD CONSTRAINT [FK_CNF_DataMask_MaskIdDetail] FOREIGN KEY([MaskIdDetail])
  REFERENCES [CNF_Mask] ([MaskId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND TABLE_NAME = 'DATA_DmgDataDetails')
BEGIN
Create table DATA_DmgDataDetails
(
	[DmgDataDetailsId]    Integer IDENTITY(1,1) NOT NULL,
	[DmgCategoryId] [int] NOT NULL,
        [MaskId] [int] NOT NULL,
	[DetailGroupOrder] [int] NOT NULL,
Primary Key ([DmgDataDetailsId])
) 
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_DATA_DmgDataDetails_MaskId')
BEGIN                                                                              
   ALTER TABLE [DATA_DmgDataDetails]  WITH CHECK ADD CONSTRAINT [FK_DATA_DmgDataDetails_MaskId] FOREIGN KEY([MaskId])
  REFERENCES [CNF_Mask] ([MaskId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_DATA_DmgDataDetails_DmgCategoryId')
BEGIN                                                                              
   ALTER TABLE [DATA_DmgDataDetails]  WITH CHECK ADD CONSTRAINT [FK_DATA_DmgDataDetails_DmgCategoryId] FOREIGN KEY([DmgCategoryId])
  REFERENCES [CNF_DmgCategory] ([DmgCategoryId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
          WHERE Name = N'DmgDataDetailsId' 
          AND OBJECT_ID = OBJECT_ID(N'DATA_DmgData'))
BEGIN
  ALTER TABLE DATA_DmgData
  ADD [DmgDataDetailsId] [int] NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_DATA_DmgData_DmgDataDetailsId')
BEGIN                                                                              
  ALTER TABLE [DATA_DmgData] WITH CHECK ADD CONSTRAINT [FK_DATA_DmgData_DmgDataDetailsId] FOREIGN KEY([DmgDataDetailsId])
  REFERENCES [DATA_DmgDataDetails] ([DmgDataDetailsId])
END
</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>3221</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES>DATA_ShopCartItemLimit=ShopCartItemLimitID
cnf_accountrestriction=AccountRestrictionId
DATA_AccountLimit=AccountLimitDataId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.objects WHERE [name] = N'data_sale_SalesRestriction' AND [type] = 'TR')
BEGIN
      DROP TRIGGER [dbo].[data_sale_SalesRestriction];
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>
Create trigger [dbo].[data_sale_SalesRestriction] on [dbo].[DATA_Sale] FOR update
	 as
begin
	SET NOCOUNT ON;
    IF UPDATE(Approved) or Update(StatusCode)
    BEGIN

		Declare @NumberOfRestrictions Int = 0

		select @NumberOfRestrictions = Count(*)
		  from CNF_AccountRestriction
		 Where Enabled = 1

		if @NumberOfRestrictions &gt; 0
		BEGIN
			DECLARE @INS_SaleID int
			DECLARE @status int = 0 
			DECLARE @DR_status int

			DECLARE @RestrictionType int	
			
			DECLARE @CheckforRestraintOnly int = 0

			SELECT @status=i.Approved, @INS_SaleID = i.Saleid 
					FROM inserted i
						JOIN deleted d
								 ON i.SaleID = d.SaleID
								 AND ((d.paid = 0) or (i.paid &lt;&gt; d.Paid))
								 AND i.statuscode = 1

			if @status = 0 
			begin
				SELECT @DR_status = CASE WHEN i.StatusCode = 2 then  1
										 else 0
									 end, 
					   @INS_SaleID = i.Saleid 
						FROM inserted i
							  JOIN deleted d
									  ON i.[SaleID] = d.[SaleID]
										 AND i.[StatusCode] &lt;&gt; d.[StatusCode]
			end


			if @status = 1
			begin
--Reservation Account
				Insert into data_shopcartitemlimit
				select  data_sale.saleid,
				        0 as B2B,
						0 as  Billing,
						ISNULL(data_reservation.accountid, ODR.AccountID) as ReservationAccountID,
						0 TicketAccountID,
						data_saleitem.Matrixcellid,
						data_saleitem.Quantity,
						case when cnf_performance.PerformanceID is not null then cnf_performance.PerformanceID
												 else 9999999
						end ,
						case when cnf_performance.Eventid is not null then cnf_performance.Eventid
												 else  9999999
						end,
						data_sale.saleid,
						data_saleitem.saleitemid,
						case when data_saleitem.Quantity &lt; 0 then ISNULL((select top 1 1
																			from data_transaction
																			where data_transaction.transactiontype in (17, 18, 20, 40, 47)
																				and data_transaction.saleid = data_sale.saleid), 0)
								else 0
							end as UsageCheck

				from data_sale WITH(NOLOCK)
					LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
					INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
					LEFT  JOIN data_saleitem2Performance WITH(NOLOCK)			on data_saleitem2performance.saleitemid = data_saleitem.saleitemid
					LEFT  JOIN cnf_performance WITH(NOLOCK)						on cnf_Performance.performanceid = data_saleitem2performance.performanceid
					left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
					left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

					where data_sale.saleid = @INS_SaleID

--B2B Account
				Insert into data_shopcartitemlimit
				select  data_sale.saleid,
				        ISNULL(data_reservation.B2BAccountID, ODR.B2BAccountID) as B2B,
						0 as  Billing,
						0 as ReservationAccountID,
						0 TicketAccountID,
						data_saleitem.Matrixcellid,
						data_saleitem.Quantity,
						case when cnf_performance.PerformanceID is not null then cnf_performance.PerformanceID
												 else 9999999
						end ,
						case when cnf_performance.Eventid is not null then cnf_performance.Eventid
												 else  9999999
						end,
						data_sale.saleid,
						data_saleitem.saleitemid,
						case when data_saleitem.Quantity &lt; 0 then ISNULL((select top 1 1
																			from data_transaction
																			where data_transaction.transactiontype in (17, 18, 20, 40, 47)
																				and data_transaction.saleid = data_sale.saleid), 0)
								else 0
							end as UsageCheck

				from data_sale WITH(NOLOCK)
					LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
					INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
					LEFT  JOIN data_saleitem2Performance WITH(NOLOCK)			on data_saleitem2performance.saleitemid = data_saleitem.saleitemid
					LEFT  JOIN cnf_performance WITH(NOLOCK)						on cnf_Performance.performanceid = data_saleitem2performance.performanceid
					left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
					left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

					where data_sale.saleid = @INS_SaleID
					  and ISNULL(data_reservation.B2BAccountID, ODR.B2BAccountID) is not null

--Billing Account
				Insert into data_shopcartitemlimit
				select  data_sale.saleid,
				        0 as B2B,
				        ISNULL(data_reservation.BillingAccountId, ODR.BillingAccountId) as BillingAccountId,
						0 as ReservationAccountID,
						0 TicketAccountID,
						data_saleitem.Matrixcellid,
						data_saleitem.Quantity,
						case when cnf_performance.PerformanceID is not null then cnf_performance.PerformanceID
												 else 9999999
						end ,
						case when cnf_performance.Eventid is not null then cnf_performance.Eventid
												 else  9999999
						end,
						data_sale.saleid,
						data_saleitem.saleitemid,
						case when data_saleitem.Quantity &lt; 0 then ISNULL((select top 1 1
																			from data_transaction
																			where data_transaction.transactiontype in (17, 18, 20, 40, 47)
																				and data_transaction.saleid = data_sale.saleid), 0)
								else 0
							end as UsageCheck

				from data_sale WITH(NOLOCK)
					LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
					INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
					LEFT  JOIN data_saleitem2Performance WITH(NOLOCK)			on data_saleitem2performance.saleitemid = data_saleitem.saleitemid
					LEFT  JOIN cnf_performance WITH(NOLOCK)						on cnf_Performance.performanceid = data_saleitem2performance.performanceid
					left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
					left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

					where data_sale.saleid = @INS_SaleID
					  and ISNULL(data_reservation.BillingAccountId, ODR.BillingAccountId) is not null

--Ticket Account
				Insert into data_shopcartitemlimit
				select  data_sale.saleid,
				        0 as B2B,
				        0 as BillingAccountId,
						0 as ReservationAccountID,
						data_ticket.accountid TicketAccountID,
						data_saleitem.Matrixcellid,
						case when data_ticket.ticketid is not null then case when data_saleitem.Quantity &lt; 0 then -1 else 1 end
										else data_saleitem.Quantity
									end Quantity,
						case when cnf_performance.PerformanceID is not null then cnf_performance.PerformanceID
												 else 9999999
						end ,
						case when cnf_performance.Eventid is not null then cnf_performance.Eventid
												 else  9999999
						end,
						data_sale.saleid,
						data_saleitem.saleitemid,
						case when data_saleitem.Quantity &lt; 0 then ISNULL((select top 1 1
																			from data_transaction
																			where data_transaction.transactiontype in (17, 18, 20, 40, 47)
																				and data_transaction.saleid = data_sale.saleid), 0)
								else 0
							end as UsageCheck

					from data_sale WITH(NOLOCK)
						LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
						INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
						LEFT  JOIN data_saleitem2ticket WITH(NOLOCK)				on data_saleitem2ticket.saleitemid = data_saleitem.saleitemid
						LEFT  JOIN data_saleitem2Performance WITH(NOLOCK)			on data_saleitem2performance.saleitemid = data_saleitem.saleitemid
						LEFT  JOIN cnf_performance WITH(NOLOCK)						on cnf_Performance.performanceid = data_saleitem2performance.performanceid
						LEFT  JOIN data_ticket WITH(NOLOCK)							on data_ticket.ticketid = data_saleitem2ticket.ticketid
						left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
						left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

					where data_sale.saleid = @INS_SaleID
					  and data_ticket.accountid is not null

--Reservation Account
				Insert into data_shopcartitemlimit
				select  data_sale.saleid,
				        0 as B2B,
						0 as  Billing,
						ISNULL(data_reservation.accountid, ODR.AccountID) as ReservationAccountID,
						0 TicketAccountID,
						data_saleitem.Matrixcellid,
						data_saleitem.Quantity,
						0,
						0,
						data_sale.saleid,
						data_saleitem.saleitemid,
						case when data_saleitem.Quantity &lt; 0 then ISNULL((select top 1 1
																			from data_transaction
																			where data_transaction.transactiontype in (17, 18, 20, 40, 47)
																				and data_transaction.saleid = data_sale.saleid), 0)
								else 0
							end as UsageCheck

				from data_sale WITH(NOLOCK)
					LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
					INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
					left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
					left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

					where data_sale.saleid = @INS_SaleID

--B2B Account
				Insert into data_shopcartitemlimit
				select  data_sale.saleid,
				        ISNULL(data_reservation.B2BAccountID, ODR.B2BAccountID) as B2B,
						0 as  Billing,
						0 as ReservationAccountID,
						0 TicketAccountID,
						data_saleitem.Matrixcellid,
						data_saleitem.Quantity,
						0,
						0,
						data_sale.saleid,
						data_saleitem.saleitemid,
						case when data_saleitem.Quantity &lt; 0 then ISNULL((select top 1 1
																			from data_transaction
																			where data_transaction.transactiontype in (17, 18, 20, 40, 47)
																				and data_transaction.saleid = data_sale.saleid), 0)
								else 0
							end as UsageCheck

				from data_sale WITH(NOLOCK)
					LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
					INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
					left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
					left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

					where data_sale.saleid = @INS_SaleID
					  and ISNULL(data_reservation.B2BAccountID, ODR.B2BAccountID) is not null

--Billing Account
				Insert into data_shopcartitemlimit
				select  data_sale.saleid,
				        0 as B2B,
				        ISNULL(data_reservation.BillingAccountId, ODR.BillingAccountId) as BillingAccountId,
						0 as ReservationAccountID,
						0 TicketAccountID,
						data_saleitem.Matrixcellid,
						data_saleitem.Quantity,
						0,
						0,
						data_sale.saleid,
						data_saleitem.saleitemid,
						case when data_saleitem.Quantity &lt; 0 then ISNULL((select top 1 1
																			from data_transaction
																			where data_transaction.transactiontype in (17, 18, 20, 40, 47)
																				and data_transaction.saleid = data_sale.saleid), 0)
								else 0
							end as UsageCheck

				from data_sale WITH(NOLOCK)
					LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
					INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
					left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
					left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

					where data_sale.saleid = @INS_SaleID
					  and ISNULL(data_reservation.BillingAccountId, ODR.BillingAccountId) is not null

--Ticket Account
				Insert into data_shopcartitemlimit
				select  data_sale.saleid,
				        0 as B2B,
				        0 as BillingAccountId,
						0 as ReservationAccountID,
						data_ticket.accountid TicketAccountID,
						data_saleitem.Matrixcellid,
						case when data_ticket.ticketid is not null then case when data_saleitem.Quantity &lt; 0 then -1 else 1 end
										else data_saleitem.Quantity
									end Quantity,
						0,
						0,
						data_sale.saleid,
						data_saleitem.saleitemid,
						case when data_saleitem.Quantity &lt; 0 then ISNULL((select top 1 1
																			from data_transaction
																			where data_transaction.transactiontype in (17, 18, 20, 40, 47)
																				and data_transaction.saleid = data_sale.saleid), 0)
								else 0
							end as UsageCheck

					from data_sale WITH(NOLOCK)
						LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
						INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
						LEFT  JOIN data_saleitem2ticket WITH(NOLOCK)				on data_saleitem2ticket.saleitemid = data_saleitem.saleitemid
						LEFT  JOIN data_ticket WITH(NOLOCK)							on data_ticket.ticketid = data_saleitem2ticket.ticketid
						left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
						left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

					where data_sale.saleid = @INS_SaleID
					  and data_ticket.accountid is not null	

			END

--Reservation Deletes
			if @DR_status = 1
			begin
			--Reservation Account
				Insert into data_shopcartitemlimit
				select  data_sale.saleid,
				        0 as B2B,
						0 as  Billing,
						ISNULL(data_reservation.accountid, ODR.AccountID) as ReservationAccountID,
						0 TicketAccountID,
						data_saleitem.Matrixcellid,
						data_saleitem.Quantity,
						case when cnf_performance.PerformanceID is not null then cnf_performance.PerformanceID
												 else 9999999
						end ,
						case when cnf_performance.Eventid is not null then cnf_performance.Eventid
												 else  9999999
						end,
						data_sale.saleid,
						data_saleitem.saleitemid,
						case when data_saleitem.Quantity &lt; 0 then ISNULL((select top 1 1
																			from data_transaction
																			where data_transaction.transactiontype in (17, 18, 20, 40, 47)
																				and data_transaction.saleid = data_sale.saleid), 0)
								else 0
							end as UsageCheck

				from data_sale WITH(NOLOCK)
					LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
					INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
					LEFT  JOIN data_saleitem2Performance WITH(NOLOCK)			on data_saleitem2performance.saleitemid = data_saleitem.saleitemid
					LEFT  JOIN cnf_performance WITH(NOLOCK)						on cnf_Performance.performanceid = data_saleitem2performance.performanceid
					left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
					left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

					where data_sale.saleid = @INS_SaleID
					  and data_saleitem.quantity &lt; 0

--B2B Account
				Insert into data_shopcartitemlimit
				select  data_sale.saleid,
				        ISNULL(data_reservation.B2BAccountID, ODR.B2BAccountID) as B2B,
						0 as  Billing,
						0 as ReservationAccountID,
						0 TicketAccountID,
						data_saleitem.Matrixcellid,
						data_saleitem.Quantity,
						case when cnf_performance.PerformanceID is not null then cnf_performance.PerformanceID
												 else 9999999
						end ,
						case when cnf_performance.Eventid is not null then cnf_performance.Eventid
												 else  9999999
						end,
						data_sale.saleid,
						data_saleitem.saleitemid,
						case when data_saleitem.Quantity &lt; 0 then ISNULL((select top 1 1
																			from data_transaction
																			where data_transaction.transactiontype in (17, 18, 20, 40, 47)
																				and data_transaction.saleid = data_sale.saleid), 0)
								else 0
							end as UsageCheck

				from data_sale WITH(NOLOCK)
					LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
					INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
					LEFT  JOIN data_saleitem2Performance WITH(NOLOCK)			on data_saleitem2performance.saleitemid = data_saleitem.saleitemid
					LEFT  JOIN cnf_performance WITH(NOLOCK)						on cnf_Performance.performanceid = data_saleitem2performance.performanceid
					left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
					left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

					where data_sale.saleid = @INS_SaleID
					  and ISNULL(data_reservation.B2BAccountID, ODR.B2BAccountID) is not null
					  and data_saleitem.quantity &lt; 0

--Billing Account
				Insert into data_shopcartitemlimit
				select  data_sale.saleid,
				        0 as B2B,
				        ISNULL(data_reservation.BillingAccountId, ODR.BillingAccountId) as BillingAccountId,
						0 as ReservationAccountID,
						0 TicketAccountID,
						data_saleitem.Matrixcellid,
						data_saleitem.Quantity,
						case when cnf_performance.PerformanceID is not null then cnf_performance.PerformanceID
												 else 9999999
						end ,
						case when cnf_performance.Eventid is not null then cnf_performance.Eventid
												 else  9999999
						end,
						data_sale.saleid,
						data_saleitem.saleitemid,
						case when data_saleitem.Quantity &lt; 0 then ISNULL((select top 1 1
																			from data_transaction
																			where data_transaction.transactiontype in (17, 18, 20, 40, 47)
																				and data_transaction.saleid = data_sale.saleid), 0)
								else 0
							end as UsageCheck

				from data_sale WITH(NOLOCK)
					LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
					INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
					LEFT  JOIN data_saleitem2Performance WITH(NOLOCK)			on data_saleitem2performance.saleitemid = data_saleitem.saleitemid
					LEFT  JOIN cnf_performance WITH(NOLOCK)						on cnf_Performance.performanceid = data_saleitem2performance.performanceid
					left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
					left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

					where data_sale.saleid = @INS_SaleID
					  and ISNULL(data_reservation.BillingAccountId, ODR.BillingAccountId) is not null
					  and data_saleitem.quantity &lt; 0

--Ticket Account
				Insert into data_shopcartitemlimit
				select  data_sale.saleid,
				        0 as B2B,
				        0 as BillingAccountId,
						0 as ReservationAccountID,
						(select data_ticket.AccountID
							  from data_saleitem2ticket WITH(NOLOCK)
								INNER JOIN data_ticket WITH(NOLOCK)				ON data_ticket.ticketid = data_saleitem2ticket.ticketid
							  where data_saleitem2ticket.saleitemid = data_saleitem.OrigSaleItemId
								and data_saleitem2ticket.operationtype = 2) TicketAccountID,
						data_saleitem.Matrixcellid,
						case when data_ticket.ticketid is not null then case when data_saleitem.Quantity &lt; 0 then -1 else 1 end
										else data_saleitem.Quantity
									end Quantity,
						case when cnf_performance.PerformanceID is not null then cnf_performance.PerformanceID
												 else 9999999
						end ,
						case when cnf_performance.Eventid is not null then cnf_performance.Eventid
												 else  9999999
						end,
						data_sale.saleid,
						data_saleitem.saleitemid,
						case when data_saleitem.Quantity &lt; 0 then ISNULL((select top 1 1
																			from data_transaction
																			where data_transaction.transactiontype in (17, 18, 20, 40, 47)
																				and data_transaction.saleid = data_sale.saleid), 0)
								else 0
							end as UsageCheck

					from data_sale WITH(NOLOCK)
						LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
						INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
						LEFT  JOIN data_saleitem2ticket WITH(NOLOCK)				on data_saleitem2ticket.saleitemid = data_saleitem.saleitemid
						LEFT  JOIN data_saleitem2Performance WITH(NOLOCK)			on data_saleitem2performance.saleitemid = data_saleitem.saleitemid
						LEFT  JOIN cnf_performance WITH(NOLOCK)						on cnf_Performance.performanceid = data_saleitem2performance.performanceid
						LEFT  JOIN data_ticket WITH(NOLOCK)							on data_ticket.ticketid = data_saleitem2ticket.ticketid
						left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
						left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

					where data_sale.saleid = @INS_SaleID
					  and data_ticket.accountid is not null
					  and data_saleitem.quantity &lt; 0

--Reservation Account
				Insert into data_shopcartitemlimit
				select  data_sale.saleid,
				        0 as B2B,
						0 as  Billing,
						ISNULL(data_reservation.accountid, ODR.AccountID) as ReservationAccountID,
						0 TicketAccountID,
						data_saleitem.Matrixcellid,
						data_saleitem.Quantity,
						0,
						0,
						data_sale.saleid,
						data_saleitem.saleitemid,
						case when data_saleitem.Quantity &lt; 0 then ISNULL((select top 1 1
																			from data_transaction
																			where data_transaction.transactiontype in (17, 18, 20, 40, 47)
																				and data_transaction.saleid = data_sale.saleid), 0)
								else 0
							end as UsageCheck

				from data_sale WITH(NOLOCK)
					LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
					INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
					left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
					left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

					where data_sale.saleid = @INS_SaleID
					  and data_saleitem.quantity &lt; 0

--B2B Account
				Insert into data_shopcartitemlimit
				select  data_sale.saleid,
				        ISNULL(data_reservation.B2BAccountID, ODR.B2BAccountID) as B2B,
						0 as  Billing,
						0 as ReservationAccountID,
						0 TicketAccountID,
						data_saleitem.Matrixcellid,
						data_saleitem.Quantity,
						0,
						0,
						data_sale.saleid,
						data_saleitem.saleitemid,
						case when data_saleitem.Quantity &lt; 0 then ISNULL((select top 1 1
																			from data_transaction
																			where data_transaction.transactiontype in (17, 18, 20, 40, 47)
																				and data_transaction.saleid = data_sale.saleid), 0)
								else 0
							end as UsageCheck

				from data_sale WITH(NOLOCK)
					LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
					INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
					left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
					left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

					where data_sale.saleid = @INS_SaleID
					  and ISNULL(data_reservation.B2BAccountID, ODR.B2BAccountID) is not null
					  and data_saleitem.quantity &lt; 0

--Billing Account
				Insert into data_shopcartitemlimit
				select  data_sale.saleid,
				        0 as B2B,
				        ISNULL(data_reservation.BillingAccountId, ODR.BillingAccountId) as BillingAccountId,
						0 as ReservationAccountID,
						0 TicketAccountID,
						data_saleitem.Matrixcellid,
						data_saleitem.Quantity,
						0,
						0,
						data_sale.saleid,
						data_saleitem.saleitemid,
						case when data_saleitem.Quantity &lt; 0 then ISNULL((select top 1 1
																			from data_transaction
																			where data_transaction.transactiontype in (17, 18, 20, 40, 47)
																				and data_transaction.saleid = data_sale.saleid), 0)
								else 0
							end as UsageCheck

				from data_sale WITH(NOLOCK)
					LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
					INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
					left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
					left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

					where data_sale.saleid = @INS_SaleID
					  and ISNULL(data_reservation.BillingAccountId, ODR.BillingAccountId) is not null
					  and data_saleitem.quantity &lt; 0

--Ticket Account
				Insert into data_shopcartitemlimit
				select  data_sale.saleid,
				        0 as B2B,
				        0 as BillingAccountId,
						0 as ReservationAccountID,
						(select data_ticket.AccountID
							  from data_saleitem2ticket WITH(NOLOCK)
								INNER JOIN data_ticket WITH(NOLOCK)				ON data_ticket.ticketid = data_saleitem2ticket.ticketid
							  where data_saleitem2ticket.saleitemid = data_saleitem.OrigSaleItemId
								and data_saleitem2ticket.operationtype = 2) TicketAccountID,
						data_saleitem.Matrixcellid,
						case when data_ticket.ticketid is not null then case when data_saleitem.Quantity &lt; 0 then -1 else 1 end
										else data_saleitem.Quantity
									end Quantity,
						0,
						0,
						data_sale.saleid,
						data_saleitem.saleitemid,
						case when data_saleitem.Quantity &lt; 0 then ISNULL((select top 1 1
																			from data_transaction
																			where data_transaction.transactiontype in (17, 18, 20, 40, 47)
																				and data_transaction.saleid = data_sale.saleid), 0)
								else 0
							end as UsageCheck

					from data_sale WITH(NOLOCK)
						LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
						INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
						LEFT  JOIN data_saleitem2ticket WITH(NOLOCK)				on data_saleitem2ticket.saleitemid = data_saleitem.saleitemid
						LEFT  JOIN data_ticket WITH(NOLOCK)							on data_ticket.ticketid = data_saleitem2ticket.ticketid
						left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
						left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

					where data_sale.saleid = @INS_SaleID
					  and data_ticket.accountid is not null	
					  and data_saleitem.quantity &lt; 0
			end

			delete from data_shopcartitemlimit where PerformanceID = 9999999
			delete from data_shopcartitemlimit where Quantity = 0
			--select * 		from data_shopcartitemlimit
			
			Exec otn_sp_CheckAccountRestrictions 0, @INS_SaleID


		end
	end
end</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>ALTER TABLE [dbo].[DATA_Sale] ENABLE TRIGGER [data_sale_SalesRestriction]</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3220</SQLVERSION><RMTRACKLINK>IDBOS-2686</RMTRACKLINK><REASON>0 - Drop Foreign Key FK__CNF_TaxBr__TaxId__2121D3D7 from CNF_TaxBracket
1 - Drop Foreign Key FK_CNF_TaxBracket_Last_UserId_Log from CNF_TaxBracket
2 - Drop Foreign Key FK_CNF_TaxBracket_Last_WorkstationId_Log from CNF_TaxBracket
3 - Drop Table CNF_TaxBracket
4 - Drop Store Procedure sp_ui_CNF_TaxBracket_delete
5 - Drop Store Procedure sp_ui_CNF_TaxBracket_update
6 - Drop Store Procedure sp_ui_CNF_TaxBracket_insert</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
            WHERE TABLE_NAME = N'CNF_TaxBracket'
              AND CONSTRAINT_NAME = N'FK__CNF_TaxBr__TaxId__2121D3D7')          
BEGIN
  ALTER TABLE [CNF_TaxBracket]
  DROP CONSTRAINT  FK__CNF_TaxBr__TaxId__2121D3D7
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
            WHERE TABLE_NAME = N'CNF_TaxBracket'
              AND CONSTRAINT_NAME = N'FK_CNF_TaxBracket_Last_UserId_Log')          
BEGIN
  ALTER TABLE [CNF_TaxBracket]
  DROP CONSTRAINT  FK_CNF_TaxBracket_Last_UserId_Log
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
            WHERE TABLE_NAME = N'CNF_TaxBracket'
              AND CONSTRAINT_NAME = N'FK_CNF_TaxBracket_Last_WorkstationId_Log')          
BEGIN
  ALTER TABLE [CNF_TaxBracket]
  DROP CONSTRAINT  FK_CNF_TaxBracket_Last_WorkstationId_Log
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'CNF_TaxBracket')) 
DROP TABLE CNF_TaxBracket</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT * 
          FROM sys.procedures
          WHERE name = 'sp_ui_CNF_TaxBracket_delete')
BEGIN
  DROP PROCEDURE sp_ui_CNF_TaxBracket_delete
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT * 
          FROM sys.procedures
          WHERE name = 'sp_ui_CNF_TaxBracket_update')
BEGIN
  DROP PROCEDURE sp_ui_CNF_TaxBracket_update
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT * 
          FROM sys.procedures
          WHERE name = 'sp_ui_CNF_TaxBracket_insert')
BEGIN
  DROP PROCEDURE sp_ui_CNF_TaxBracket_insert
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3219</SQLVERSION><RMTRACKLINK>IDBOS-2442</RMTRACKLINK><REASON>0 - Added Column ForceUseExistingAccount in table CNF_MatrixCell</REASON><TABLENAMES>CNF_MatrixCell=MatrixCellId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
          WHERE Name = N'ForceUseExistingAccount' 
          AND OBJECT_ID = OBJECT_ID(N'CNF_MatrixCell'))
BEGIN
  ALTER TABLE CNF_MatrixCell
  ADD ForceUseExistingAccount [smallint]
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>3218</SQLVERSION><RMTRACKLINK>IDBOS-2552</RMTRACKLINK><REASON>B2B Companies (Partners configuration in BOS)</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS(select * FROM sys.views where name = 'VW_AccountLimit')
	DROP View VW_AccountLimit</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>CREATE view [dbo].[VW_AccountLimit]
as

select  accountid,
		dmgcategoryID,
		AccountRestrictionId,
		PerformanceID,
		ISNULL(PerformanceName, EventName) as PerformanceName,
		EventName,
		Eventid,
		PerfDateTime,
		Saledate,                   
		cast(Description as varchar(100))  as ResDescription, 
		AccountType + ' ' + RestrictionDescription as AccountType, 
		ISNULL(Saleid, ' ') as SaleID ,             
		ISNULL(TicketName, ' ') as TicketName,               
		ISNULL(ReservationAccountQuantity,  ' ') as ReservationAccountQuantity,               
		ISNULL(WorkstationAK,  ' ') as WorkstationAK,         
		ISNULL(UserName,  ' ') as UserName,         
		ISNULL(reservationAK,  ' ') as reservationAK         
 from (             
			  select  DATA_AccountLimit.accountid, 
			      Null dmgcategoryID,
				  CNF_AccountRestriction.AccountRestrictionId as AccountRestrictionId,     
				  CNF_AccountRestriction.StartDateTime as StartDateTime,                   
				  CNF_AccountRestriction.EndDateTime as EndDateTime,                       
				  CNF_AccountRestriction.Enabled as Enabled,                                 
				  CNF_AccountRestriction.Description as Description,                         
				  CNF_AccountRestriction.RestrictionType as RestrictionType,                   
				  CNF_AccountRestriction.ReservationAccountLimit as ReservationAccountLimit,  
				  CNF_AccountRestriction.TicketAccountLimit as TicketAccountLimit,             
				  Lookup_0.Description as RestrictionDescription, 
				  AccountType.Description as AccountType,				  
				  DATA_AccountLimit.SaleDate,                                                  
				  DATA_AccountLimit.SaleID,                                                    
				  DATA_AccountLimit.SaleItemid,                                                
				  '[' + cnf_Matrixcell.code + ']' + cnf_Matrixcell.Name as TicketName,            
				  DATA_AccountLimit.ReservationAccountQuantity,                                                                        
				  cnf_User.username,                                                
				  cnf_workstation.workstationAK,                                                           
				  data_reservation.reservationAK as reservationAK,
				  cnf_performance.PerformanceID,
				  cnf_performance.Eventid,
				  cnf_performance.PerfDateTime,
				  cnf_performance.PerformanceName,
				  cnf_Event.EventName

			  from CNF_AccountRestriction with (nolock)                                            
				INNER JOIN DATA_AccountLimit WITH(NOLOCK)						ON data_accountlimit.accountrestrictionid = cnf_accountrestriction.accountrestrictionid  				
				LEFT  JOIN cnf_performance WITH(NOLOCK)							ON cnf_performance.Performanceid = data_accountlimit.Performanceid
				LEFT  JOIN cnf_event WITH(NOLOCK)								ON cnf_event.eventid = cnf_performance.eventid
				INNER JOIN DATA_SaleItem WITH(NOLOCK)							ON data_saleitem.saleitemid = data_accountLimit.SaleitemID
				INNER JOIN data_sale WITH(NOLOCK)								ON data_sale.saleid = data_saleitem.saleid
				INNER JOIN cnf_user WITH(NOLOCK)								ON cnf_user.Userid = data_sale.Userid
				INNER JOIN cnf_Workstation WITH(NOLOCK)							ON cnf_Workstation.workstationid = data_sale.workstationid
				INNER JOIN cnf_Matrixcell WITH(NOLOCK)							ON cnf_matrixcell.matrixcellid = data_saleitem.matrixcellid     
				LEFT  JOIN data_reservation WITH(NOLOCK)						ON data_reservation.saleid = data_accountlimit.saleid         
				inner join (SELECT CNF_LookUp.ItemId,              
						           ISNULL(dbo.CNF_MultiLanguage.Translation, dbo.CNF_LookUp.Description) AS Description                  
						      FROM CNF_Lookup with (nolock)                                                            
									LEFT JOIN CNF_MultiLanguage with (nolock) ON (CNF_Lookup.LookupTableId=CNF_MultiLanguage.ComponentName)    
																				   and (CNF_Lookup.ItemId=CNF_MultiLanguage.PropertyName)                   
																				   and (CNF_MultiLanguage.FormName = 'LOOKUP')                       
																				   and (CNF_MultiLanguage.LanguageId = 0)                             
						WHERE (CNF_LookUp.LookUpTableId = 818)                                                     
					) AS Lookup_0											ON Lookup_0.ItemId=CNF_AccountRestriction.RestrictionType  
				inner join (SELECT CNF_LookUp.ItemId,              
						           ISNULL(dbo.CNF_MultiLanguage.Translation, dbo.CNF_LookUp.Description) AS Description                  
						      FROM CNF_Lookup with (nolock)                                                            
									LEFT JOIN CNF_MultiLanguage with (nolock) ON (CNF_Lookup.LookupTableId=CNF_MultiLanguage.ComponentName)    
																				   and (CNF_Lookup.ItemId=CNF_MultiLanguage.PropertyName)                   
																				   and (CNF_MultiLanguage.FormName = 'LOOKUP')                       
																				   and (CNF_MultiLanguage.LanguageId = 0)                             
						WHERE (CNF_LookUp.LookUpTableId = 823)                                                     
					) AS AccountType											ON AccountType.ItemId=CNF_AccountRestriction.AccountType  
					
			UNION ALL

			select CNF_AccountRestriction2Account.Accountid,
			      CNF_AccountRestriction2dmgCategory.dmgcategoryid,
				  CNF_AccountRestriction.AccountRestrictionId as AccountRestrictionId,      
				  CNF_AccountRestriction.StartDateTime as StartDateTime,              
				  CNF_AccountRestriction.EndDateTime as EndDateTime,                
				  CNF_AccountRestriction.Enabled as Enabled,                        
				  data_note.Note as Description,          
				  null as RestrictionType,                                     
				  null as ReservationAccountLimit,                              
				  CNF_AccountRestriction.TicketAccountLimit as TicketAccountLimit,       
				  Lookup_0.Description as RestrictionDescription,   
				  AccountType.Description as AccountType,
				  data_note.notedate,                                         
				  null,                                                        
				  null,                                                         
				  null,                                                         
				  null,                                                                                                               
				  cnf_User.username,                                                
				  cnf_workstation.workstationAK,                                    
				  null,
				  null,
				  null,
				  null,
				  null,
				  null

			  from                                                                
				CNF_AccountRestriction with (nolock)                              
				  left  join CNF_AccountRestriction2Account with (nolock)			ON CNF_AccountRestriction2Account.AccountRestrictionId = CNF_AccountRestriction.AccountRestrictionId       
				  left  join CNF_AccountRestriction2dmgCategory with (nolock)		ON CNF_AccountRestriction2dmgCategory.AccountRestrictionId = CNF_AccountRestriction.AccountRestrictionId    
				INNER JOIN data_note WITH(NOLOCK)								on data_note.notekey = CNF_AccountRestriction.AccountRestrictionId       
												and data_note.notetype = 518               
												and data_note.note = 'Reset completed'        
				INNER JOIN cnf_User WITH(NOLOCK)                 ON cnf_User.userid = data_Note.Userid        
				INNER JOIN cnf_Workstation WITH(NOLOCK)          ON cnf_workstation.workstationid = data_note.workstationid     
				inner join (	  SELECT CNF_LookUp.ItemId,                                       
						   ISNULL(dbo.CNF_MultiLanguage.Translation, dbo.CNF_LookUp.Description) AS Description               
						FROM CNF_Lookup with (nolock)                                   
						LEFT JOIN CNF_MultiLanguage with (nolock) ON (CNF_Lookup.LookupTableId=CNF_MultiLanguage.ComponentName)     
											   and (CNF_Lookup.ItemId=CNF_MultiLanguage.PropertyName)       
											   and (CNF_MultiLanguage.FormName = 'LOOKUP')      
											   and (CNF_MultiLanguage.LanguageId = 0)         
						WHERE (CNF_LookUp.LookUpTableId = 818)                                
					) AS Lookup_0											ON Lookup_0.ItemId=CNF_AccountRestriction.RestrictionType 
				inner join (SELECT CNF_LookUp.ItemId,              
						           ISNULL(dbo.CNF_MultiLanguage.Translation, dbo.CNF_LookUp.Description) AS Description                  
						      FROM CNF_Lookup with (nolock)                                                            
									LEFT JOIN CNF_MultiLanguage with (nolock) ON (CNF_Lookup.LookupTableId=CNF_MultiLanguage.ComponentName)    
																				   and (CNF_Lookup.ItemId=CNF_MultiLanguage.PropertyName)                   
																				   and (CNF_MultiLanguage.FormName = 'LOOKUP')                       
																				   and (CNF_MultiLanguage.LanguageId = 0)                             
						WHERE (CNF_LookUp.LookUpTableId = 823)                                                     
					) AS AccountType											ON AccountType.ItemId=CNF_AccountRestriction.AccountType  					
    
   
 )p</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_GetAccountRestrictions_Performance]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_GetAccountRestrictions_Performance</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>CREATE Procedure [dbo].[otn_sp_GetAccountRestrictions_Performance]( @AccountRestrictionID int,
																	@Quantity int,														
																	@RestrictionType int,
																	@AccountType int,
																	@AccountID int,
																	@PerformanceID int,
																	@EventID int,
																	@SaleID int,
																	@SaleItemID int,
																	@CheckforRestrictionOnly int,
																	@PreventSale int OUTPUT,
																	@RejectReasonErrorCode int OUTPUT,
																	@RejectType int OUTPUT,
																	@RejectRestrictionDescription varchar(100) OUTPUT,
																	@RejectRemainingAmount int OUTPUT
																	)  

AS    
BEGIN

	DECLARE @SalesDate datetime = getdate();
	DECLARE @Limit int
	DECLARE	@PerDayLimit int
	DECLARE	@PerWeekLimit int
	DECLARE	@PerMonthLimit int
	DECLARE	@PerQuarterLimit int
	DECLARE	@PerSemiAnnualLimit int
	DECLARE	@PerYearLimit int
	DECLARE @ReservationAccountQuantity_DayofYear int
	DECLARE @ReservationAccountQuantity_WeekofYear int
	DECLARE @ReservationAccountQuantity_MonthofYear int
	DECLARE @ReservationAccountQuantity_QuarterofYear int
	DECLARE @ReservationAccountQuantity_SemiAnnualofYear int
	DECLARE @ReservationAccountQuantity_Year int

	DECLARE @RestrictLimit int = 99999
	DECLARE @ReservationAccountOwner int = 1
	DECLARE @TicketAccountOwner int = 2
    DECLARE @Description varchar(max)
	DECLARE @CheckOnly int = 1
	DECLARE @RestrictionLimit int

	SET @PreventSale = 0  
	SET @RejectReasonErrorCode = 0
	SET @RejectType = 0
	SET	@RejectRestrictionDescription = ''
	SET @RejectRemainingAmount = 0


	if ((@PerformanceID is not null) and (@EventID is not null))
	BEGIN
		DECLARE Restriction_Cursor CURSOR LOCAL FOR
				select AccountRestrictionID,
			       Description,
					Limit,
					PerDayLimit,
					PerWeekLimit,
					PerMonthLimit,
					PerQuarterLimit,
					PerSemiAnnualLimit,
					PerYearLimit,
					(case when ReservationAccountQuantity_DayofYear &gt; 0 then ReservationAccountQuantity_DayofYear
						else 0
					end) ReservationAccountQuantity_DayofYear,
					(case when ReservationAccountQuantity_WeekofYear &gt; 0 then ReservationAccountQuantity_WeekofYear
						else 0
					end) ReservationAccountQuantity_WeekofYear,
					(case when ReservationAccountQuantity_MonthofYear &gt; 0 then ReservationAccountQuantity_MonthofYear
						else 0
					end) ReservationAccountQuantity_MonthofYear,
					(case when ReservationAccountQuantity_QuarterofYear &gt; 0 then ReservationAccountQuantity_QuarterofYear
						else 0
					end) ReservationAccountQuantity_QuarterofYear,
					(case when ReservationAccountQuantity_SemiAnnualofYear &gt; 0 then ReservationAccountQuantity_SemiAnnualofYear
						else 0
					end) ReservationAccountQuantity_SemiAnnualofYear,
					(case when ReservationAccountQuantity_Year &gt; 0 then ReservationAccountQuantity_Year
						else 0
					end) ReservationAccountQuantity_Year
		from (
				select distinct CNF_AccountRestriction.AccountRestrictionID,
				        CNF_AccountRestriction.Description,
						CNF_AccountRestriction.Limit,
						ISNULL(CNF_AccountRestriction.PerDayLimit, @RestrictLimit) as PerDayLimit,
						ISNULL(CNF_AccountRestriction.PerWeekLimit, @RestrictLimit) as PerWeekLimit,
						ISNULL(CNF_AccountRestriction.PerMonthLimit, @RestrictLimit) as PerMonthLimit,
						ISNULL(CNF_AccountRestriction.PerQuarterLimit, @RestrictLimit) as PerQuarterLimit,
						ISNULL(CNF_AccountRestriction.PerSemiAnnualLimit, @RestrictLimit) as PerSemiAnnualLimit,
						ISNULL(CNF_AccountRestriction.PerYearLimit, @RestrictLimit) as PerYearLimit,
						ISNULL((select sum(case when cast(saledate as date) = cast(@SalesDate as date) then ReservationAccountQuantity
										else 0
									end)
								from DATA_AccountLimit
									INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
								where (DATA_AccountLimit.Accountid = @AccountID)
									and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
									and DATA_AccountLimit.SaleDate &gt;= CNF_AccountRestriction.StartDateTime
									and data_accountLimit.PerformanceID = @PerformanceID
						), 0) ReservationAccountQuantity_DayofYear,
						ISNULL((select sum(case when (cast(datepart(yy, saledate) as varchar(4)) + '-' + cast(datepart(wk, saledate) as varchar(2))) = cast(datepart(yy, @SalesDate) as varchar(4)) + '-' + cast(datepart(wk, @SalesDate) as varchar(2)) then ReservationAccountQuantity
											else 0
										end)
								from DATA_AccountLimit
												INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
								where (DATA_AccountLimit.Accountid = @AccountID)
								and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
								and DATA_AccountLimit.SaleDate &gt;= CNF_AccountRestriction.StartDateTime
								and data_accountLimit.PerformanceID = @PerformanceID
						), 0) ReservationAccountQuantity_WeekofYear,
						ISNULL((select sum(case when (cast(datepart(yy, saledate) as varchar(4)) + '-' + cast(datepart(mm, saledate) as varchar(2))) = cast(datepart(yy, @SalesDate) as varchar(4)) + '-' + cast(datepart(mm, @SalesDate) as varchar(2)) then ReservationAccountQuantity
											else 0
										end)
								from DATA_AccountLimit
												INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
								where (DATA_AccountLimit.Accountid = @AccountID)
								and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
								and DATA_AccountLimit.SaleDate &gt;= CNF_AccountRestriction.StartDateTime
								and data_accountLimit.PerformanceID = @PerformanceID
						), 0) ReservationAccountQuantity_MonthofYear,

						ISNULL((select sum(case when (DATEPART(year, SaleDate) = DATEPART(year, @SalesDate)) then 
																	CASE when (DATEPART(QUARTER, SaleDate) = DATEPART(QUARTER, @SalesDate)) then ReservationAccountQuantity
																		 else 0
																	end
												else 0
											end)
								from DATA_AccountLimit
												INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
								where (DATA_AccountLimit.Accountid = @AccountID)
								and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
								and DATA_AccountLimit.SaleDate &gt;= CNF_AccountRestriction.StartDateTime
								and data_accountLimit.PerformanceID = @PerformanceID
						), 0) ReservationAccountQuantity_QuarterofYear,

						ISNULL((select sum(case when (DATEPART(year, SaleDate) = DATEPART(year, @SalesDate)) then 
															CASE WHEN ((CASE when DATEPART(QUARTER, SaleDate) in (1, 2) then 1
																			else 2
																	end) =
																	(CASE when DATEPART(QUARTER, @SalesDate) in (1, 2) then 1
																			else 2
																	end))  then ReservationAccountQuantity
																else 0
															end 

										else 0
									end)
								from DATA_AccountLimit
												INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
								where (DATA_AccountLimit.Accountid = @AccountID)
								and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
								and DATA_AccountLimit.SaleDate &gt;= CNF_AccountRestriction.StartDateTime
								and data_accountLimit.PerformanceID = @PerformanceID
						), 0) ReservationAccountQuantity_SemiAnnualofYear,

						ISNULL((select sum(case when (cast(datepart(yy, saledate) as varchar(4))) = cast(datepart(yy, @SalesDate) as varchar(4)) then ReservationAccountQuantity
											else 0
										end)
								from DATA_AccountLimit
												INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
								where (DATA_AccountLimit.Accountid = @AccountID)
								and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
								and DATA_AccountLimit.SaleDate &gt;= CNF_AccountRestriction.StartDateTime
								and data_accountLimit.PerformanceID = @PerformanceID
						), 0) ReservationAccountQuantity_Year

				from CNF_AccountRestriction WITH(NOLOCK)
																					
				where CNF_AccountRestriction.AccountRestrictionID = @AccountRestrictionID

				UNION ALL

				select distinct CNF_AccountRestriction.AccountRestrictionID,
				        CNF_AccountRestriction.Description,
						CNF_AccountRestriction.Limit,
						ISNULL(CNF_AccountRestriction.PerDayLimit, @RestrictLimit) as PerDayLimit,
						ISNULL(CNF_AccountRestriction.PerWeekLimit, @RestrictLimit) as PerWeekLimit,
						ISNULL(CNF_AccountRestriction.PerMonthLimit, @RestrictLimit) as PerMonthLimit,
						ISNULL(CNF_AccountRestriction.PerQuarterLimit, @RestrictLimit) as PerQuarterLimit,
						ISNULL(CNF_AccountRestriction.PerSemiAnnualLimit, @RestrictLimit) as PerSemiAnnualLimit,
						ISNULL(CNF_AccountRestriction.PerYearLimit, @RestrictLimit) as PerYearLimit,
						ISNULL((select sum(case when cast(saledate as date) = cast(@SalesDate as date) then ReservationAccountQuantity
										else 0
									end)
								from DATA_AccountLimit
									INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
								where (DATA_AccountLimit.Accountid = @AccountID)
									and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
									and DATA_AccountLimit.SaleDate &gt;= CNF_AccountRestriction.StartDateTime
									and data_accountLimit.PerformanceID in (select performanceid from cnf_performance where Eventid =  @EventId)
						), 0) ReservationAccountQuantity_DayofYear,
						ISNULL((select sum(case when (cast(datepart(yy, saledate) as varchar(4)) + '-' + cast(datepart(wk, saledate) as varchar(2))) = cast(datepart(yy, @SalesDate) as varchar(4)) + '-' + cast(datepart(wk, @SalesDate) as varchar(2)) then ReservationAccountQuantity
											else 0
										end)
								from DATA_AccountLimit
												INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
								where (DATA_AccountLimit.Accountid = @AccountID)
								and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
								and DATA_AccountLimit.SaleDate &gt;= CNF_AccountRestriction.StartDateTime
								and data_accountLimit.PerformanceID in (select performanceid from cnf_performance where Eventid =  @EventId)
						), 0) ReservationAccountQuantity_WeekofYear,
						ISNULL((select sum(case when (cast(datepart(yy, saledate) as varchar(4)) + '-' + cast(datepart(mm, saledate) as varchar(2))) = cast(datepart(yy, @SalesDate) as varchar(4)) + '-' + cast(datepart(mm, @SalesDate) as varchar(2)) then ReservationAccountQuantity
											else 0
										end)
								from DATA_AccountLimit
												INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
								where (DATA_AccountLimit.Accountid = @AccountID)
								and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
								and DATA_AccountLimit.SaleDate &gt;= CNF_AccountRestriction.StartDateTime
								and data_accountLimit.PerformanceID in (select performanceid from cnf_performance where Eventid =  @EventId)
						), 0) ReservationAccountQuantity_MonthofYear,

						ISNULL((select sum(case when (DATEPART(year, SaleDate) = DATEPART(year, @SalesDate)) then 
																	CASE when (DATEPART(QUARTER, SaleDate) = DATEPART(QUARTER, @SalesDate)) then ReservationAccountQuantity
																		 else 0
																	end
												else 0
											end)
								from DATA_AccountLimit
												INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
								where (DATA_AccountLimit.Accountid = @AccountID)
								and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
								and DATA_AccountLimit.SaleDate &gt;= CNF_AccountRestriction.StartDateTime
								and data_accountLimit.PerformanceID in (select performanceid from cnf_performance where Eventid =  @EventId)
						), 0) ReservationAccountQuantity_QuarterofYear,

						ISNULL((select sum(case when (DATEPART(year, SaleDate) = DATEPART(year, @SalesDate)) then 
															CASE WHEN ((CASE when DATEPART(QUARTER, SaleDate) in (1, 2) then 1
																			else 2
																	end) =
																	(CASE when DATEPART(QUARTER, @SalesDate) in (1, 2) then 1
																			else 2
																	end))  then ReservationAccountQuantity
																else 0
															end 

										else 0
									end)
								from DATA_AccountLimit
												INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
								where (DATA_AccountLimit.Accountid = @AccountID)
								and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
								and DATA_AccountLimit.SaleDate &gt;= CNF_AccountRestriction.StartDateTime
								and data_accountLimit.PerformanceID in (select performanceid from cnf_performance where Eventid =  @EventId)
						), 0) ReservationAccountQuantity_SemiAnnualofYear,

						ISNULL((select sum(case when (cast(datepart(yy, saledate) as varchar(4))) = cast(datepart(yy, @SalesDate) as varchar(4)) then ReservationAccountQuantity
											else 0
										end)
								from DATA_AccountLimit
												INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
								where (DATA_AccountLimit.Accountid = @AccountID)
								and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
								and DATA_AccountLimit.SaleDate &gt;= CNF_AccountRestriction.StartDateTime
								and data_accountLimit.PerformanceID in (select performanceid from cnf_performance where Eventid =  @EventId)
						), 0) ReservationAccountQuantity_Year

				from CNF_AccountRestriction WITH(NOLOCK)
																					
				where CNF_AccountRestriction.AccountRestrictionID = @AccountRestrictionID

			)p

		where (ISNULL(Limit, 0) &gt; 0)



		OPEN Restriction_Cursor

		FETCH NEXT FROM Restriction_Cursor INTO
							@AccountRestrictionID, 
							@Description,
							@Limit,
							@PerDayLimit,
							@PerWeekLimit,
							@PerMonthLimit,
							@PerQuarterLimit,
							@PerSemiAnnualLimit,
							@PerYearLimit,
							@ReservationAccountQuantity_DayofYear,
							@ReservationAccountQuantity_WeekofYear,
							@ReservationAccountQuantity_MonthofYear,
							@ReservationAccountQuantity_QuarterofYear,
							@ReservationAccountQuantity_SemiAnnualofYear,
							@ReservationAccountQuantity_Year


		WHILE @@FETCH_STATUS = 0
		BEGIN	
			if @Limit is not null and @PerformanceId is not null 
			BEGIN
				if @Quantity &lt;= @Limit and @Quantity &lt;= (@Limit - @ReservationAccountQuantity_Year)
				BEGIN
					If @CheckforRestrictionOnly &lt;&gt; @CheckOnly
					BEGIN
							DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

							INSERT INTO [dbo].[DATA_AccountLimit]
											([AccountRestrictionId]
											,[AccountId]
											,[PerformanceId]
											,[SaleId]
											,[SaleItemId]
											,[SaleDate]
											,[ReservationAccountQuantity])
										VALUES
											(@AccountRestrictionID
											,@AccountID
											,@PerformanceID
											,@SaleID
											,@SaleItemID
											,@SalesDate
											,@Quantity)
					END
				END
				ELSE
				BEGIN
					Set @PreventSale = 1
					Set @RejectType = 3
					if (@PerformanceID is not null) and (@EventID is not null)
					BEGIN
						if @RejectReasonErrorCode = 0
						begin
							SET @RejectRemainingAmount =  (@Limit - @ReservationAccountQuantity_Year)
							SET @RejectRestrictionDescription = @Description
							if @RejectRemainingAmount &lt; 0 
								SET @RejectRemainingAmount = 0

							if @RejectRemainingAmount = 0	   						 
								Set @RejectReasonErrorCode = 5087
							else
								Set @RejectReasonErrorCode = 5088
						end
					END
				END			
			END


		FETCH NEXT FROM Restriction_Cursor INTO
							@AccountRestrictionID, 
							@Description,
							@Limit,
							@PerDayLimit,
							@PerWeekLimit,
							@PerMonthLimit,
							@PerQuarterLimit,
							@PerSemiAnnualLimit,
							@PerYearLimit,
							@ReservationAccountQuantity_DayofYear,
							@ReservationAccountQuantity_WeekofYear,
							@ReservationAccountQuantity_MonthofYear,
							@ReservationAccountQuantity_QuarterofYear,
							@ReservationAccountQuantity_SemiAnnualofYear,
							@ReservationAccountQuantity_Year


		END	
	
		CLOSE Restriction_Cursor;
		DEALLOCATE Restriction_Cursor;
	END	

RETURN
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_GetAccountRestrictions_Ticket]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_GetAccountRestrictions_Ticket</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>CREATE Procedure [dbo].otn_sp_GetAccountRestrictions_Ticket(   @AccountRestrictionID int,
																		@Quantity int,														
																		@AccountType int,
																		@RestrictionType int,
																		@AccountID int,
																		@PerformanceID int,
																		@EventID int,
																		@SaleID int,
																		@SaleItemID int,
																		@CheckforRestrictionOnly int,
																		@PreventSale int OUTPUT,
																		@RejectReasonErrorCode int OUTPUT,
																		@RejectType int OUTPUT,
																		@RejectRestrictionDescription varchar(100) OUTPUT,
																		@RejectRemainingAmount int OUTPUT
																		)  

AS    
BEGIN

	DECLARE @SalesDate datetime = getdate();
	DECLARE @Limit Int
	DECLARE	@PerDayLimit int
	DECLARE	@PerWeekLimit int
	DECLARE	@PerMonthLimit int
	DECLARE	@PerQuarterLimit int
	DECLARE	@PerSemiAnnualLimit int
	DECLARE	@PerYearLimit int
	DECLARE @ReservationAccountQuantity_DayofYear int
	DECLARE @ReservationAccountQuantity_WeekofYear int
	DECLARE @ReservationAccountQuantity_MonthofYear int
	DECLARE @ReservationAccountQuantity_QuarterofYear int
	DECLARE @ReservationAccountQuantity_SemiAnnualofYear int
	DECLARE @ReservationAccountQuantity_Year int

	DECLARE @RestrictLimit int = 99999
	DECLARE @ReservationAccountOwner int = 1
    DECLARE @Description varchar(max)
	DECLARE @CheckOnly int = 1
	DECLARE @RestrictionLimit int

	SET @PreventSale = 0  
	SET @RejectReasonErrorCode = 0
	SET @RejectType = 0
	SET	@RejectRestrictionDescription = ''
	SET @RejectRemainingAmount = 0


	if ((@PerformanceID is null) and (@EventID is null))
	BEGIN
		DECLARE Restriction_Cursor CURSOR LOCAL FOR
			select  AccountRestrictionID,
			        Description,
					Limit,
					PerDayLimit,
					PerWeekLimit,
					PerMonthLimit,
					PerQuarterLimit,
					PerSemiAnnualLimit,
					PerYearLimit,
					case when ReservationAccountQuantity_DayofYear &gt; 0 then ReservationAccountQuantity_DayofYear
						else 0
					end ReservationAccountQuantity_DayofYear,
					case when ReservationAccountQuantity_WeekofYear &gt; 0 then ReservationAccountQuantity_WeekofYear
						else 0
					end ReservationAccountQuantity_WeekofYear,
					case when ReservationAccountQuantity_MonthofYear &gt; 0 then ReservationAccountQuantity_MonthofYear
						else 0
					end ReservationAccountQuantity_MonthofYear,

					case when ReservationAccountQuantity_QuarterofYear &gt; 0 then ReservationAccountQuantity_QuarterofYear
						else 0
					end ReservationAccountQuantity_QuarterofYear,
					case when ReservationAccountQuantity_SemiAnnualofYear &gt; 0 then ReservationAccountQuantity_SemiAnnualofYear
						else 0
					end ReservationAccountQuantity_SemiAnnualofYear,
					case when ReservationAccountQuantity_Year &gt; 0 then ReservationAccountQuantity_Year
						else 0
					end ReservationAccountQuantity_Year
				
		from (
				select distinct CNF_AccountRestriction.AccountRestrictionID,
				        CNF_AccountRestriction.Description,
						CNF_AccountRestriction.Limit,
						ISNULL(CNF_AccountRestriction.PerDayLimit, @RestrictLimit) as PerDayLimit,
						ISNULL(CNF_AccountRestriction.PerWeekLimit, @RestrictLimit) as PerWeekLimit,
						ISNULL(CNF_AccountRestriction.PerMonthLimit, @RestrictLimit) as PerMonthLimit,
						ISNULL(CNF_AccountRestriction.PerQuarterLimit, @RestrictLimit) as PerQuarterLimit,
						ISNULL(CNF_AccountRestriction.PerSemiAnnualLimit, @RestrictLimit) as PerSemiAnnualLimit,
						ISNULL(CNF_AccountRestriction.PerYearLimit, @RestrictLimit) as PerYearLimit,
						ISNULL((select sum(case when cast(saledate as date) = cast(@SalesDate as date) then ReservationAccountQuantity
										else 0
									end)
								from DATA_AccountLimit
								INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
								where (DATA_AccountLimit.Accountid = @AccountID)
									and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
									and DATA_AccountLimit.SaleDate &gt;= CNF_AccountRestriction.StartDateTime
						), 0) ReservationAccountQuantity_DayofYear,
						ISNULL((select sum(case when (cast(datepart(yy, saledate) as varchar(4)) + '-' + cast(datepart(wk, saledate) as varchar(2))) = cast(datepart(yy, @SalesDate) as varchar(4)) + '-' + cast(datepart(wk, @SalesDate) as varchar(2)) then ReservationAccountQuantity
											else 0
										end)
								from DATA_AccountLimit
									INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
								where (DATA_AccountLimit.Accountid = @AccountID)
								and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
								and DATA_AccountLimit.SaleDate &gt;= CNF_AccountRestriction.StartDateTime
						), 0) ReservationAccountQuantity_WeekofYear,
						ISNULL((select sum(case when (cast(datepart(yy, saledate) as varchar(4)) + '-' + cast(datepart(mm, saledate) as varchar(2))) = cast(datepart(yy, @SalesDate) as varchar(4)) + '-' + cast(datepart(mm, @SalesDate) as varchar(2)) then ReservationAccountQuantity
											else 0
										end)
								from DATA_AccountLimit
									INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
								where (DATA_AccountLimit.Accountid = @AccountID)
								and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
								and DATA_AccountLimit.SaleDate &gt;= CNF_AccountRestriction.StartDateTime
						), 0) ReservationAccountQuantity_MonthofYear,

						ISNULL((select sum(case when (DATEPART(year, SaleDate) = DATEPART(year, @SalesDate)) then 
																	CASE when (DATEPART(QUARTER, SaleDate) = DATEPART(QUARTER, @SalesDate)) then ReservationAccountQuantity
																		 else 0
																	end
												else 0
											end)
								from DATA_AccountLimit
									INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
								where (DATA_AccountLimit.Accountid = @AccountID)
								and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
								and DATA_AccountLimit.SaleDate &gt;= CNF_AccountRestriction.StartDateTime
						), 0) ReservationAccountQuantity_QuarterofYear,

						ISNULL((select sum(case when (DATEPART(year, SaleDate) = DATEPART(year, @SalesDate)) then 
															CASE WHEN ((CASE when DATEPART(QUARTER, SaleDate) in (1, 2) then 1
																			else 2
																	end) =
																	(CASE when DATEPART(QUARTER, @SalesDate) in (1, 2) then 1
																			else 2
																	end))  then ReservationAccountQuantity
																else 0
															end 

										else 0
									end)
								from DATA_AccountLimit
									INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
								where (DATA_AccountLimit.Accountid = @AccountID)
								and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
								and DATA_AccountLimit.SaleDate &gt;= CNF_AccountRestriction.StartDateTime
						), 0) ReservationAccountQuantity_SemiAnnualofYear,

						ISNULL((select sum(case when (cast(datepart(yy, saledate) as varchar(4))) = cast(datepart(yy, @SalesDate) as varchar(4)) then ReservationAccountQuantity
											else 0
										end)
								from DATA_AccountLimit
								INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
								where (DATA_AccountLimit.Accountid = @AccountID)
								and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
								and DATA_AccountLimit.SaleDate &gt;= CNF_AccountRestriction.StartDateTime
						), 0) ReservationAccountQuantity_Year


			from CNF_AccountRestriction WITH(NOLOCK)
				where CNF_AccountRestriction.AccountRestrictionID = @AccountRestrictionID

			)p
		where (ISNULL(Limit, 0) &gt; 0)


		OPEN Restriction_Cursor

		FETCH NEXT FROM Restriction_Cursor INTO
							@AccountRestrictionID, 
							@Description,
							@Limit,
							@PerDayLimit,
							@PerWeekLimit,
							@PerMonthLimit,
							@PerQuarterLimit,
							@PerSemiAnnualLimit,
							@PerYearLimit,
							@ReservationAccountQuantity_DayofYear,
							@ReservationAccountQuantity_WeekofYear,
							@ReservationAccountQuantity_MonthofYear,
							@ReservationAccountQuantity_QuarterofYear,
							@ReservationAccountQuantity_SemiAnnualofYear,
							@ReservationAccountQuantity_Year


		WHILE @@FETCH_STATUS = 0
		BEGIN
	
			If @Limit is not null and @PerformanceId is null 
			BEGIN
				if @Quantity &lt;= @Limit
				BEGIN
					if (((@Quantity + @ReservationAccountQuantity_DayofYear) &lt;= @PerDayLimit)   and
						((@Quantity + @ReservationAccountQuantity_WeekofYear) &lt;= @PerWeekLimit)  and
						((@Quantity + @ReservationAccountQuantity_MonthofYear) &lt;= @PerMonthLimit) and
						((@Quantity + @ReservationAccountQuantity_QuarterofYear) &lt;= @PerQuarterLimit) and
						((@Quantity + @ReservationAccountQuantity_SemiAnnualofYear) &lt;= @PerSemiAnnualLimit) and
						((@Quantity + @ReservationAccountQuantity_Year) &lt;= @PerYearLimit)) and
						 (@Quantity &lt;= (@Limit - @ReservationAccountQuantity_Year))
					BEGIN
							If @CheckforRestrictionOnly &lt;&gt; @CheckOnly
							BEGIN								
									DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

									INSERT INTO [dbo].[DATA_AccountLimit]
													([AccountRestrictionId]
													,[AccountId]
													,[PerformanceId]
													,[SaleId]
													,[SaleItemId]
													,[SaleDate]
													,[ReservationAccountQuantity])
												VALUES
													(@AccountRestrictionID
													,@AccountID
													,@PerformanceID
													,@SaleID
													,@SaleItemID
													,@SalesDate
													,@Quantity)
							END
					END
					ELSE
					BEGIN
						Set @PreventSale = 1
						Set @RejectType = 1
						if @RejectReasonErrorCode = 0
						begin					    
							if ((@Quantity + @ReservationAccountQuantity_DayofYear) &gt; @PerDayLimit)
							begin
								SET @RejectRemainingAmount =  (@PerDayLimit - @ReservationAccountQuantity_DayofYear)
								SET @RejectRestrictionDescription = @Description
							
								if @RejectRemainingAmount &lt; 0 
								   SET @RejectRemainingAmount = 0

								if @RejectRemainingAmount = 0
									Set @RejectReasonErrorCode = 5075
								else
									Set @RejectReasonErrorCode = 5076
							end
						end

						if @RejectReasonErrorCode = 0
						begin
							if ((@Quantity + @ReservationAccountQuantity_WeekofYear) &gt; @PerWeekLimit)
							begin
								SET @RejectRemainingAmount =  (@PerWeekLimit - @ReservationAccountQuantity_WeekofYear) 
								SET @RejectRestrictionDescription = @Description
								if @RejectRemainingAmount &lt; 0 
								   SET @RejectRemainingAmount = 0

								if @RejectRemainingAmount = 0
									Set @RejectReasonErrorCode = 5077
								else
									Set @RejectReasonErrorCode = 5078
							end
						end

						if @RejectReasonErrorCode = 0
						begin
							if ((@Quantity + @ReservationAccountQuantity_MonthofYear) &gt; @PerMonthLimit)
							begin
								SET @RejectRemainingAmount =  (@PerMonthLimit - @ReservationAccountQuantity_MonthofYear) 
								SET @RejectRestrictionDescription = @Description
								if @RejectRemainingAmount &lt; 0 
								   SET @RejectRemainingAmount = 0

								if @RejectRemainingAmount = 0   							 
									Set @RejectReasonErrorCode = 5079
								else
									Set @RejectReasonErrorCode = 5080	
							end
						end

						if @RejectReasonErrorCode = 0
						begin
							if ((@Quantity + @ReservationAccountQuantity_QuarterofYear) &gt; @PerQuarterLimit)
							begin
								SET @RejectRemainingAmount =  (@PerQuarterLimit - @ReservationAccountQuantity_QuarterofYear) 
								SET @RejectRestrictionDescription = @Description
								if @RejectRemainingAmount &lt; 0 
								   SET @RejectRemainingAmount = 0

								if @RejectRemainingAmount = 0   							 
									Set @RejectReasonErrorCode = 5090
								else
									Set @RejectReasonErrorCode = 5091	
							end
						end

						if @RejectReasonErrorCode = 0
						begin
							if ((@Quantity + @ReservationAccountQuantity_SemiAnnualofYear) &gt; @PerSemiAnnualLimit)
							begin
								SET @RejectRemainingAmount =  (@PerSemiAnnualLimit - @ReservationAccountQuantity_SemiAnnualofYear) 
								SET @RejectRestrictionDescription = @Description
								if @RejectRemainingAmount &lt; 0 
								   SET @RejectRemainingAmount = 0

								if @RejectRemainingAmount = 0   							 
									Set @RejectReasonErrorCode = 5092
								else
									Set @RejectReasonErrorCode = 5093	
							end
						end

						if @RejectReasonErrorCode = 0
						begin
							if ((@Quantity + @ReservationAccountQuantity_Year) &gt; @PerYearLimit) 
							begin
								SET @RejectRemainingAmount =  (@PerYearLimit - @ReservationAccountQuantity_Year)
								SET @RejectRestrictionDescription = @Description 
								if @RejectRemainingAmount &lt; 0 
								   SET @RejectRemainingAmount = 0

								if @RejectRemainingAmount = 0
									Set @RejectReasonErrorCode = 5081
								else
									Set @RejectReasonErrorCode = 5082
							end
						end

						if @RejectReasonErrorCode = 0
						begin
							if ((@Quantity + @ReservationAccountQuantity_Year) &gt; @Limit) 
							begin
								SET @RejectRemainingAmount =  (@Limit - @ReservationAccountQuantity_Year)
								SET @RejectRestrictionDescription = @Description 
								if @RejectRemainingAmount &lt; 0 
								   SET @RejectRemainingAmount = 0

								if @RejectRemainingAmount = 0
									Set @RejectReasonErrorCode = 5083
								else
									Set @RejectReasonErrorCode = 5084
							end
						end

					END
				END
				ELSE
				BEGIN
					Set @PreventSale = 1
					Set @RejectType = 1
					if @RejectReasonErrorCode = 0
					begin
						SET @RejectRemainingAmount =  (@Limit - @ReservationAccountQuantity_Year)
						SET @RejectRestrictionDescription = @Description 
						if @RejectRemainingAmount &lt; 0 
							SET @RejectRemainingAmount = 0

						if @RejectRemainingAmount = 0
							Set @RejectReasonErrorCode = 5085
						else
							Set @RejectReasonErrorCode = 5086
					end
				END
			END


		FETCH NEXT FROM Restriction_Cursor INTO
							@AccountRestrictionID, 
							@Description,
							@Limit,
							@PerDayLimit,
							@PerWeekLimit,
							@PerMonthLimit,
							@PerQuarterLimit,
							@PerSemiAnnualLimit,
							@PerYearLimit,
							@ReservationAccountQuantity_DayofYear,
							@ReservationAccountQuantity_WeekofYear,
							@ReservationAccountQuantity_MonthofYear,
							@ReservationAccountQuantity_QuarterofYear,
							@ReservationAccountQuantity_SemiAnnualofYear,
							@ReservationAccountQuantity_Year


		END	
	
		CLOSE Restriction_Cursor;
		DEALLOCATE Restriction_Cursor;
	END

RETURN
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_GetAccountRestrictions]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_GetAccountRestrictions</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>CREATE Procedure [dbo].[otn_sp_GetAccountRestrictions]( @AccountRestrictionID int,
                                                        @Quantity int,														
														@RestrictionType int,
														@AccountType int,
														@AccountID int,
														@PerformanceID int,
														@EventID int,
														@SaleID int,
														@SaleItemID int,
														@CheckforRestrictionOnly int,
														@PreventSale int OUTPUT,
														@RejectReasonErrorCode int OUTPUT,
														@RejectType int OUTPUT,
														@RejectRestrictionDescription varchar(100) OUTPUT,
														@RejectRemainingAmount int OUTPUT
														)  

AS    
BEGIN

	DECLARE @TicketType int = 1
	DECLARE @PerformanceType int = 2

	if @PreventSale = 0 and @RestrictionType = @TicketType
	BEGIN
		Exec otn_sp_GetAccountRestrictions_Ticket       @AccountRestrictionID,
														@Quantity,														
														@RestrictionType,
														@AccountType,
														@AccountID,
														@PerformanceID,
														@EventID,
														@SaleID,
														@SaleItemID,
														@CheckforRestrictionOnly,
														@PreventSale OUTPUT,
														@RejectReasonErrorCode OUTPUT,
														@RejectType OUTPUT,
														@RejectRestrictionDescription OUTPUT,
														@RejectRemainingAmount OUTPUT
	end

	if @PreventSale = 0 and @RestrictionType = @PerformanceType
	BEGIN
		Exec otn_sp_GetAccountRestrictions_Performance   @AccountRestrictionID,
														 @Quantity,														
														 @RestrictionType,
														 @AccountType,
														 @AccountID,
														 @PerformanceID,
														 @EventID,
														 @SaleID,
														 @SaleItemID,
														 @CheckforRestrictionOnly,
														 @PreventSale OUTPUT,
														 @RejectReasonErrorCode OUTPUT,
														 @RejectType OUTPUT,
														 @RejectRestrictionDescription OUTPUT,
														 @RejectRemainingAmount OUTPUT

	END
	
RETURN;
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_AR_B2BOwner_Matrixcell]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_AR_B2BOwner_Matrixcell</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>CREATE PROCEDURE [otn_sp_AR_B2BOwner_Matrixcell]        (
														  @GUID        varchar(100), 
													      @SalesId		int,
														  @PreventSale int OUTPUT,
														  @RejectReasonErrorCode int OUTPUT,
														  @RejectType int OUTPUT,
														  @RejectRestrictionDescription varchar(100) OUTPUT,
														  @RejectRemainingAmount int OUTPUT
														) 
AS    
BEGIN

	DECLARE @SalesDate datetime = getdate();
	DECLARE @RestrictionType int = 1
	DECLARE @AccountType int = 2
	DECLARE @AccountID int
	DECLARE @OldAccountRestrictionID int = 99999
	DECLARE @Limit int
	DECLARE @AccountRestrictionID int
	DECLARE @MatrixCellID int
	DECLARE @Quantity int
	DECLARE @FullQuantity int
	DECLARE @PerformanceID int
	DECLARE @EventID int
	DECLARE @SaleID int
	DECLARE @SaleitemID int
	DECLARE @CheckforRestrictionOnly int
	DECLARE @OLD_Resevation_Owner int
	DECLARE @CountofMatrixCells int = 0
	DECLARE @Prevent int = 0

	
--Reservation Owner	
	SET @RestrictionType = 1
	set @CountofMatrixCells = 0
	SET @OLD_Resevation_Owner = 99999

	DECLARE Check_Cursor CURSOR LOCAL FOR
		select  B2B_Owner,
				Res_Table.MatrixCellID,
				sum(Quantity) as Quantity,
				SaleID,
				SaleitemID,
				CheckforRestrictionOnly,
				cnf_AccountRestriction.AccountRestrictionID,
				cnf_AccountRestriction.Limit

		  from data_shopcartitemlimit Res_Table
				INNER JOIN cnf_AccountRestriction2MatrixCell WITH(NOLOCK)				ON cnf_AccountRestriction2MatrixCell.MatrixCellID = Res_Table.MatrixCellID
				LEFT JOIN cnf_AccountRestriction2Account WITH(NOLOCK)					ON (cnf_AccountRestriction2Account.AccountID = Res_Table.B2B_Owner)																							
					                                                                       and cnf_accountrestriction2Account.AccountRestrictionID = CNF_AccountRestriction2MatrixCell.AccountRestrictionId
																						   
			    LEFT JOIN cnf_AccountRestriction2DMGCategory WITH(NOLOCK)				ON (cnf_AccountRestriction2DMGCategory.DMGCategoryID = (select DMGCategoryID from data_account WITH(NOLOCK) where data_account.accountid = Res_Table.B2B_Owner))																							
					                                                                       and cnf_AccountRestriction2DMGCategory.AccountRestrictionID = CNF_AccountRestriction2MatrixCell.AccountRestrictionId				
				
				INNER JOIN cnf_AccountRestriction WITH(NOLOCK)							ON cnf_AccountRestriction.AccountRestrictionId = cnf_AccountRestriction2MatrixCell.AccountRestrictionId

	     where cnf_AccountRestriction.Enabled = 1
		   and Convert(date, GetDAte(), 120) between Convert(date, StartDateTime, 120) and Convert(date, EndDateTime, 120)
		   and CNF_AccountRestriction.RestrictionType = @RestrictionType
		   and Res_Table.B2B_Owner is not null
		   and Limit is not null
		   and cnf_AccountRestriction.AccountType = @AccountType
		   and B2B_Owner &lt;&gt; 0
		   and ((cnf_AccountRestriction2Account.accountid is not null) or (cnf_AccountRestriction2DMGCategory.dmgcategoryid is not null))
		   and ISNULL(Res_Table.PerformanceID, 0) = 0
		   and (((@SalesID = 0) and (Res_Table.ShopCartGuid = @GUID))
		         or (('0' = @GUID) and (Res_Table.Saleid = @SalesID)))

			 GROUP BY B2B_Owner,
							 Res_Table.MatrixCellID,
							 SaleID,
							 SaleitemID,
							 CheckforRestrictionOnly,
							 cnf_AccountRestriction.AccountRestrictionID,
							 cnf_AccountRestriction.Limit

		 order by cnf_AccountRestriction.AccountRestrictionID

	OPEN Check_Cursor

	FETCH NEXT FROM Check_Cursor INTO
						@AccountID,
						@MatrixCellID,
						@Quantity,
						@SaleID,
						@SaleitemID,
						@CheckforRestrictionOnly,
	                    @AccountRestrictionID,
						@Limit


	WHILE @@FETCH_STATUS = 0
	BEGIN
		IF @OldAccountRestrictionID &lt;&gt; @AccountRestrictionID and @AccountID &lt;&gt; @OLD_Resevation_Owner and (@PreventSale = 0)
		BEGIN 

			SET @Prevent = 0;

			select @FullQuantity = sum(Quantity),  
				    @CountofMatrixCells = Count(*)
				from data_shopcartitemlimit Res_Table
				where MatrixCellID in (select MatrixcellId 
										from cnf_AccountRestriction2MatrixCell WITH(NOLOCK)									
										where cnf_AccountRestriction2MatrixCell.AccountRestrictionId = @AccountRestrictionID)
				and B2B_Owner = @AccountID
				and ISNULL(PerformanceID, 0) = 0
			    and (((@SalesID = 0) and (Res_Table.ShopCartGuid = @GUID))
					 or (('0' = @GUID) and (Res_Table.Saleid = @SalesID)))

			if @FullQuantity &gt; 0
			Begin			  
				if @CountofMatrixCells = 1 						
					Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @RestrictionType, @AccountType, @AccountID,  
														null, null, @SaleID, @SaleitemID, @CheckforRestrictionOnly, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
				else
				begin
					Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @RestrictionType, @AccountType, @AccountID,  
														null, null, @SaleID, @SaleitemID, 1, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
					set @Prevent = @PreventSale

					if @Prevent = 0 and @CheckforRestrictionOnly = 0 
					begin
						    DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

						INSERT INTO [dbo].[DATA_AccountLimit]
										([AccountRestrictionId]
										,[AccountId]
										,[PerformanceId]
										,[SaleId]
										,[SaleItemId]
										,[SaleDate]
										,[ReservationAccountQuantity])
									VALUES
										(@AccountRestrictionID
										,@AccountID
										,@PerformanceID
										,@SaleID
										,@SaleItemID
										,@SalesDate
										,@FullQuantity)						 
					end
				end
			end
			else
			begin
				INSERT INTO [dbo].[DATA_AccountLimit]
								([AccountRestrictionId]
								,[AccountId]
								,[PerformanceId]
								,[SaleId]
								,[SaleItemId]
								,[SaleDate]
								,[ReservationAccountQuantity])
							VALUES
								(@AccountRestrictionID
								,@AccountID
								,@PerformanceID
								,@SaleID
								,@SaleItemID
								,@SalesDate
								,@Quantity)	
			end
		END	
		ELSE
		BEGIN
			IF @OldAccountRestrictionID = @AccountRestrictionID and @AccountID = @OLD_Resevation_Owner and @Quantity &lt; 0
			begin
								INSERT INTO [dbo].[DATA_AccountLimit]
												([AccountRestrictionId]
												,[AccountId]
												,[PerformanceId]
												,[SaleId]
												,[SaleItemId]
												,[SaleDate]
												,[ReservationAccountQuantity])
											VALUES
												(@AccountRestrictionID
												,@AccountID
												,@PerformanceID
												,@SaleID
												,@SaleItemID
												,@SalesDate
												,@Quantity)	



			end 
			IF @OldAccountRestrictionID &lt;&gt; @AccountRestrictionID and @AccountID &lt;&gt; @OLD_Resevation_Owner
			begin
				if @Prevent = 0 and @CheckforRestrictionOnly = 0 
				begin
				    DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

					INSERT INTO [dbo].[DATA_AccountLimit]
									([AccountRestrictionId]
									,[AccountId]
									,[PerformanceId]
									,[SaleId]
									,[SaleItemId]
									,[SaleDate]
									,[ReservationAccountQuantity])
								VALUES
									(@AccountRestrictionID
									,@AccountID
									,@PerformanceID
									,@SaleID
									,@SaleItemID
									,@SalesDate
									,@Quantity)						 
				end
			end
		END

		Set @OldAccountRestrictionID = @AccountRestrictionID
		SET @OLD_Resevation_Owner = @AccountID

		FETCH NEXT FROM Check_Cursor INTO
						@AccountID,
						@MatrixCellID,
						@Quantity,
						@SaleID,
						@SaleitemID,
						@CheckforRestrictionOnly,
	                    @AccountRestrictionID,
						@Limit
	END

	CLOSE Check_Cursor;
	DEALLOCATE Check_Cursor;


RETURN;

END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_AR_B2BOwner_Performance]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_AR_B2BOwner_Performance</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>CREATE PROCEDURE [otn_sp_AR_B2BOwner_Performance]  (
                                                      @GUID        varchar(100),
													  @SalesId		int,
													  @PreventSale int OUTPUT,
													  @RejectReasonErrorCode int OUTPUT,
													  @RejectType int OUTPUT,
													  @RejectRestrictionDescription varchar(100) OUTPUT,
													  @RejectRemainingAmount int OUTPUT
                                                    ) 
AS    
BEGIN

	DECLARE @SalesDate datetime = getdate();
	DECLARE @RestrictionType int = 2
	DECLARE @AccountType int = 2
	DECLARE @AccountID int
	DECLARE @OldAccountRestrictionID int = 99999
	DECLARE @AccountRestrictionID int
	DECLARE @MatrixCellID int
	DECLARE @Quantity int
	DECLARE @FullQuantity int
	DECLARE @PerformanceID int
	DECLARE @EventID int
	DECLARE @SaleID int
	DECLARE @SaleitemID int
	DECLARE @CheckforRestrictionOnly int
	DECLARE @Limit int
	DECLARE @OLD_Resevation_Owner int
	DECLARE @CountofMatrixCells int = 0
	DECLARE @Prevent int = 0
	DECLARE @Old_PerformanceID int = 0
	DECLARE @Old_EventID int = 0

	
--Performance Reservation Owner Check
	Set @OldAccountRestrictionID = 99999

	DECLARE Check_Cursor CURSOR LOCAL FOR
		select   B2B_Owner,
							Res_Table.MatrixCellID,
							SUM(Quantity) as Quantity,
							SaleID,
							SaleitemID,
							CheckforRestrictionOnly,
							cnf_AccountRestriction.AccountRestrictionID,
							Limit,
							Res_Table.PerformanceID,
							RES_Table.Eventid

			from data_shopcartitemlimit Res_Table
				INNER JOIN CNF_AccountRestriction2Performance							ON CNF_AccountRestriction2Performance.PerformanceID = Res_Table.PerformanceID

				LEFT JOIN cnf_AccountRestriction2Account WITH(NOLOCK)					ON (cnf_AccountRestriction2Account.AccountID = Res_Table.B2B_Owner)																							
					                     													and cnf_AccountRestriction2Account.AccountRestrictionId = CNF_AccountRestriction2Performance.AccountRestrictionId										
			        
				LEFT JOIN cnf_AccountRestriction2DMGCategory WITH(NOLOCK)				ON (cnf_AccountRestriction2DMGCategory.DMGCategoryID = (select DMGCategoryID from data_account WITH(NOLOCK) where data_account.accountid = Res_Table.B2B_Owner))																							
					                                                                 		and cnf_AccountRestriction2DMGCategory.AccountRestrictionId = CNF_AccountRestriction2Performance.AccountRestrictionId
					
				INNER JOIN cnf_AccountRestriction WITH(NOLOCK)							ON cnf_AccountRestriction.AccountRestrictionId = CNF_AccountRestriction2Performance.AccountRestrictionId


			where cnf_AccountRestriction.Enabled = 1
				and Convert(date, GetDAte(), 120) between Convert(date, StartDateTime, 120) and Convert(date, EndDateTime, 120)
				and CNF_AccountRestriction.RestrictionType = @RestrictionType
				and Res_Table.B2B_Owner is not null
				and Limit is not null
				and B2B_Owner &lt;&gt; 0
		        and cnf_AccountRestriction.AccountType = @AccountType
				and ((cnf_AccountRestriction2Account.accountid is not null) or (cnf_AccountRestriction2DMGCategory.dmgcategoryid is not null))
			    and (((@SalesID = 0) and (Res_Table.ShopCartGuid = @GUID))
					 or (('0' = @GUID) and (Res_Table.Saleid = @SalesID)))

			GROUP BY B2B_Owner,
							Res_Table.MatrixCellID,
							SaleID,
							SaleitemID,
							CheckforRestrictionOnly,
							cnf_AccountRestriction.AccountRestrictionID,
							Limit,
							Res_Table.PerformanceID,
							RES_Table.Eventid
	OPEN Check_Cursor

	FETCH NEXT FROM Check_Cursor INTO
						@AccountID,
						@MatrixCellID,
						@Quantity,
						@SaleID,
						@SaleitemID,
						@CheckforRestrictionOnly,
						@AccountRestrictionID,
						@Limit,
						@PerformanceID,
						@EventID


	WHILE @@FETCH_STATUS = 0
	BEGIN
		IF @OldAccountRestrictionID &lt;&gt; @AccountRestrictionID and (@PreventSale = 0) or ((@OldAccountRestrictionID = @AccountRestrictionID) and (@PreventSale = 0) and (@Old_PerformanceID &lt;&gt; @PerformanceID))
		BEGIN 

			SET @Prevent = 0;

			select @FullQuantity = sum(Quantity),  @CountofMatrixCells = 1
				from data_shopcartitemlimit Res_Table
				where PerformanceID = @PerformanceID 	
					and B2B_Owner = @AccountID
				    and (((@SalesID = 0) and (Res_Table.ShopCartGuid = @GUID))
						 or (('0' = @GUID) and (Res_Table.Saleid = @SalesID)))

			if @FullQuantity &gt; 0
			Begin				
				if @CountofMatrixCells = 1 						 																
					Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @RestrictionType, @AccountType, @AccountID, 
														@PerformanceID, @EventID, @SaleID, @SaleitemID, @CheckforRestrictionOnly, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
				else
				begin
					Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @RestrictionType, @AccountType, @AccountID,  
														@PerformanceID, @EventID, @SaleID, @SaleitemID, 1, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
					set @Prevent = @PreventSale

					if @Prevent = 0 and @CheckforRestrictionOnly = 0 
					begin
						DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

						INSERT INTO [dbo].[DATA_AccountLimit]
										([AccountRestrictionId]
										,[AccountId]
										,[PerformanceId]
										,[SaleId]
										,[SaleItemId]
										,[SaleDate]
										,[ReservationAccountQuantity])
									VALUES
										(@AccountRestrictionID
										,@AccountID
										,@PerformanceID
										,@SaleID
										,@SaleItemID
										,@SalesDate
										,@FullQuantity)							 
					end
				end
			end
			else
			begin
				INSERT INTO [dbo].[DATA_AccountLimit]
								([AccountRestrictionId]
								,[AccountId]
								,[PerformanceId]
								,[SaleId]
								,[SaleItemId]
								,[SaleDate]
								,[ReservationAccountQuantity])
							VALUES
								(@AccountRestrictionID
								,@AccountID
								,@PerformanceID
								,@SaleID
								,@SaleItemID
								,@SalesDate
								,@Quantity)	
			end
		END
		ELSE
		BEGIN
			IF @OldAccountRestrictionID = @AccountRestrictionID and @AccountID = @OLD_Resevation_Owner and @Quantity &lt; 0
			begin
								INSERT INTO [dbo].[DATA_AccountLimit]
												([AccountRestrictionId]
												,[AccountId]
												,[PerformanceId]
												,[SaleId]
												,[SaleItemId]
												,[SaleDate]
												,[ReservationAccountQuantity])
											VALUES
												(@AccountRestrictionID
												,@AccountID
												,@PerformanceID
												,@SaleID
												,@SaleItemID
												,@SalesDate
												,@Quantity)	



			end 
			IF @OldAccountRestrictionID &lt;&gt; @AccountRestrictionID and @AccountID &lt;&gt; @OLD_Resevation_Owner
			begin
				if @Prevent = 0 and @CheckforRestrictionOnly = 0 
				begin
					DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

					INSERT INTO [dbo].[DATA_AccountLimit]
									([AccountRestrictionId]
									,[AccountId]
									,[PerformanceId]
									,[SaleId]
									,[SaleItemId]
									,[SaleDate]
									,[ReservationAccountQuantity])
								VALUES
									(@AccountRestrictionID
									,@AccountID
									,@PerformanceID
									,@SaleID
									,@SaleItemID
									,@SalesDate
									,@Quantity)						 
				end
			end
		END

		Set @OldAccountRestrictionID = @AccountRestrictionID
		SET @OLD_Resevation_Owner = @AccountID
		SET @Old_PerformanceID = @PerformanceID

		FETCH NEXT FROM Check_Cursor INTO
						@AccountID,
						@MatrixCellID,
						@Quantity,
						@SaleID,
						@SaleitemID,
						@CheckforRestrictionOnly,
						@AccountRestrictionID,
						@Limit,
						@PerformanceID,
						@EventID
	END

	CLOSE Check_Cursor;
	DEALLOCATE Check_Cursor;


--Event Reservation Owner Check
	IF @PreventSale = 0
	BEGIN
		Set @OldAccountRestrictionID = 99999
		DECLARE Check_Cursor CURSOR LOCAL FOR
			select   B2B_Owner,
								Res_Table.MatrixCellID,
								SUM(Quantity) as Quantity,
								SaleID,
								SaleitemID,
								CheckforRestrictionOnly,
								cnf_AccountRestriction.AccountRestrictionID,
								cnf_AccountRestriction.Limit,
								Res_Table.PerformanceID,
								RES_Table.Eventid

				from data_shopcartitemlimit Res_Table
					INNER JOIN CNF_AccountRestriction2Event WITH(NOLOCK)					ON CNF_AccountRestriction2Event.EventID = Res_Table.EventID

					LEFT JOIN cnf_AccountRestriction2Account WITH(NOLOCK)					ON (cnf_AccountRestriction2Account.AccountID = Res_Table.B2B_Owner)																							
					                     														and CNF_AccountRestriction2Event.AccountRestrictionId = cnf_AccountRestriction2Account.AccountRestrictionId	
																								
					LEFT JOIN cnf_AccountRestriction2DMGCategory WITH(NOLOCK)				ON (cnf_AccountRestriction2DMGCategory.DMGCategoryID = (select DMGCategoryID from data_account WITH(NOLOCK) where data_account.accountid = Res_Table.B2B_Owner))																							
					                         													and CNF_AccountRestriction2Event.AccountRestrictionId = cnf_AccountRestriction2DMGCategory.AccountRestrictionId	

					INNER JOIN cnf_AccountRestriction WITH(NOLOCK)							ON cnf_AccountRestriction.AccountRestrictionId = CNF_AccountRestriction2Event.AccountRestrictionId

				where cnf_AccountRestriction.Enabled = 1
				and Convert(date, GetDAte(), 120) between Convert(date, StartDateTime, 120) and Convert(date, EndDateTime, 120)
				and CNF_AccountRestriction.RestrictionType = @RestrictionType
				and Res_Table.B2B_Owner is not null
				and Limit is not null
				and Res_Table.B2B_Owner &lt;&gt; 0
		        and cnf_AccountRestriction.AccountType =  @AccountType
				and ((cnf_AccountRestriction2Account.accountid is not null) or (cnf_AccountRestriction2DMGCategory.dmgcategoryid is not null))
				and (((@SalesID = 0) and (Res_Table.ShopCartGuid = @GUID))
						 or (('0' = @GUID) and (Res_Table.Saleid = @SalesID)))

				GROUP BY B2B_Owner,
								Res_Table.MatrixCellID,
								SaleID,
								SaleitemID,
								CheckforRestrictionOnly,
								cnf_AccountRestriction.AccountRestrictionID,
								cnf_AccountRestriction.Limit,
								Res_Table.PerformanceID,
								RES_Table.Eventid

		OPEN Check_Cursor

		FETCH NEXT FROM Check_Cursor INTO
							@AccountID,
							@MatrixCellID,
							@Quantity,
							@SaleID,
							@SaleitemID,
							@CheckforRestrictionOnly,
							@AccountRestrictionID,
							@Limit,
							@PerformanceID,
							@EventID


		WHILE @@FETCH_STATUS = 0
		BEGIN
			IF @OldAccountRestrictionID &lt;&gt; @AccountRestrictionID and (@PreventSale = 0) 
					or ((@OldAccountRestrictionID = @AccountRestrictionID) and (@PreventSale = 0) and (@OLD_PerformanceID &lt;&gt; @PerformanceID))
			BEGIN 

				SET @Prevent = 0;

				select @FullQuantity = sum(Quantity),  @CountofMatrixCells = 1 
					from data_shopcartitemlimit Res_Table
					where PerformanceID = @PerformanceID	
						and B2B_Owner = @AccountID
					    and (((@SalesID = 0) and (Res_Table.ShopCartGuid = @GUID))
							 or (('0' = @GUID) and (Res_Table.Saleid = @SalesID)))
				
				if @FullQuantity &gt; 0
				Begin
					if @CountofMatrixCells = 1 
						
						Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @RestrictionType, @AccountType, @AccountID, 
															@PerformanceID, @EventID, @SaleID, @SaleitemID, @CheckforRestrictionOnly, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
					else
					begin
						Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @RestrictionType, @AccountType, @AccountID,  
															@PerformanceID, @EventID, @SaleID, @SaleitemID, 1, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
						set @Prevent = @PreventSale

						if @Prevent = 0 and @CheckforRestrictionOnly = 0 
						begin
							DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

							INSERT INTO [dbo].[DATA_AccountLimit]
											([AccountRestrictionId]
											,[AccountId]
											,[PerformanceId]
											,[SaleId]
											,[SaleItemId]
											,[SaleDate]
											,[ReservationAccountQuantity])
										VALUES
											(@AccountRestrictionID
											,@AccountID
											,@PerformanceID
											,@SaleID
											,@SaleItemID
											,@SalesDate
											,@FullQuantity)							 
						end
					end
				end
				else
				begin
					INSERT INTO [dbo].[DATA_AccountLimit]
									([AccountRestrictionId]
									,[AccountId]
									,[PerformanceId]
									,[SaleId]
									,[SaleItemId]
									,[SaleDate]
									,[ReservationAccountQuantity])
								VALUES
									(@AccountRestrictionID
									,@AccountID
									,@PerformanceID
									,@SaleID
									,@SaleItemID
									,@SalesDate
									,@Quantity)	
				end
			END
			ELSE
			BEGIN
				IF @OldAccountRestrictionID = @AccountRestrictionID and @AccountID = @OLD_Resevation_Owner and @Quantity &lt; 0
				begin
									INSERT INTO [dbo].[DATA_AccountLimit]
													([AccountRestrictionId]
													,[AccountId]
													,[PerformanceId]
													,[SaleId]
													,[SaleItemId]
													,[SaleDate]
													,[ReservationAccountQuantity])
												VALUES
													(@AccountRestrictionID
													,@AccountID
													,@PerformanceID
													,@SaleID
													,@SaleItemID
													,@SalesDate
													,@Quantity)	

				end 
				IF @OldAccountRestrictionID &lt;&gt; @AccountRestrictionID and @AccountID &lt;&gt; @OLD_Resevation_Owner
				begin
					if @Prevent = 0 and @CheckforRestrictionOnly = 0 
					begin
								DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

								INSERT INTO [dbo].[DATA_AccountLimit]
												([AccountRestrictionId]
												,[AccountId]
												,[PerformanceId]
												,[SaleId]
												,[SaleItemId]
												,[SaleDate]
												,[ReservationAccountQuantity])
											VALUES
												(@AccountRestrictionID
												,@AccountID
												,@PerformanceID
												,@SaleID
												,@SaleItemID
												,@SalesDate
												,@Quantity)						 
					end
				end
			END			

			Set @OldAccountRestrictionID = @AccountRestrictionID
			SET @OLD_Resevation_Owner = @AccountID
			SET @Old_EventID = @EventID
			Set @Old_PerformanceID = @PerformanceID

		FETCH NEXT FROM Check_Cursor INTO
							@AccountID,
							@MatrixCellID,
							@Quantity,
							@SaleID,
							@SaleitemID,
							@CheckforRestrictionOnly,
							@AccountRestrictionID,
							@Limit,
							@PerformanceID,
							@EventID
		END

		CLOSE Check_Cursor;
		DEALLOCATE Check_Cursor;
	END

RETURN;
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_AR_BillOwner_Matrixcell]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_AR_BillOwner_Matrixcell</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>CREATE PROCEDURE [otn_sp_AR_BillOwner_Matrixcell]      (
														  @GUID        varchar(100), 
													      @SalesId		int,
														  @PreventSale int OUTPUT,
														  @RejectReasonErrorCode int OUTPUT,
														  @RejectType int OUTPUT,
														  @RejectRestrictionDescription varchar(100) OUTPUT,
														  @RejectRemainingAmount int OUTPUT
														) 
AS    
BEGIN

	DECLARE @SalesDate datetime = getdate();
	DECLARE @RestrictionType int = 1
	DECLARE @AccountType int = 3
	DECLARE @AccountID int
	DECLARE @OldAccountRestrictionID int = 99999
	DECLARE @Limit int
	DECLARE @AccountRestrictionID int
	DECLARE @MatrixCellID int
	DECLARE @Quantity int
	DECLARE @FullQuantity int
	DECLARE @PerformanceID int
	DECLARE @EventID int
	DECLARE @SaleID int
	DECLARE @SaleitemID int
	DECLARE @CheckforRestrictionOnly int
	DECLARE @OLD_Resevation_Owner int
	DECLARE @CountofMatrixCells int = 0
	DECLARE @Prevent int = 0

	
--Reservation Owner	
	SET @RestrictionType = 1
	set @CountofMatrixCells = 0
	SET @OLD_Resevation_Owner = 99999

	DECLARE Check_Cursor CURSOR LOCAL FOR
		select  Billing_Owner,
				Res_Table.MatrixCellID,
				sum(Quantity) as Quantity,
				SaleID,
				SaleitemID,
				CheckforRestrictionOnly,
				cnf_AccountRestriction.AccountRestrictionID,
				cnf_AccountRestriction.Limit

		  from data_shopcartitemlimit Res_Table
				INNER JOIN cnf_AccountRestriction2MatrixCell WITH(NOLOCK)				ON cnf_AccountRestriction2MatrixCell.MatrixCellID = Res_Table.MatrixCellID
				LEFT JOIN cnf_AccountRestriction2Account WITH(NOLOCK)					ON (cnf_AccountRestriction2Account.AccountID = Res_Table.Billing_Owner)																							
					                                                                       and cnf_accountrestriction2Account.AccountRestrictionID = CNF_AccountRestriction2MatrixCell.AccountRestrictionId
																						   
			    LEFT JOIN cnf_AccountRestriction2DMGCategory WITH(NOLOCK)				ON (cnf_AccountRestriction2DMGCategory.DMGCategoryID = (select DMGCategoryID from data_account WITH(NOLOCK) where data_account.accountid = Res_Table.Billing_Owner))																							
					                                                                       and cnf_AccountRestriction2DMGCategory.AccountRestrictionID = CNF_AccountRestriction2MatrixCell.AccountRestrictionId				
				
				INNER JOIN cnf_AccountRestriction WITH(NOLOCK)							ON cnf_AccountRestriction.AccountRestrictionId = cnf_AccountRestriction2MatrixCell.AccountRestrictionId

	     where cnf_AccountRestriction.Enabled = 1
		   and Convert(date, GetDAte(), 120) between Convert(date, StartDateTime, 120) and Convert(date, EndDateTime, 120)
		   and CNF_AccountRestriction.RestrictionType = @RestrictionType
		   and Res_Table.Billing_Owner is not null
		   and Limit is not null
		   and cnf_AccountRestriction.AccountType = @AccountType
		   and Billing_Owner &lt;&gt; 0
		   and ((cnf_AccountRestriction2Account.accountid is not null) or (cnf_AccountRestriction2DMGCategory.dmgcategoryid is not null))
		   and ISNULL(Res_Table.PerformanceID, 0) = 0
		   and (((@SalesID = 0) and (Res_Table.ShopCartGuid = @GUID))
		         or (('0' = @GUID) and (Res_Table.Saleid = @SalesID)))

			 GROUP BY Billing_Owner,
							 Res_Table.MatrixCellID,
							 SaleID,
							 SaleitemID,
							 CheckforRestrictionOnly,
							 cnf_AccountRestriction.AccountRestrictionID,
							 cnf_AccountRestriction.Limit

		 order by cnf_AccountRestriction.AccountRestrictionID

	OPEN Check_Cursor

	FETCH NEXT FROM Check_Cursor INTO
						@AccountID,
						@MatrixCellID,
						@Quantity,
						@SaleID,
						@SaleitemID,
						@CheckforRestrictionOnly,
	                    @AccountRestrictionID,
						@Limit


	WHILE @@FETCH_STATUS = 0
	BEGIN
		IF @OldAccountRestrictionID &lt;&gt; @AccountRestrictionID and @AccountID &lt;&gt; @OLD_Resevation_Owner and (@PreventSale = 0)
		BEGIN 

			SET @Prevent = 0;

			select @FullQuantity = sum(Quantity),  
				    @CountofMatrixCells = Count(*)
				from data_shopcartitemlimit Res_Table
				where MatrixCellID in (select MatrixcellId 
										from cnf_AccountRestriction2MatrixCell WITH(NOLOCK)									
										where cnf_AccountRestriction2MatrixCell.AccountRestrictionId = @AccountRestrictionID)
				and Billing_Owner = @AccountID
				and ISNULL(PerformanceID, 0) = 0
			    and (((@SalesID = 0) and (Res_Table.ShopCartGuid = @GUID))
					 or (('0' = @GUID) and (Res_Table.Saleid = @SalesID)))

			if @FullQuantity &gt; 0
			Begin			  
				if @CountofMatrixCells = 1 						
					Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @RestrictionType, @AccountType, @AccountID,  
														null, null, @SaleID, @SaleitemID, @CheckforRestrictionOnly, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
				else
				begin
					Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @RestrictionType, @AccountType, @AccountID,  
														null, null, @SaleID, @SaleitemID, 1, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
					set @Prevent = @PreventSale

					if @Prevent = 0 and @CheckforRestrictionOnly = 0 
					begin
						    DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

						INSERT INTO [dbo].[DATA_AccountLimit]
										([AccountRestrictionId]
										,[AccountId]
										,[PerformanceId]
										,[SaleId]
										,[SaleItemId]
										,[SaleDate]
										,[ReservationAccountQuantity])
									VALUES
										(@AccountRestrictionID
										,@AccountID
										,@PerformanceID
										,@SaleID
										,@SaleItemID
										,@SalesDate
										,@FullQuantity)						 
					end
				end
			end
			else
			begin
				INSERT INTO [dbo].[DATA_AccountLimit]
								([AccountRestrictionId]
								,[AccountId]
								,[PerformanceId]
								,[SaleId]
								,[SaleItemId]
								,[SaleDate]
								,[ReservationAccountQuantity])
							VALUES
								(@AccountRestrictionID
								,@AccountID
								,@PerformanceID
								,@SaleID
								,@SaleItemID
								,@SalesDate
								,@Quantity)	
			end
		END
		ELSE
		BEGIN
			IF @OldAccountRestrictionID = @AccountRestrictionID and @AccountID = @OLD_Resevation_Owner and @Quantity &lt; 0
			begin
								INSERT INTO [dbo].[DATA_AccountLimit]
												([AccountRestrictionId]
												,[AccountId]
												,[PerformanceId]
												,[SaleId]
												,[SaleItemId]
												,[SaleDate]
												,[ReservationAccountQuantity])
											VALUES
												(@AccountRestrictionID
												,@AccountID
												,@PerformanceID
												,@SaleID
												,@SaleItemID
												,@SalesDate
												,@Quantity)	



			end 
			IF @OldAccountRestrictionID &lt;&gt; @AccountRestrictionID and @AccountID &lt;&gt; @OLD_Resevation_Owner
			begin
				if @Prevent = 0 and @CheckforRestrictionOnly = 0 
				begin
				    DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

					INSERT INTO [dbo].[DATA_AccountLimit]
									([AccountRestrictionId]
									,[AccountId]
									,[PerformanceId]
									,[SaleId]
									,[SaleItemId]
									,[SaleDate]
									,[ReservationAccountQuantity])
								VALUES
									(@AccountRestrictionID
									,@AccountID
									,@PerformanceID
									,@SaleID
									,@SaleItemID
									,@SalesDate
									,@Quantity)						 
				end
			end
		END

		Set @OldAccountRestrictionID = @AccountRestrictionID
		SET @OLD_Resevation_Owner = @AccountID

		FETCH NEXT FROM Check_Cursor INTO
						@AccountID,
						@MatrixCellID,
						@Quantity,
						@SaleID,
						@SaleitemID,
						@CheckforRestrictionOnly,
	                    @AccountRestrictionID,
						@Limit
	END

	CLOSE Check_Cursor;
	DEALLOCATE Check_Cursor;


RETURN;

END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_AR_BillOwner_Performance]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_AR_BillOwner_Performance</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT> CREATE PROCEDURE [otn_sp_AR_BillOwner_Performance]  (
                                                      @GUID        varchar(100), 
													  @SalesId	int,
													  @PreventSale int OUTPUT,
													  @RejectReasonErrorCode int OUTPUT,
													  @RejectType int OUTPUT,
													  @RejectRestrictionDescription varchar(100) OUTPUT,
													  @RejectRemainingAmount int OUTPUT
                                                    ) 
AS    
BEGIN

	DECLARE @SalesDate datetime = getdate();
	DECLARE @RestrictionType int = 2
	DECLARE @AccountType int = 3
	DECLARE @AccountID int
	DECLARE @OldAccountRestrictionID int = 99999
	DECLARE @AccountRestrictionID int
	DECLARE @MatrixCellID int
	DECLARE @Quantity int
	DECLARE @FullQuantity int
	DECLARE @PerformanceID int
	DECLARE @EventID int
	DECLARE @SaleID int
	DECLARE @SaleitemID int
	DECLARE @CheckforRestrictionOnly int
	DECLARE @Limit int
	DECLARE @OLD_Resevation_Owner int
	DECLARE @CountofMatrixCells int = 0
	DECLARE @Prevent int = 0
	DECLARE @Old_PerformanceID int = 0
	DECLARE @Old_EventID int = 0

	
--Performance Reservation Owner Check
	Set @OldAccountRestrictionID = 99999
	DECLARE Check_Cursor CURSOR LOCAL FOR
		select   Billing_Owner,
							Res_Table.MatrixCellID,
							SUM(Quantity) as Quantity,
							SaleID,
							SaleitemID,
							CheckforRestrictionOnly,
							cnf_AccountRestriction.AccountRestrictionID,
							Limit,
							Res_Table.PerformanceID,
							RES_Table.Eventid

			from data_shopcartitemlimit Res_Table
				INNER JOIN CNF_AccountRestriction2Performance							ON CNF_AccountRestriction2Performance.PerformanceID = Res_Table.PerformanceID

				LEFT JOIN cnf_AccountRestriction2Account WITH(NOLOCK)					ON (cnf_AccountRestriction2Account.AccountID = Res_Table.Billing_Owner)																							
					                     													and cnf_AccountRestriction2Account.AccountRestrictionId = CNF_AccountRestriction2Performance.AccountRestrictionId										
			        
				LEFT JOIN cnf_AccountRestriction2DMGCategory WITH(NOLOCK)				ON (cnf_AccountRestriction2DMGCategory.DMGCategoryID = (select DMGCategoryID from data_account WITH(NOLOCK) where data_account.accountid = Res_Table.Billing_Owner))																							
					                                                                 		and cnf_AccountRestriction2DMGCategory.AccountRestrictionId = CNF_AccountRestriction2Performance.AccountRestrictionId
					
				INNER JOIN cnf_AccountRestriction WITH(NOLOCK)							ON cnf_AccountRestriction.AccountRestrictionId = CNF_AccountRestriction2Performance.AccountRestrictionId


			where cnf_AccountRestriction.Enabled = 1
				and Convert(date, GetDAte(), 120) between Convert(date, StartDateTime, 120) and Convert(date, EndDateTime, 120)
				and CNF_AccountRestriction.RestrictionType = @RestrictionType
				and Res_Table.Billing_Owner is not null
				and Limit is not null
				and Billing_Owner &lt;&gt; 0
		        and cnf_AccountRestriction.AccountType = @AccountType
				and ((cnf_AccountRestriction2Account.accountid is not null) or (cnf_AccountRestriction2DMGCategory.dmgcategoryid is not null))
			    and (((@SalesID = 0) and (Res_Table.ShopCartGuid = @GUID))
					 or (('0' = @GUID) and (Res_Table.Saleid = @SalesID)))

			GROUP BY Billing_Owner,
							Res_Table.MatrixCellID,
							SaleID,
							SaleitemID,
							CheckforRestrictionOnly,
							cnf_AccountRestriction.AccountRestrictionID,
							Limit,
							Res_Table.PerformanceID,
							RES_Table.Eventid
	OPEN Check_Cursor

	FETCH NEXT FROM Check_Cursor INTO
						@AccountID,
						@MatrixCellID,
						@Quantity,
						@SaleID,
						@SaleitemID,
						@CheckforRestrictionOnly,
						@AccountRestrictionID,
						@Limit,
						@PerformanceID,
						@EventID


	WHILE @@FETCH_STATUS = 0
	BEGIN
		IF @OldAccountRestrictionID &lt;&gt; @AccountRestrictionID and (@PreventSale = 0) or ((@OldAccountRestrictionID = @AccountRestrictionID) and (@PreventSale = 0) and (@Old_PerformanceID &lt;&gt; @PerformanceID))
		BEGIN 
			SET @Prevent = 0;

			select @FullQuantity = sum(Quantity),  @CountofMatrixCells = 1
				from data_shopcartitemlimit Res_Table
				where PerformanceID = @PerformanceID 	
					and Billing_Owner = @AccountID
					and (((@SalesID = 0) and (Res_Table.ShopCartGuid = @GUID))
							or (('0' = @GUID) and (Res_Table.Saleid = @SalesID)))

			if @FullQuantity &gt; 0
			Begin				
				if @CountofMatrixCells = 1 						 																
					Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @RestrictionType, @AccountType, @AccountID, 
														@PerformanceID, @EventID, @SaleID, @SaleitemID, @CheckforRestrictionOnly, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
				else
				begin
					Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @RestrictionType, @AccountType, @AccountID, 
														@PerformanceID, @EventID, @SaleID, @SaleitemID, 1, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
					set @Prevent = @PreventSale

					if @Prevent = 0 and @CheckforRestrictionOnly = 0 
					begin
						DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

						INSERT INTO [dbo].[DATA_AccountLimit]
										([AccountRestrictionId]
										,[AccountId]
										,[PerformanceId]
										,[SaleId]
										,[SaleItemId]
										,[SaleDate]
										,[ReservationAccountQuantity])
									VALUES
										(@AccountRestrictionID
										,@AccountID
										,@PerformanceID
										,@SaleID
										,@SaleItemID
										,@SalesDate
										,@FullQuantity)							 
					end
				end
			end
			else
			begin
				INSERT INTO [dbo].[DATA_AccountLimit]
								([AccountRestrictionId]
								,[AccountId]
								,[PerformanceId]
								,[SaleId]
								,[SaleItemId]
								,[SaleDate]
								,[ReservationAccountQuantity])
							VALUES
								(@AccountRestrictionID
								,@AccountID
								,@PerformanceID
								,@SaleID
								,@SaleItemID
								,@SalesDate
								,@Quantity)	
			end
		END
		ELSE
		BEGIN
			IF @OldAccountRestrictionID = @AccountRestrictionID and @AccountID = @OLD_Resevation_Owner and @Quantity &lt; 0
			begin
								INSERT INTO [dbo].[DATA_AccountLimit]
												([AccountRestrictionId]
												,[AccountId]
												,[PerformanceId]
												,[SaleId]
												,[SaleItemId]
												,[SaleDate]
												,[ReservationAccountQuantity])
											VALUES
												(@AccountRestrictionID
												,@AccountID
												,@PerformanceID
												,@SaleID
												,@SaleItemID
												,@SalesDate
												,@Quantity)	



			end 
			IF @OldAccountRestrictionID &lt;&gt; @AccountRestrictionID and @AccountID &lt;&gt; @OLD_Resevation_Owner
			begin
				if @Prevent = 0 and @CheckforRestrictionOnly = 0 
				begin
					DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

					INSERT INTO [dbo].[DATA_AccountLimit]
									([AccountRestrictionId]
									,[AccountId]
									,[PerformanceId]
									,[SaleId]
									,[SaleItemId]
									,[SaleDate]
									,[ReservationAccountQuantity])
								VALUES
									(@AccountRestrictionID
									,@AccountID
									,@PerformanceID
									,@SaleID
									,@SaleItemID
									,@SalesDate
									,@Quantity)						 
				end
			end
		END

		Set @OldAccountRestrictionID = @AccountRestrictionID
		SET @OLD_Resevation_Owner = @AccountID
		SET @Old_PerformanceID = @PerformanceID

		FETCH NEXT FROM Check_Cursor INTO
						@AccountID,
						@MatrixCellID,
						@Quantity,
						@SaleID,
						@SaleitemID,
						@CheckforRestrictionOnly,
						@AccountRestrictionID,
						@Limit,
						@PerformanceID,
						@EventID
	END

	CLOSE Check_Cursor;
	DEALLOCATE Check_Cursor;


--Event Reservation Owner Check
	IF @PreventSale = 0
	BEGIN
		Set @OldAccountRestrictionID = 99999
		DECLARE Check_Cursor CURSOR LOCAL FOR
			select   Billing_Owner,
								Res_Table.MatrixCellID,
								SUM(Quantity) as Quantity,
								SaleID,
								SaleitemID,
								CheckforRestrictionOnly,
								cnf_AccountRestriction.AccountRestrictionID,
								cnf_AccountRestriction.Limit,
								Res_Table.PerformanceID,
								RES_Table.Eventid

				from data_shopcartitemlimit Res_Table
					INNER JOIN CNF_AccountRestriction2Event WITH(NOLOCK)					ON CNF_AccountRestriction2Event.EventID = Res_Table.EventID

					LEFT JOIN cnf_AccountRestriction2Account WITH(NOLOCK)					ON (cnf_AccountRestriction2Account.AccountID = Res_Table.Billing_Owner)																							
					                     														and CNF_AccountRestriction2Event.AccountRestrictionId = cnf_AccountRestriction2Account.AccountRestrictionId	
																								
					LEFT JOIN cnf_AccountRestriction2DMGCategory WITH(NOLOCK)				ON (cnf_AccountRestriction2DMGCategory.DMGCategoryID = (select DMGCategoryID from data_account WITH(NOLOCK) where data_account.accountid = Res_Table.Billing_Owner))																							
					                         													and CNF_AccountRestriction2Event.AccountRestrictionId = cnf_AccountRestriction2DMGCategory.AccountRestrictionId	

					INNER JOIN cnf_AccountRestriction WITH(NOLOCK)							ON cnf_AccountRestriction.AccountRestrictionId = CNF_AccountRestriction2Event.AccountRestrictionId

				where cnf_AccountRestriction.Enabled = 1
				and Convert(date, GetDAte(), 120) between Convert(date, StartDateTime, 120) and Convert(date, EndDateTime, 120)
				and CNF_AccountRestriction.RestrictionType = @RestrictionType
				and Res_Table.Billing_Owner is not null
				and Limit is not null
				and Res_Table.Billing_Owner &lt;&gt; 0
		        and cnf_AccountRestriction.AccountType =  @AccountType
				and ((cnf_AccountRestriction2Account.accountid is not null) or (cnf_AccountRestriction2DMGCategory.dmgcategoryid is not null))
				and (((@SalesID = 0) and (Res_Table.ShopCartGuid = @GUID))
						or (('0' = @GUID) and (Res_Table.Saleid = @SalesID)))

				GROUP BY Billing_Owner,
								Res_Table.MatrixCellID,
								SaleID,
								SaleitemID,
								CheckforRestrictionOnly,
								cnf_AccountRestriction.AccountRestrictionID,
								cnf_AccountRestriction.Limit,
								Res_Table.PerformanceID,
								RES_Table.Eventid

		OPEN Check_Cursor

		FETCH NEXT FROM Check_Cursor INTO
							@AccountID,
							@MatrixCellID,
							@Quantity,
							@SaleID,
							@SaleitemID,
							@CheckforRestrictionOnly,
							@AccountRestrictionID,
							@Limit,
							@PerformanceID,
							@EventID


		WHILE @@FETCH_STATUS = 0
		BEGIN
			IF @OldAccountRestrictionID &lt;&gt; @AccountRestrictionID and (@PreventSale = 0) 
					or ((@OldAccountRestrictionID = @AccountRestrictionID) and (@PreventSale = 0) and (@OLD_PerformanceID &lt;&gt; @PerformanceID))
			BEGIN 

				SET @Prevent = 0;

				select @FullQuantity = sum(Quantity),  @CountofMatrixCells = 1 
					from data_shopcartitemlimit Res_Table
					where PerformanceID = @PerformanceID	
						and Billing_Owner = @AccountID
					    and (((@SalesID = 0) and (Res_Table.ShopCartGuid = @GUID))
							 or (('0' = @GUID) and (Res_Table.Saleid = @SalesID)))

				if @FullQuantity &gt; 0
				Begin
					if @CountofMatrixCells = 1 
						
						Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @RestrictionType, @AccountType, @AccountID,  
															@PerformanceID, @EventID, @SaleID, @SaleitemID, @CheckforRestrictionOnly, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
					else
					begin
						Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @RestrictionType, @AccountType, @AccountID,  
															@PerformanceID, @EventID, @SaleID, @SaleitemID, 1, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
						set @Prevent = @PreventSale

						if @Prevent = 0 and @CheckforRestrictionOnly = 0 
						begin
							DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

							INSERT INTO [dbo].[DATA_AccountLimit]
											([AccountRestrictionId]
											,[AccountId]
											,[PerformanceId]
											,[SaleId]
											,[SaleItemId]
											,[SaleDate]
											,[ReservationAccountQuantity])
										VALUES
											(@AccountRestrictionID
											,@AccountID
											,@PerformanceID
											,@SaleID
											,@SaleItemID
											,@SalesDate
											,@FullQuantity)							 
						end
					end
				end
				else
				begin
					INSERT INTO [dbo].[DATA_AccountLimit]
									([AccountRestrictionId]
									,[AccountId]
									,[PerformanceId]
									,[SaleId]
									,[SaleItemId]
									,[SaleDate]
									,[ReservationAccountQuantity])
								VALUES
									(@AccountRestrictionID
									,@AccountID
									,@PerformanceID
									,@SaleID
									,@SaleItemID
									,@SalesDate
									,@Quantity)	
				end
			END
			ELSE
			BEGIN
				IF @OldAccountRestrictionID = @AccountRestrictionID and @AccountID = @OLD_Resevation_Owner and @Quantity &lt; 0
				begin
									INSERT INTO [dbo].[DATA_AccountLimit]
													([AccountRestrictionId]
													,[AccountId]
													,[PerformanceId]
													,[SaleId]
													,[SaleItemId]
													,[SaleDate]
													,[ReservationAccountQuantity])
												VALUES
													(@AccountRestrictionID
													,@AccountID
													,@PerformanceID
													,@SaleID
													,@SaleItemID
													,@SalesDate
													,@Quantity)	

				end 
				IF @OldAccountRestrictionID &lt;&gt; @AccountRestrictionID and @AccountID &lt;&gt; @OLD_Resevation_Owner
				begin
					if @Prevent = 0 and @CheckforRestrictionOnly = 0 
					begin
								DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

								INSERT INTO [dbo].[DATA_AccountLimit]
												([AccountRestrictionId]
												,[AccountId]
												,[PerformanceId]
												,[SaleId]
												,[SaleItemId]
												,[SaleDate]
												,[ReservationAccountQuantity])
											VALUES
												(@AccountRestrictionID
												,@AccountID
												,@PerformanceID
												,@SaleID
												,@SaleItemID
												,@SalesDate
												,@Quantity)						 
					end
				end
			END			

			Set @OldAccountRestrictionID = @AccountRestrictionID
			SET @OLD_Resevation_Owner = @AccountID
			SET @Old_EventID = @EventID
			Set @Old_PerformanceID = @PerformanceID

		FETCH NEXT FROM Check_Cursor INTO
							@AccountID,
							@MatrixCellID,
							@Quantity,
							@SaleID,
							@SaleitemID,
							@CheckforRestrictionOnly,
							@AccountRestrictionID,
							@Limit,
							@PerformanceID,
							@EventID
		END

		CLOSE Check_Cursor;
		DEALLOCATE Check_Cursor;
	END

RETURN;
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_AR_ReservationOwner_Matrixcell]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_AR_ReservationOwner_Matrixcell</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>CREATE PROCEDURE [otn_sp_AR_ReservationOwner_Matrixcell]  (
														  @GUID        varchar(100),
														  @SalesID int,
														  @PreventSale int OUTPUT,
														  @RejectReasonErrorCode int OUTPUT,
														  @RejectType int OUTPUT,
														  @RejectRestrictionDescription varchar(100) OUTPUT,
														  @RejectRemainingAmount int OUTPUT
														) 
AS    
BEGIN

	DECLARE @SalesDate datetime = getdate();
	DECLARE @RestrictionType int = 1
	DECLARE @AccountType int = 1
	DECLARE @AccountID int
	DECLARE @OldAccountRestrictionID int = 99999
	DECLARE @Limit int
	DECLARE @AccountRestrictionID int
	DECLARE @MatrixCellID int
	DECLARE @Quantity int
	DECLARE @FullQuantity int
	DECLARE @PerformanceID int
	DECLARE @EventID int
	DECLARE @SaleID int
	DECLARE @SaleitemID int
	DECLARE @CheckforRestrictionOnly int
	DECLARE @OLD_Resevation_Owner int
	DECLARE @CountofMatrixCells int = 0
	DECLARE @Prevent int = 0

	
--Reservation Owner	
	SET @RestrictionType = 1
	set @CountofMatrixCells = 0
	SET @OLD_Resevation_Owner = 99999

	DECLARE Check_Cursor CURSOR LOCAL FOR
		select  Reservation_Owner,
				Res_Table.MatrixCellID,
				sum(Quantity) as Quantity,
				SaleID,
				SaleitemID,
				CheckforRestrictionOnly,
				cnf_AccountRestriction.AccountRestrictionID,
				cnf_AccountRestriction.Limit

		  from data_shopcartitemlimit Res_Table
				INNER JOIN cnf_AccountRestriction2MatrixCell WITH(NOLOCK)				ON cnf_AccountRestriction2MatrixCell.MatrixCellID = Res_Table.MatrixCellID
				LEFT JOIN cnf_AccountRestriction2Account WITH(NOLOCK)					ON (cnf_AccountRestriction2Account.AccountID = Res_Table.Reservation_Owner)																							
					                                                                       and cnf_accountrestriction2Account.AccountRestrictionID = CNF_AccountRestriction2MatrixCell.AccountRestrictionId
																						   
			    LEFT JOIN cnf_AccountRestriction2DMGCategory WITH(NOLOCK)				ON (cnf_AccountRestriction2DMGCategory.DMGCategoryID = (select DMGCategoryID from data_account WITH(NOLOCK) where data_account.accountid = Res_Table.Reservation_Owner))																							
					                                                                       and cnf_AccountRestriction2DMGCategory.AccountRestrictionID = CNF_AccountRestriction2MatrixCell.AccountRestrictionId				
				
				INNER JOIN cnf_AccountRestriction WITH(NOLOCK)							ON cnf_AccountRestriction.AccountRestrictionId = cnf_AccountRestriction2MatrixCell.AccountRestrictionId

	     where cnf_AccountRestriction.Enabled = 1
		   and Convert(date, GetDAte(), 120) between Convert(date, StartDateTime, 120) and Convert(date, EndDateTime, 120)
		   and CNF_AccountRestriction.RestrictionType = @RestrictionType
		   and Res_Table.Reservation_Owner is not null
		   and Limit is not null
		   and cnf_AccountRestriction.AccountType = @AccountType
		   and Reservation_Owner &lt;&gt; 0
		   and ((cnf_AccountRestriction2Account.accountid is not null) or (cnf_AccountRestriction2DMGCategory.dmgcategoryid is not null))
		   and ISNULL(Res_Table.PerformanceID, 0) = 0
		   and (((@SalesID = 0) and (Res_Table.ShopCartGuid = @GUID))
		         or (('0' = @GUID) and (Res_Table.Saleid = @SalesID)))

			 GROUP BY Reservation_Owner,
							 Res_Table.MatrixCellID,
							 SaleID,
							 SaleitemID,
							 CheckforRestrictionOnly,
							 cnf_AccountRestriction.AccountRestrictionID,
							 cnf_AccountRestriction.Limit

		 order by cnf_AccountRestriction.AccountRestrictionID

	OPEN Check_Cursor

	FETCH NEXT FROM Check_Cursor INTO
						@AccountID,
						@MatrixCellID,
						@Quantity,
						@SaleID,
						@SaleitemID,
						@CheckforRestrictionOnly,
	                    @AccountRestrictionID,
						@Limit


	WHILE @@FETCH_STATUS = 0
	BEGIN
		IF @OldAccountRestrictionID &lt;&gt; @AccountRestrictionID and @AccountID &lt;&gt; @OLD_Resevation_Owner and (@PreventSale = 0)
		BEGIN 

			SET @Prevent = 0;

			select @FullQuantity = sum(Quantity),  
				    @CountofMatrixCells = Count(*)
				from data_shopcartitemlimit Res_Table
				where MatrixCellID in (select MatrixcellId 
										from cnf_AccountRestriction2MatrixCell WITH(NOLOCK)									
										where cnf_AccountRestriction2MatrixCell.AccountRestrictionId = @AccountRestrictionID)
				and Reservation_Owner = @AccountID
				and ISNULL(PerformanceID, 0) = 0
			    and (((@SalesID = 0) and (Res_Table.ShopCartGuid = @GUID))
					 or (('0' = @GUID) and (Res_Table.Saleid = @SalesID)))

			if @FullQuantity &gt; 0
			Begin			  
				if @CountofMatrixCells = 1 						
					Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @RestrictionType, @AccountType, @AccountID, 
														null, null, @SaleID, @SaleitemID, @CheckforRestrictionOnly, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
				else
				begin
					Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @RestrictionType, @AccountType, @AccountID,  
														null, null, @SaleID, @SaleitemID, 1, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
					set @Prevent = @PreventSale

					if @Prevent = 0 and @CheckforRestrictionOnly = 0 
					begin
						    DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

						INSERT INTO [dbo].[DATA_AccountLimit]
										([AccountRestrictionId]
										,[AccountId]
										,[PerformanceId]
										,[SaleId]
										,[SaleItemId]
										,[SaleDate]
										,[ReservationAccountQuantity])
									VALUES
										(@AccountRestrictionID
										,@AccountID
										,@PerformanceID
										,@SaleID
										,@SaleItemID
										,@SalesDate
										,@FullQuantity)						 
					end
				end
			end
			else
			begin
				INSERT INTO [dbo].[DATA_AccountLimit]
								([AccountRestrictionId]
								,[AccountId]
								,[PerformanceId]
								,[SaleId]
								,[SaleItemId]
								,[SaleDate]
								,[ReservationAccountQuantity])
							VALUES
								(@AccountRestrictionID
								,@AccountID
								,@PerformanceID
								,@SaleID
								,@SaleItemID
								,@SalesDate
								,@Quantity)	
			end
		END	
		ELSE
		BEGIN
			IF @OldAccountRestrictionID = @AccountRestrictionID and @AccountID = @OLD_Resevation_Owner and @Quantity &lt; 0
			begin
								INSERT INTO [dbo].[DATA_AccountLimit]
												([AccountRestrictionId]
												,[AccountId]
												,[PerformanceId]
												,[SaleId]
												,[SaleItemId]
												,[SaleDate]
												,[ReservationAccountQuantity])
											VALUES
												(@AccountRestrictionID
												,@AccountID
												,@PerformanceID
												,@SaleID
												,@SaleItemID
												,@SalesDate
												,@Quantity)	



			end 
			IF @OldAccountRestrictionID &lt;&gt; @AccountRestrictionID and @AccountID &lt;&gt; @OLD_Resevation_Owner
			begin
				if @Prevent = 0 and @CheckforRestrictionOnly = 0 
				begin
				    DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

					INSERT INTO [dbo].[DATA_AccountLimit]
									([AccountRestrictionId]
									,[AccountId]
									,[PerformanceId]
									,[SaleId]
									,[SaleItemId]
									,[SaleDate]
									,[ReservationAccountQuantity])
								VALUES
									(@AccountRestrictionID
									,@AccountID
									,@PerformanceID
									,@SaleID
									,@SaleItemID
									,@SalesDate
									,@Quantity)						 
				end
			end
		END

		Set @OldAccountRestrictionID = @AccountRestrictionID
		SET @OLD_Resevation_Owner = @AccountID

		FETCH NEXT FROM Check_Cursor INTO
						@AccountID,
						@MatrixCellID,
						@Quantity,
						@SaleID,
						@SaleitemID,
						@CheckforRestrictionOnly,
	                    @AccountRestrictionID,
						@Limit
	END

	CLOSE Check_Cursor;
	DEALLOCATE Check_Cursor;


RETURN;

END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_AR_ReservationOwner_Performance]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_AR_ReservationOwner_Performance</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>CREATE PROCEDURE [otn_sp_AR_ReservationOwner_Performance]  (
															  @GUID        varchar(100), 
													          @SalesId		int,
															  @PreventSale int OUTPUT,
															  @RejectReasonErrorCode int OUTPUT,
															  @RejectType int OUTPUT,
															  @RejectRestrictionDescription varchar(100) OUTPUT,
															  @RejectRemainingAmount int OUTPUT
															) 
AS    
BEGIN

	DECLARE @SalesDate datetime = getdate();
	DECLARE @RestrictionType int = 2
	DECLARE @AccountType int = 1
	DECLARE @AccountID int
	DECLARE @OldAccountRestrictionID int = 99999
	DECLARE @AccountRestrictionID int
	DECLARE @MatrixCellID int
	DECLARE @Quantity int
	DECLARE @FullQuantity int
	DECLARE @PerformanceID int
	DECLARE @EventID int
	DECLARE @SaleID int
	DECLARE @SaleitemID int
	DECLARE @CheckforRestrictionOnly int
	DECLARE @Limit int
	DECLARE @OLD_Resevation_Owner int
	DECLARE @CountofMatrixCells int = 0
	DECLARE @Prevent int = 0
	DECLARE @Old_PerformanceID int = 0
	DECLARE @Old_EventID int = 0

	
--Performance Reservation Owner Check
	Set @OldAccountRestrictionID = 99999
	DECLARE Check_Cursor CURSOR LOCAL FOR
		select   Reservation_Owner,
							Res_Table.MatrixCellID,
							SUM(Quantity) as Quantity,
							SaleID,
							SaleitemID,
							CheckforRestrictionOnly,
							cnf_AccountRestriction.AccountRestrictionID,
							Limit,
							Res_Table.PerformanceID,
							RES_Table.Eventid

			from data_shopcartitemlimit Res_Table
				INNER JOIN CNF_AccountRestriction2Performance							ON CNF_AccountRestriction2Performance.PerformanceID = Res_Table.PerformanceID

				LEFT JOIN cnf_AccountRestriction2Account WITH(NOLOCK)					ON (cnf_AccountRestriction2Account.AccountID = Res_Table.Reservation_Owner)																							
					                     													and cnf_AccountRestriction2Account.AccountRestrictionId = CNF_AccountRestriction2Performance.AccountRestrictionId										
			        
				LEFT JOIN cnf_AccountRestriction2DMGCategory WITH(NOLOCK)				ON (cnf_AccountRestriction2DMGCategory.DMGCategoryID = (select DMGCategoryID from data_account WITH(NOLOCK) where data_account.accountid = Res_Table.Reservation_Owner))																							
					                                                                 		and cnf_AccountRestriction2DMGCategory.AccountRestrictionId = CNF_AccountRestriction2Performance.AccountRestrictionId
					
				INNER JOIN cnf_AccountRestriction WITH(NOLOCK)							ON cnf_AccountRestriction.AccountRestrictionId = CNF_AccountRestriction2Performance.AccountRestrictionId


			where cnf_AccountRestriction.Enabled = 1
				and Convert(date, GetDAte(), 120) between Convert(date, StartDateTime, 120) and Convert(date, EndDateTime, 120)
				and CNF_AccountRestriction.RestrictionType = @RestrictionType
				and Res_Table.Reservation_Owner is not null
				and Limit is not null
				and Reservation_Owner &lt;&gt; 0
		        and cnf_AccountRestriction.AccountType = @AccountType
				and ((cnf_AccountRestriction2Account.accountid is not null) or (cnf_AccountRestriction2DMGCategory.dmgcategoryid is not null))
				and (((@SalesID = 0) and (Res_Table.ShopCartGuid = @GUID))
						or (('0' = @GUID) and (Res_Table.Saleid = @SalesID)))

			GROUP BY Reservation_Owner,
							Res_Table.MatrixCellID,
							SaleID,
							SaleitemID,
							CheckforRestrictionOnly,
							cnf_AccountRestriction.AccountRestrictionID,
							Limit,
							Res_Table.PerformanceID,
							RES_Table.Eventid
	OPEN Check_Cursor

	FETCH NEXT FROM Check_Cursor INTO
						@AccountID,
						@MatrixCellID,
						@Quantity,
						@SaleID,
						@SaleitemID,
						@CheckforRestrictionOnly,
						@AccountRestrictionID,
						@Limit,
						@PerformanceID,
						@EventID


	WHILE @@FETCH_STATUS = 0
	BEGIN
		IF @OldAccountRestrictionID &lt;&gt; @AccountRestrictionID and (@PreventSale = 0) or ((@OldAccountRestrictionID = @AccountRestrictionID) and (@PreventSale = 0) and (@Old_PerformanceID &lt;&gt; @PerformanceID))
		BEGIN 

			SET @Prevent = 0;

			select @FullQuantity = sum(Quantity),  @CountofMatrixCells = 1
				from data_shopcartitemlimit Res_Table
				where PerformanceID = @PerformanceID 	
					and Reservation_Owner = @AccountID
					and (((@SalesID = 0) and (Res_Table.ShopCartGuid = @GUID))
							or (('0' = @GUID) and (Res_Table.Saleid = @SalesID)))

			if @FullQuantity &gt; 0
			Begin				
				if @CountofMatrixCells = 1 						 																
					Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @RestrictionType, @AccountType, @AccountID,  
														@PerformanceID, @EventID, @SaleID, @SaleitemID, @CheckforRestrictionOnly, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
				else
				begin
					Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @RestrictionType, @AccountType, @AccountID, 
														@PerformanceID, @EventID, @SaleID, @SaleitemID, 1, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
					set @Prevent = @PreventSale

					if @Prevent = 0 and @CheckforRestrictionOnly = 0 
					begin
						DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

						INSERT INTO [dbo].[DATA_AccountLimit]
										([AccountRestrictionId]
										,[AccountId]
										,[PerformanceId]
										,[SaleId]
										,[SaleItemId]
										,[SaleDate]
										,[ReservationAccountQuantity])
									VALUES
										(@AccountRestrictionID
										,@AccountID
										,@PerformanceID
										,@SaleID
										,@SaleItemID
										,@SalesDate
										,@FullQuantity)							 
					end
				end
			end
			else
			begin
				INSERT INTO [dbo].[DATA_AccountLimit]
								([AccountRestrictionId]
								,[AccountId]
								,[PerformanceId]
								,[SaleId]
								,[SaleItemId]
								,[SaleDate]
								,[ReservationAccountQuantity])
							VALUES
								(@AccountRestrictionID
								,@AccountID
								,@PerformanceID
								,@SaleID
								,@SaleItemID
								,@SalesDate
								,@Quantity)	
			end
		END
		ELSE
		BEGIN
			IF @OldAccountRestrictionID = @AccountRestrictionID and @AccountID = @OLD_Resevation_Owner and @Quantity &lt; 0
			begin
								INSERT INTO [dbo].[DATA_AccountLimit]
												([AccountRestrictionId]
												,[AccountId]
												,[PerformanceId]
												,[SaleId]
												,[SaleItemId]
												,[SaleDate]
												,[ReservationAccountQuantity])
											VALUES
												(@AccountRestrictionID
												,@AccountID
												,@PerformanceID
												,@SaleID
												,@SaleItemID
												,@SalesDate
												,@Quantity)	



			end 
			IF @OldAccountRestrictionID &lt;&gt; @AccountRestrictionID and @AccountID &lt;&gt; @OLD_Resevation_Owner
			begin
				if @Prevent = 0 and @CheckforRestrictionOnly = 0 
				begin
					DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

					INSERT INTO [dbo].[DATA_AccountLimit]
									([AccountRestrictionId]
									,[AccountId]
									,[PerformanceId]
									,[SaleId]
									,[SaleItemId]
									,[SaleDate]
									,[ReservationAccountQuantity])
								VALUES
									(@AccountRestrictionID
									,@AccountID
									,@PerformanceID
									,@SaleID
									,@SaleItemID
									,@SalesDate
									,@Quantity)						 
				end
			end
		END

		Set @OldAccountRestrictionID = @AccountRestrictionID
		SET @OLD_Resevation_Owner = @AccountID
		SET @Old_PerformanceID = @PerformanceID

		FETCH NEXT FROM Check_Cursor INTO
						@AccountID,
						@MatrixCellID,
						@Quantity,
						@SaleID,
						@SaleitemID,
						@CheckforRestrictionOnly,
						@AccountRestrictionID,
						@Limit,
						@PerformanceID,
						@EventID
	END

	CLOSE Check_Cursor;
	DEALLOCATE Check_Cursor;


--Event Reservation Owner Check
	IF @PreventSale = 0
	BEGIN
		Set @OldAccountRestrictionID = 99999
		DECLARE Check_Cursor CURSOR LOCAL FOR
			select   Reservation_Owner,
								Res_Table.MatrixCellID,
								SUM(Quantity) as Quantity,
								SaleID,
								SaleitemID,
								CheckforRestrictionOnly,
								cnf_AccountRestriction.AccountRestrictionID,
								cnf_AccountRestriction.Limit,
								Res_Table.PerformanceID,
								RES_Table.Eventid

				from data_shopcartitemlimit Res_Table
					INNER JOIN CNF_AccountRestriction2Event WITH(NOLOCK)					ON CNF_AccountRestriction2Event.EventID = Res_Table.EventID

					LEFT JOIN cnf_AccountRestriction2Account WITH(NOLOCK)					ON (cnf_AccountRestriction2Account.AccountID = Res_Table.Reservation_Owner)																							
					                     														and CNF_AccountRestriction2Event.AccountRestrictionId = cnf_AccountRestriction2Account.AccountRestrictionId	
																								
					LEFT JOIN cnf_AccountRestriction2DMGCategory WITH(NOLOCK)				ON (cnf_AccountRestriction2DMGCategory.DMGCategoryID = (select DMGCategoryID from data_account WITH(NOLOCK) where data_account.accountid = Res_Table.Reservation_Owner))																							
					                         													and CNF_AccountRestriction2Event.AccountRestrictionId = cnf_AccountRestriction2DMGCategory.AccountRestrictionId	

					INNER JOIN cnf_AccountRestriction WITH(NOLOCK)							ON cnf_AccountRestriction.AccountRestrictionId = CNF_AccountRestriction2Event.AccountRestrictionId

				where cnf_AccountRestriction.Enabled = 1
				and Convert(date, GetDAte(), 120) between Convert(date, StartDateTime, 120) and Convert(date, EndDateTime, 120)
				and CNF_AccountRestriction.RestrictionType = @RestrictionType
				and Res_Table.Reservation_Owner is not null
				and Limit is not null
				and Res_Table.Reservation_Owner &lt;&gt; 0
		        and cnf_AccountRestriction.AccountType =  @AccountType
				and ((cnf_AccountRestriction2Account.accountid is not null) or (cnf_AccountRestriction2DMGCategory.dmgcategoryid is not null))
				and (((@SalesID = 0) and (Res_Table.ShopCartGuid = @GUID))
						or (('0' = @GUID) and (Res_Table.Saleid = @SalesID)))

				GROUP BY Reservation_Owner,
								Res_Table.MatrixCellID,
								SaleID,
								SaleitemID,
								CheckforRestrictionOnly,
								cnf_AccountRestriction.AccountRestrictionID,
								cnf_AccountRestriction.Limit,
								Res_Table.PerformanceID,
								RES_Table.Eventid

		OPEN Check_Cursor

		FETCH NEXT FROM Check_Cursor INTO
							@AccountID,
							@MatrixCellID,
							@Quantity,
							@SaleID,
							@SaleitemID,
							@CheckforRestrictionOnly,
							@AccountRestrictionID,
							@Limit,
							@PerformanceID,
							@EventID


		WHILE @@FETCH_STATUS = 0
		BEGIN
			IF @OldAccountRestrictionID &lt;&gt; @AccountRestrictionID and (@PreventSale = 0) 
					or ((@OldAccountRestrictionID = @AccountRestrictionID) and (@PreventSale = 0) and (@OLD_PerformanceID &lt;&gt; @PerformanceID))
			BEGIN 


				SET @Prevent = 0;


				select @FullQuantity = sum(Quantity),  @CountofMatrixCells = 1 
					from data_shopcartitemlimit Res_Table
					where PerformanceID = @PerformanceID	
						and Reservation_Owner = @AccountID
					    and (((@SalesID = 0) and (Res_Table.ShopCartGuid = @GUID))
							 or (('0' = @GUID) and (Res_Table.Saleid = @SalesID)))

				if @FullQuantity &gt; 0
				Begin
					if @CountofMatrixCells = 1 
						
						Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @RestrictionType, @AccountType, @AccountID, 
															@PerformanceID, @EventID, @SaleID, @SaleitemID, @CheckforRestrictionOnly, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
					else
					begin
						Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @RestrictionType, @AccountType, @AccountID, 
															@PerformanceID, @EventID, @SaleID, @SaleitemID, 1, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
						set @Prevent = @PreventSale

						if @Prevent = 0 and @CheckforRestrictionOnly = 0 
						begin
							DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

							INSERT INTO [dbo].[DATA_AccountLimit]
											([AccountRestrictionId]
											,[AccountId]
											,[PerformanceId]
											,[SaleId]
											,[SaleItemId]
											,[SaleDate]
											,[ReservationAccountQuantity])
										VALUES
											(@AccountRestrictionID
											,@AccountID
											,@PerformanceID
											,@SaleID
											,@SaleItemID
											,@SalesDate
											,@FullQuantity)							 
						end
					end
				end
				else
				begin
					INSERT INTO [dbo].[DATA_AccountLimit]
									([AccountRestrictionId]
									,[AccountId]
									,[PerformanceId]
									,[SaleId]
									,[SaleItemId]
									,[SaleDate]
									,[ReservationAccountQuantity])
								VALUES
									(@AccountRestrictionID
									,@AccountID
									,@PerformanceID
									,@SaleID
									,@SaleItemID
									,@SalesDate
									,@Quantity)	
				end
			END
			ELSE
			BEGIN
				IF @OldAccountRestrictionID = @AccountRestrictionID and @AccountID = @OLD_Resevation_Owner and @Quantity &lt; 0
				begin
									INSERT INTO [dbo].[DATA_AccountLimit]
													([AccountRestrictionId]
													,[AccountId]
													,[PerformanceId]
													,[SaleId]
													,[SaleItemId]
													,[SaleDate]
													,[ReservationAccountQuantity])
												VALUES
													(@AccountRestrictionID
													,@AccountID
													,@PerformanceID
													,@SaleID
													,@SaleItemID
													,@SalesDate
													,@Quantity)	

				end 
				IF @OldAccountRestrictionID &lt;&gt; @AccountRestrictionID and @AccountID &lt;&gt; @OLD_Resevation_Owner
				begin
					if @Prevent = 0 and @CheckforRestrictionOnly = 0 
					begin
								DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

								INSERT INTO [dbo].[DATA_AccountLimit]
												([AccountRestrictionId]
												,[AccountId]
												,[PerformanceId]
												,[SaleId]
												,[SaleItemId]
												,[SaleDate]
												,[ReservationAccountQuantity])
											VALUES
												(@AccountRestrictionID
												,@AccountID
												,@PerformanceID
												,@SaleID
												,@SaleItemID
												,@SalesDate
												,@Quantity)						 
					end
				end
			END			

			Set @OldAccountRestrictionID = @AccountRestrictionID
			SET @OLD_Resevation_Owner = @AccountID
			SET @Old_EventID = @EventID
			Set @Old_PerformanceID = @PerformanceID

		FETCH NEXT FROM Check_Cursor INTO
							@AccountID,
							@MatrixCellID,
							@Quantity,
							@SaleID,
							@SaleitemID,
							@CheckforRestrictionOnly,
							@AccountRestrictionID,
							@Limit,
							@PerformanceID,
							@EventID
		END

		CLOSE Check_Cursor;
		DEALLOCATE Check_Cursor;
	END

RETURN;
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_AR_TicketOwner_Matrixcell]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_AR_TicketOwner_Matrixcell</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>CREATE PROCEDURE [otn_sp_AR_TicketOwner_Matrixcell]  (
                                                      @GUID        varchar(100), 
													  @SalesId		int,
													  @PreventSale int OUTPUT,
													  @RejectReasonErrorCode int OUTPUT,
													  @RejectType int OUTPUT,
													  @RejectRestrictionDescription varchar(100) OUTPUT,
													  @RejectRemainingAmount int OUTPUT
                                                    ) 
AS    
BEGIN


	DECLARE @SalesDate datetime = getdate();
	DECLARE @RestrictionType int = 1
    DECLARE @AccountType int = 4
	DECLARE @OldAccountRestrictionID int = 99999
	DECLARE @AccountRestrictionID int
	DECLARE @AccountID int
	DECLARE @MatrixCellID int
	DECLARE @Quantity int
	DECLARE @FullQuantity int
	DECLARE @PerformanceID int
	DECLARE @EventID int
	DECLARE @SaleID int
	DECLARE @SaleitemID int
	DECLARE @CheckforRestrictionOnly int
	DECLARE @Limit int
	DECLARE @OLD_Ticket_Owner int
	DECLARE @CountofMatrixCells int = 0
	DECLARE @Prevent int = 0


	Set @OldAccountRestrictionID = 99999
	SET @OLD_Ticket_Owner = 99999

	DECLARE Check_Cursor CURSOR LOCAL FOR
		select   			Ticket_Owner,
							Res_Table.MatrixCellID,
							SUM(Quantity) as Quantity,
							SaleID,
							SaleitemID,
							CheckforRestrictionOnly,
							cnf_AccountRestriction.AccountRestrictionID,
							cnf_AccountRestriction.Limit

			from data_shopcartitemlimit Res_Table
				INNER JOIN cnf_AccountRestriction2MatrixCell WITH(NOLOCK)				ON cnf_AccountRestriction2MatrixCell.MatrixCellID = Res_Table.MatrixCellID
					
				LEFT JOIN cnf_AccountRestriction2Account WITH(NOLOCK)					ON (cnf_AccountRestriction2Account.AccountID = Res_Table.Ticket_Owner)																							
					                                                                    and cnf_accountrestriction2Account.AccountRestrictionID = CNF_AccountRestriction2MatrixCell.AccountRestrictionId
																										
			    LEFT JOIN cnf_AccountRestriction2DMGCategory WITH(NOLOCK)				ON (cnf_AccountRestriction2DMGCategory.DMGCategoryID = (select DMGCategoryID from data_account WITH(NOLOCK) where data_account.accountid = Res_Table.Ticket_Owner))																							
					                                                                    and cnf_AccountRestriction2DMGCategory.AccountRestrictionID = CNF_AccountRestriction2MatrixCell.AccountRestrictionId				
				
				INNER JOIN cnf_AccountRestriction WITH(NOLOCK)							ON cnf_AccountRestriction.AccountRestrictionId = cnf_AccountRestriction2MatrixCell.AccountRestrictionId

			where cnf_AccountRestriction.Enabled = 1
			and Convert(date, GetDAte(), 120) between Convert(date, StartDateTime, 120) and Convert(date, EndDateTime, 120)
			and CNF_AccountRestriction.RestrictionType = @RestrictionType
			and Res_Table.Ticket_Owner is not null
			and Limit is not null
			and cnf_AccountRestriction.AccountType = @AccountType
			and Res_Table.Ticket_Owner &lt;&gt; 0
			and ((cnf_AccountRestriction2Account.accountid is not null) or (cnf_AccountRestriction2DMGCategory.dmgcategoryid is not null))
			and ISNULL(Res_Table.PerformanceID, 0) = 0
		    and (((@SalesID = 0) and (Res_Table.ShopCartGuid = @GUID))
		         or (('0' = @GUID) and (Res_Table.Saleid = @SalesID)))

			GROUP BY 
							Ticket_Owner,
							Res_Table.MatrixCellID,
							SaleID,
							SaleitemID,
							CheckforRestrictionOnly,
							cnf_AccountRestriction.AccountRestrictionID,
							cnf_AccountRestriction.Limit

			order by Ticket_Owner, AccountRestrictionID

	OPEN Check_Cursor

	FETCH NEXT FROM Check_Cursor INTO
						@AccountID,
						@MatrixCellID,
						@Quantity,
						@SaleID,
						@SaleitemID,
						@CheckforRestrictionOnly,
						@AccountRestrictionID,
						@Limit


	WHILE @@FETCH_STATUS = 0
	BEGIN
		IF @OldAccountRestrictionID &lt;&gt; @AccountRestrictionID and (@PreventSale = 0)  or ((@OldAccountRestrictionID = @AccountRestrictionID) and (@PreventSale = 0) and (@AccountID &lt;&gt; @OLD_Ticket_Owner))
		BEGIN 

			SET @Prevent = 0;

			select @FullQuantity = sum(Quantity),  @CountofMatrixCells = Count(*) 
				from data_shopcartitemlimit Res_Table
				where MatrixCellID in (select MatrixcellId 
										from cnf_AccountRestriction2MatrixCell WITH(NOLOCK)									
										where cnf_AccountRestriction2MatrixCell.AccountRestrictionId = @AccountRestrictionID)	
					and Ticket_Owner = @AccountID
					and ISNULL(PerformanceID, 0) = 0
				    and (((@SalesID = 0) and (Res_Table.ShopCartGuid = @GUID))
						 or (('0' = @GUID) and (Res_Table.Saleid = @SalesID)))

			if @FullQuantity &gt; 0
			Begin				
				if @CountofMatrixCells = 1 						 																
					Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @RestrictionType, @AccountType, @AccountID, 
														null, null, @SaleID, @SaleitemID, @CheckforRestrictionOnly, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
				ELSE
				begin
					Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @RestrictionType, @AccountType, @AccountID, 
														null, null, @SaleID, @SaleitemID, 1, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
					set @Prevent = @PreventSale

					if @Prevent = 0 and @CheckforRestrictionOnly = 0 
					begin
						DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

						INSERT INTO [dbo].[DATA_AccountLimit]
										([AccountRestrictionId]
										,[AccountId]
										,[PerformanceId]
										,[SaleId]
										,[SaleItemId]
										,[SaleDate]
										,[ReservationAccountQuantity])
									VALUES
										(@AccountRestrictionID
										,@AccountID
										,@PerformanceID
										,@SaleID
										,@SaleItemID
										,@SalesDate
										,@FullQuantity)							 
					end
				end
			end
			else
			begin
				INSERT INTO [dbo].[DATA_AccountLimit]
								([AccountRestrictionId]
								,[AccountId]
								,[PerformanceId]
								,[SaleId]
								,[SaleItemId]
								,[SaleDate]
								,[ReservationAccountQuantity])
							VALUES
								(@AccountRestrictionID
								,@AccountID
								,@PerformanceID
								,@SaleID
								,@SaleItemID
								,@SalesDate
								,@Quantity)	
			end
		END
		ELSE
		BEGIN
			IF @OldAccountRestrictionID = @AccountRestrictionID and @AccountID = @OLD_Ticket_Owner and @Quantity &lt; 0
			begin
								INSERT INTO [dbo].[DATA_AccountLimit]
												([AccountRestrictionId]
												,[AccountId]
												,[PerformanceId]
												,[SaleId]
												,[SaleItemId]
												,[SaleDate]
												,[ReservationAccountQuantity])
											VALUES
												(@AccountRestrictionID
												,@AccountID
												,@PerformanceID
												,@SaleID
												,@SaleItemID
												,@SalesDate
												,@Quantity)	

			end 
			IF @OldAccountRestrictionID &lt;&gt; @AccountRestrictionID and @AccountID &lt;&gt; @OLD_Ticket_Owner
			begin
				if @Prevent = 0 and @CheckforRestrictionOnly = 0 
				begin
							DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

							INSERT INTO [dbo].[DATA_AccountLimit]
											([AccountRestrictionId]
											,[AccountId]
											,[PerformanceId]
											,[SaleId]
											,[SaleItemId]
											,[SaleDate]
											,[ReservationAccountQuantity])
										VALUES
											(@AccountRestrictionID
											,@AccountID
											,@PerformanceID
											,@SaleID
											,@SaleItemID
											,@SalesDate
											,@Quantity)						 
				end
			end
		END

		Set @OldAccountRestrictionID = @AccountRestrictionID
		SET @OLD_Ticket_Owner = @AccountID

		FETCH NEXT FROM Check_Cursor INTO
						@AccountID,
						@MatrixCellID,
						@Quantity,
						@SaleID,
						@SaleitemID,
						@CheckforRestrictionOnly,
						@AccountRestrictionID,
						@Limit

	END

	CLOSE Check_Cursor;
	DEALLOCATE Check_Cursor;


RETURN;

END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_AR_TicketOwner_Performance]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_AR_TicketOwner_Performance</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>CREATE PROCEDURE [otn_sp_AR_TicketOwner_Performance]  (
                                                      @GUID        varchar(100), 
													  @SalesId		int,
													  @PreventSale int OUTPUT,
													  @RejectReasonErrorCode int OUTPUT,
													  @RejectType int OUTPUT,
													  @RejectRestrictionDescription varchar(100) OUTPUT,
													  @RejectRemainingAmount int OUTPUT
                                                    ) 
AS    
BEGIN

	DECLARE @SalesDate datetime = getdate();
	DECLARE @RestrictionType int = 2
    DECLARE @AccountType int = 4
	DECLARE @OldAccountRestrictionID int = 99999
	DECLARE @AccountRestrictionID int
	DECLARE @AccountID int
	DECLARE @MatrixCellID int
	DECLARE @Quantity int
	DECLARE @FullQuantity int
	DECLARE @PerformanceID int
	DECLARE @EventID int
	DECLARE @SaleID int
	DECLARE @SaleitemID int
	DECLARE @CheckforRestrictionOnly int
	DECLARE @Limit int
	DECLARE @OLD_Ticket_Owner int
	DECLARE @CountofMatrixCells int = 0
	DECLARE @Prevent int = 0
	DECLARE @Old_PerformanceID int = 0
	DECLARE @Old_EventID int = 0

	
--Performance Reservation Owner Check
	Set @OldAccountRestrictionID = 99999
	Set @OLD_Ticket_Owner = 99999
	
	DECLARE Check_Cursor CURSOR LOCAL FOR
		select   
							Ticket_Owner,
							Res_Table.MatrixCellID,
							SUM(Quantity) as Quantity,
							SaleID,
							SaleitemID,
							CheckforRestrictionOnly,
							cnf_AccountRestriction.AccountRestrictionID,
							cnf_AccountRestriction.Limit,
							Res_Table.PerformanceID,
							RES_Table.Eventid

			from data_shopcartitemlimit Res_Table
				INNER JOIN CNF_AccountRestriction2Performance							ON CNF_AccountRestriction2Performance.PerformanceID = Res_Table.PerformanceID

				LEFT JOIN cnf_AccountRestriction2Account WITH(NOLOCK)					ON (cnf_AccountRestriction2Account.AccountID = Res_Table.Ticket_Owner)
					                                                                        and cnf_AccountRestriction2Account.AccountRestrictionId = CNF_AccountRestriction2Performance.AccountRestrictionId
					                     																								
			    LEFT JOIN cnf_AccountRestriction2DMGCategory WITH(NOLOCK)				ON (cnf_AccountRestriction2DMGCategory.DMGCategoryID = (select DMGCategoryID from data_account WITH(NOLOCK) where data_account.accountid = Res_Table.Ticket_Owner))																							
					                                                                 		and cnf_AccountRestriction2DMGCategory.AccountRestrictionId = CNF_AccountRestriction2Performance.AccountRestrictionId
				INNER JOIN cnf_AccountRestriction WITH(NOLOCK)							ON cnf_AccountRestriction.AccountRestrictionId = CNF_AccountRestriction2Performance.AccountRestrictionId

			where cnf_AccountRestriction.Enabled = 1
			and Convert(date, GetDAte(), 120) between Convert(date, StartDateTime, 120) and Convert(date, EndDateTime, 120)
			and CNF_AccountRestriction.RestrictionType = @RestrictionType
			and Res_Table.Ticket_Owner is not null
			and TicketAccountLimit is not null
			and Res_Table.Ticket_Owner &lt;&gt; 0
		    and cnf_AccountRestriction.AccountType = @AccountType
			and ((cnf_AccountRestriction2Account.accountid is not null) or (cnf_AccountRestriction2DMGCategory.dmgcategoryid is not null))
		    and (((@SalesID = 0) and (Res_Table.ShopCartGuid = @GUID))
		         or (('0' = @GUID) and (Res_Table.Saleid = @SalesID)))

			GROUP BY 
							Ticket_Owner,
							Res_Table.MatrixCellID,
							SaleID,
							SaleitemID,
							CheckforRestrictionOnly,
							cnf_AccountRestriction.AccountRestrictionID,
							cnf_AccountRestriction.Limit,
							Res_Table.PerformanceID,
							RES_Table.Eventid

	OPEN Check_Cursor

	FETCH NEXT FROM Check_Cursor INTO
						@AccountID,
						@MatrixCellID,
						@Quantity,
						@SaleID,
						@SaleitemID,
						@CheckforRestrictionOnly,
						@AccountRestrictionID,
						@Limit,
						@PerformanceID,
						@EventID


	WHILE @@FETCH_STATUS = 0
	BEGIN
		IF @OldAccountRestrictionID &lt;&gt; @AccountRestrictionID and (@PreventSale = 0) or ((@OldAccountRestrictionID = @AccountRestrictionID) and (@PreventSale = 0) and ((@Old_PerformanceID &lt;&gt; @PerformanceID) or (@OLD_Ticket_Owner &lt;&gt; @AccountID)))
		BEGIN 

			SET @Prevent = 0;

			select @FullQuantity = sum(Quantity),  @CountofMatrixCells = 1
				from data_shopcartitemlimit Res_Table
				where PerformanceID = @PerformanceID 	
					and Ticket_Owner = @AccountID
				    and (((@SalesID = 0) and (Res_Table.ShopCartGuid = @GUID))
						 or (('0' = @GUID) and (Res_Table.Saleid = @SalesID)))

			if @FullQuantity &gt; 0
			Begin
				if @CountofMatrixCells = 1 						 																
					Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @RestrictionType, @AccountType, @AccountID, 
														@PerformanceID, @EventID, @SaleID, @SaleitemID, @CheckforRestrictionOnly, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
				else
				begin
					Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @RestrictionType, @AccountType, @AccountID, 
														@PerformanceID, @EventID, @SaleID, @SaleitemID, 1, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
					set @Prevent = @PreventSale

					if @Prevent = 0 and @CheckforRestrictionOnly = 0 
					begin
						DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

						INSERT INTO [dbo].[DATA_AccountLimit]
										([AccountRestrictionId]
										,[AccountId]
										,[PerformanceId]
										,[SaleId]
										,[SaleItemId]
										,[SaleDate]
										,[ReservationAccountQuantity])
									VALUES
										(@AccountRestrictionID
										,@AccountID
										,@PerformanceID
										,@SaleID
										,@SaleItemID
										,@SalesDate
										,@FullQuantity)								 
					end
				end
			end
			else
			begin
				INSERT INTO [dbo].[DATA_AccountLimit]
								([AccountRestrictionId]
								,[AccountId]
								,[PerformanceId]
								,[SaleId]
								,[SaleItemId]
								,[SaleDate]
								,[ReservationAccountQuantity])
							VALUES
								(@AccountRestrictionID
								,@AccountID
								,@PerformanceID
								,@SaleID
								,@SaleItemID
								,@SalesDate
								,@Quantity)	
			end
		END
		ELSE
		BEGIN
			IF @OldAccountRestrictionID = @AccountRestrictionID and @AccountID = @OLD_Ticket_Owner and @Quantity &lt; 0
			begin
								INSERT INTO [dbo].[DATA_AccountLimit]
												([AccountRestrictionId]
												,[AccountId]
												,[PerformanceId]
												,[SaleId]
												,[SaleItemId]
												,[SaleDate]
												,[ReservationAccountQuantity])
											VALUES
												(@AccountRestrictionID
												,@AccountID
												,@PerformanceID
												,@SaleID
												,@SaleItemID
												,@SalesDate
												,@Quantity)	

			end 
				
			IF @OldAccountRestrictionID &lt;&gt; @AccountRestrictionID and @AccountID &lt;&gt; @OLD_Ticket_Owner
			begin
				if @Prevent = 0 and @CheckforRestrictionOnly = 0 
				begin
							DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

							INSERT INTO [dbo].[DATA_AccountLimit]
											([AccountRestrictionId]
											,[AccountId]
											,[PerformanceId]
											,[SaleId]
											,[SaleItemId]
											,[SaleDate]
											,[ReservationAccountQuantity])
										VALUES
											(@AccountRestrictionID
											,@AccountID
											,@PerformanceID
											,@SaleID
											,@SaleItemID
											,@SalesDate
											,@Quantity)						 
				end
			end
		END
		Set @OldAccountRestrictionID = @AccountRestrictionID
		Set @OLD_Ticket_Owner = @AccountID

	FETCH NEXT FROM Check_Cursor INTO
						@AccountID,
						@MatrixCellID,
						@Quantity,
						@SaleID,
						@SaleitemID,
						@CheckforRestrictionOnly,
						@AccountRestrictionID,
						@Limit,
						@PerformanceID,
						@EventID
	END

	CLOSE Check_Cursor;
	DEALLOCATE Check_Cursor;


--Event Ticket Owner Check
	IF @PreventSale = 0
	BEGIN
		Set @OldAccountRestrictionID = 99999
		Set @OLD_Ticket_Owner = 99999
		DECLARE Check_Cursor CURSOR LOCAL FOR
			select   
							 Ticket_Owner,
							 Res_Table.MatrixCellID,
							 SUM(Quantity),
							 SaleID,
							 SaleitemID,
							 CheckforRestrictionOnly,
							 cnf_AccountRestriction.AccountRestrictionID,
							 cnf_AccountRestriction.Limit,
							 Res_Table.PerformanceID,
							 RES_Table.Eventid

		
				from data_shopcartitemlimit Res_Table
					INNER JOIN CNF_AccountRestriction2Event WITH(NOLOCK)					ON CNF_AccountRestriction2Event.EventID = Res_Table.EventID

					LEFT JOIN cnf_AccountRestriction2Account WITH(NOLOCK)					ON (cnf_AccountRestriction2Account.AccountID = Res_Table.Ticket_Owner)																							
					                     														and CNF_AccountRestriction2Event.AccountRestrictionId = cnf_AccountRestriction2Account.AccountRestrictionId	
																								
			        LEFT JOIN cnf_AccountRestriction2DMGCategory WITH(NOLOCK)				ON (cnf_AccountRestriction2DMGCategory.DMGCategoryID = (select DMGCategoryID from data_account WITH(NOLOCK) where data_account.accountid = Res_Table.Ticket_Owner))																							
					                         													and CNF_AccountRestriction2Event.AccountRestrictionId = cnf_AccountRestriction2DMGCategory.AccountRestrictionId	

					INNER JOIN cnf_AccountRestriction WITH(NOLOCK)							ON cnf_AccountRestriction.AccountRestrictionId = CNF_AccountRestriction2Event.AccountRestrictionId


			 where cnf_AccountRestriction.Enabled = 1
			   and Convert(date, GetDAte(), 120) between Convert(date, StartDateTime, 120) and Convert(date, EndDateTime, 120)
			   and CNF_AccountRestriction.RestrictionType = @RestrictionType
			   and Res_Table.Ticket_Owner is not null
			   and Limit is not null
			   and Res_Table.Ticket_Owner &lt;&gt; 0
		       and cnf_AccountRestriction.AccountType = @AccountType
			   and ((cnf_AccountRestriction2Account.accountid is not null) or (cnf_AccountRestriction2DMGCategory.dmgcategoryid is not null))
			   and (((@SalesID = 0) and (Res_Table.ShopCartGuid = @GUID))
					 or (('0' = @GUID) and (Res_Table.Saleid = @SalesID)))

			 GROUP BY 
							 Ticket_Owner,
							 Res_Table.MatrixCellID,
							 SaleID,
							 SaleitemID,
							 CheckforRestrictionOnly,
							 cnf_AccountRestriction.AccountRestrictionID,
							 cnf_AccountRestriction.Limit,
							 Res_Table.PerformanceID,
							 RES_Table.Eventid

		OPEN Check_Cursor

		FETCH NEXT FROM Check_Cursor INTO
							@AccountID,
							@MatrixCellID,
							@Quantity,
							@SaleID,
							@SaleitemID,
							@CheckforRestrictionOnly,
							@AccountRestrictionID,
							@Limit,
							@PerformanceID,
							@EventID


		WHILE @@FETCH_STATUS = 0
		BEGIN
			IF @OldAccountRestrictionID &lt;&gt; @AccountRestrictionID  and (@PreventSale = 0) 
			     or ((@OldAccountRestrictionID = @AccountRestrictionID) and (@PreventSale = 0)  and ((@OLD_PerformanceID &lt;&gt; @PerformanceID) or (@OLD_Ticket_Owner &lt;&gt; @AccountID)))			  
			BEGIN 

				SET @Prevent = 0;

				select @FullQuantity = sum(Quantity),  @CountofMatrixCells = 1
					from data_shopcartitemlimit Res_Table
					where PerformanceID = @PerformanceID  	
						and Ticket_Owner = @AccountID
					    and (((@SalesID = 0) and (Res_Table.ShopCartGuid = @GUID))
							 or (('0' = @GUID) and (Res_Table.Saleid = @SalesID)))	
						
				if @FullQuantity &gt; 0
				Begin
					if @CountofMatrixCells = 1 						 																
						Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @RestrictionType, @AccountType, @AccountID, 
															@PerformanceID, @EventID, @SaleID, @SaleitemID, @CheckforRestrictionOnly, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
					else
					begin
						Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @RestrictionType, @AccountType, @AccountID, 
															@PerformanceID, @EventID, @SaleID, @SaleitemID, 1, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
						set @Prevent = @PreventSale

						if @Prevent = 0 and @CheckforRestrictionOnly = 0 
						begin
							DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

							INSERT INTO [dbo].[DATA_AccountLimit]
											([AccountRestrictionId]
											,[AccountId]
											,[PerformanceId]
											,[SaleId]
											,[SaleItemId]
											,[SaleDate]
											,[ReservationAccountQuantity])
										VALUES
											(@AccountRestrictionID
											,@AccountID
											,@PerformanceID
											,@SaleID
											,@SaleItemID
											,@SalesDate
											,@FullQuantity)							 
						end
					end
				end
				else
				begin
					INSERT INTO [dbo].[DATA_AccountLimit]
									([AccountRestrictionId]
									,[AccountId]
									,[PerformanceId]
									,[SaleId]
									,[SaleItemId]
									,[SaleDate]
									,[ReservationAccountQuantity])
								VALUES
									(@AccountRestrictionID
									,@AccountID
									,@PerformanceID
									,@SaleID
									,@SaleItemID
									,@SalesDate
									,@Quantity)	
				end
			END
			ELSE
			BEGIN
				IF @OldAccountRestrictionID = @AccountRestrictionID and @AccountID = @OLD_Ticket_Owner and @Quantity &lt; 0
				begin
									INSERT INTO [dbo].[DATA_AccountLimit]
													([AccountRestrictionId]
													,[AccountId]
													,[PerformanceId]
													,[SaleId]
													,[SaleItemId]
													,[SaleDate]
													,[ReservationAccountQuantity])
												VALUES
													(@AccountRestrictionID
													,@AccountID
													,@PerformanceID
													,@SaleID
													,@SaleItemID
													,@SalesDate
													,@Quantity)	

				end 
				IF @OldAccountRestrictionID &lt;&gt; @AccountRestrictionID and @AccountID &lt;&gt; @OLD_Ticket_Owner
				begin
					if @Prevent = 0 and @CheckforRestrictionOnly = 0 
					begin
								DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

								INSERT INTO [dbo].[DATA_AccountLimit]
												([AccountRestrictionId]
												,[AccountId]
												,[PerformanceId]
												,[SaleId]
												,[SaleItemId]
												,[SaleDate]
												,[ReservationAccountQuantity])
											VALUES
												(@AccountRestrictionID
												,@AccountID
												,@PerformanceID
												,@SaleID
												,@SaleItemID
												,@SalesDate
												,@Quantity )						 
					end
				end
			END
			

			Set @OldAccountRestrictionID = @AccountRestrictionID
			Set @OLD_Ticket_Owner = @AccountID
			SET @OLD_EventID = @EventID
			Set @Old_PerformanceID = @PerformanceID

		FETCH NEXT FROM Check_Cursor INTO
							@AccountID,
							@MatrixCellID,
							@Quantity,
							@SaleID,
							@SaleitemID,
							@CheckforRestrictionOnly,
							@AccountRestrictionID,
							@Limit,
							@PerformanceID,
							@EventID
		END

		CLOSE Check_Cursor;
		DEALLOCATE Check_Cursor;
	END

RETURN;
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_CheckAccountRestrictions]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_CheckAccountRestrictions</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>CREATE PROCEDURE [otn_sp_CheckAccountRestrictions]  (
													  @GUID                      varchar(100),
													  @SalesId					 int
                                                    ) 
AS    
BEGIN

	DECLARE @PreventSale int = 0
	DECLARE @RejectReasonErrorCode int = 0
	DECLARE @RejectRestrictionDescription varchar(100) = ''
	DECLARE @RejectRemainingAmount int = 0
	DECLARE @RejectType int = 0
	DECLARE @sql varchar(250) = ''
	DECLARE @B2BAccountType int = 2
	DECLARE @BillAccountType int = 3
	DECLARE @ResAccountType int = 1
	DECLARE @TicketAccountType int = 4

	DECLARE @TicketType int = 1
	DECLARE @PerformanceType int = 2

	   	 
--Reservation Owner Check by Ticket
	IF EXISTS(select *
				from CNF_AccountRestriction
				where Accounttype = @ResAccountType and RestrictionType = @TicketType)
		exec otn_sp_AR_ReservationOwner_Matrixcell @GUID, @SalesId, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
	

--Reservation Owner Check by Event/Performance
  	If @PreventSale = 0 
	Begin
		IF EXISTS(select *
					from CNF_AccountRestriction
					where Accounttype = @ResAccountType and RestrictionType = @PerformanceType)
		   exec otn_sp_AR_ReservationOwner_Performance @GUID, @SalesId, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
	end


--B2B Owner Check by Ticket
	If @PreventSale = 0 
	Begin
		IF EXISTS(select *
					from CNF_AccountRestriction
					where Accounttype = @B2BAccountType and RestrictionType = @TicketType)
		   exec otn_sp_AR_B2BOwner_Matrixcell @GUID, @SalesId, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
	end


--B2B Owner Check by Event/Performance
	If @PreventSale = 0 
	Begin
		IF EXISTS(select *
					from CNF_AccountRestriction
					where Accounttype = @B2BAccountType and RestrictionType = @PerformanceType)
		   exec otn_sp_AR_B2BOwner_Performance @GUID, @SalesId, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
	end


--Billing Owner Check by Ticket
	If @PreventSale = 0 
	Begin
		IF EXISTS(select *
					from CNF_AccountRestriction
					where Accounttype = @BillAccountType and RestrictionType = @TicketType) 
		   exec otn_sp_AR_BillOwner_Matrixcell @GUID, @SalesId, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
	end


--Billing Owner Check by Event/Performance
	If @PreventSale = 0 
	Begin
		IF EXISTS(select *
					from CNF_AccountRestriction
					where Accounttype = @BillAccountType and RestrictionType = @PerformanceType)  
		   exec otn_sp_AR_BillOwner_Performance @GUID, @SalesId, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
	end


--Ticket Owner Check by Ticket
	If @PreventSale = 0 
	Begin
		IF EXISTS(select *
					from CNF_AccountRestriction
					where Accounttype = @TicketAccountType and RestrictionType = @TicketType)  
		   exec otn_sp_AR_TicketOwner_Matrixcell @GUID, @SalesId, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
	end


--Ticket Owner Check by Event/Performance
	If @PreventSale = 0 
	Begin
		IF EXISTS(select *
					from CNF_AccountRestriction
					where Accounttype = @TicketAccountType and RestrictionType = @PerformanceType)  
		   exec otn_sp_AR_TicketOwner_Performance @GUID, @SalesId, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
	end


	delete from data_shopcartitemlimit where  (((@SalesID = 0) and (data_shopcartitemlimit.ShopCartGuid = @GUID)) or (('0' = @GUID) and (data_shopcartitemlimit.Saleid = @SalesID)))

	EXEC(@sql)

	select @PreventSale as PreventSale, 
	       @RejectReasonErrorCode as RejectReasonErrorCode, 
		   @RejectType as RejectType,
	       @RejectRestrictionDescription as RejectRestrictionDescription,
	       @RejectRemainingAmount as RejectRemainingAmount

END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT * FROM sys.columns
          WHERE Name = N'Limit' 
          AND OBJECT_ID = OBJECT_ID(N'cnf_accountrestriction'))
Begin
   update cnf_accountrestriction
      set AccountType = case when ReservationAccountLimit &gt; 0 then 1
                             else 4
			 end,
	   Limit = case when ReservationAccountLimit &gt; 0 then ReservationAccountLimit
                        else TicketAccountLimit
		    end
end</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT * FROM sys.columns
          WHERE Name = N'ReservationAccountQuantity' 
          AND OBJECT_ID = OBJECT_ID(N'data_accountlimit'))
Begin


	update data_accountlimit
	   set ReservationAccountQuantity = case when TicketAccountQuantity &lt;&gt; 0 and ReservationAccountQuantity = 0 then TicketAccountQuantity
											 when ticketaccountquantity &lt;&gt; 0 and ReservationAccountQuantity &lt;&gt; 0 then ReservationAccountQuantity + TicketAccountQuantity
											 else ReservationAccountQuantity
										end

end</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.objects WHERE [name] = N'data_sale_SalesRestriction' AND [type] = 'TR')
BEGIN
      DROP TRIGGER [dbo].[data_sale_SalesRestriction];
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>Create trigger [dbo].[data_sale_SalesRestriction] on [dbo].[DATA_Sale] FOR update
	 as
begin
	SET NOCOUNT ON;
    IF UPDATE(Approved) or Update(StatusCode)
    BEGIN

		Declare @NumberOfRestrictions Int = 0

		select @NumberOfRestrictions = Count(*)
		  from CNF_AccountRestriction
		 Where Enabled = 1

		if @NumberOfRestrictions &gt; 0
		BEGIN
			DECLARE @INS_SaleID int
			DECLARE @status int = 0 
			DECLARE @DR_status int

			DECLARE @RestrictionType int	
			
			DECLARE @CheckforRestraintOnly int = 0

			SELECT @status=i.Approved, @INS_SaleID = i.Saleid 
					FROM inserted i
						JOIN deleted d
								 ON i.SaleID = d.SaleID
								 AND ((d.paid = 0) or (i.paid &lt;&gt; d.Paid))
								 AND i.statuscode = 1

			if @status = 0 
			begin
				SELECT @DR_status = CASE WHEN i.StatusCode = 2 then  1
										 else 0
									 end, 
					   @INS_SaleID = i.Saleid 
						FROM inserted i
							  JOIN deleted d
									  ON i.[SaleID] = d.[SaleID]
										 AND i.[StatusCode] &lt;&gt; d.[StatusCode]
			end


			if @status = 1
			begin
--Reservation Account
				Insert into data_shopcartitemlimit
				select  data_sale.saleid,
				        0 as B2B,
						0 as  Billing,
						ISNULL(data_reservation.accountid, ODR.AccountID) as ReservationAccountID,
						0 TicketAccountID,
						data_saleitem.Matrixcellid,
						data_saleitem.Quantity,
						case when cnf_performance.PerformanceID is not null then cnf_performance.PerformanceID
												 else 9999999
						end ,
						case when cnf_performance.Eventid is not null then cnf_performance.Eventid
												 else  9999999
						end,
						data_sale.saleid,
						data_saleitem.saleitemid,
						case when data_saleitem.Quantity &lt; 0 then ISNULL((select top 1 1
																			from data_transaction
																			where data_transaction.transactiontype in (17, 18, 20, 40, 47)
																				and data_transaction.saleid = data_sale.saleid), 0)
								else 0
							end as UsageCheck

				from data_sale WITH(NOLOCK)
					LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
					INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
					LEFT  JOIN data_saleitem2Performance WITH(NOLOCK)			on data_saleitem2performance.saleitemid = data_saleitem.saleitemid
					LEFT  JOIN cnf_performance WITH(NOLOCK)						on cnf_Performance.performanceid = data_saleitem2performance.performanceid
					left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
					left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

					where data_sale.saleid = @INS_SaleID

--B2B Account
				Insert into data_shopcartitemlimit
				select  data_sale.saleid,
				        ISNULL(data_reservation.B2BAccountID, ODR.B2BAccountID) as B2B,
						0 as  Billing,
						0 as ReservationAccountID,
						0 TicketAccountID,
						data_saleitem.Matrixcellid,
						data_saleitem.Quantity,
						case when cnf_performance.PerformanceID is not null then cnf_performance.PerformanceID
												 else 9999999
						end ,
						case when cnf_performance.Eventid is not null then cnf_performance.Eventid
												 else  9999999
						end,
						data_sale.saleid,
						data_saleitem.saleitemid,
						case when data_saleitem.Quantity &lt; 0 then ISNULL((select top 1 1
																			from data_transaction
																			where data_transaction.transactiontype in (17, 18, 20, 40, 47)
																				and data_transaction.saleid = data_sale.saleid), 0)
								else 0
							end as UsageCheck

				from data_sale WITH(NOLOCK)
					LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
					INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
					LEFT  JOIN data_saleitem2Performance WITH(NOLOCK)			on data_saleitem2performance.saleitemid = data_saleitem.saleitemid
					LEFT  JOIN cnf_performance WITH(NOLOCK)						on cnf_Performance.performanceid = data_saleitem2performance.performanceid
					left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
					left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

					where data_sale.saleid = @INS_SaleID
					  and ISNULL(data_reservation.B2BAccountID, ODR.B2BAccountID) is not null

--Billing Account
				Insert into data_shopcartitemlimit
				select  data_sale.saleid,
				        0 as B2B,
				        ISNULL(data_reservation.BillingAccountId, ODR.BillingAccountId) as BillingAccountId,
						0 as ReservationAccountID,
						0 TicketAccountID,
						data_saleitem.Matrixcellid,
						data_saleitem.Quantity,
						case when cnf_performance.PerformanceID is not null then cnf_performance.PerformanceID
												 else 9999999
						end ,
						case when cnf_performance.Eventid is not null then cnf_performance.Eventid
												 else  9999999
						end,
						data_sale.saleid,
						data_saleitem.saleitemid,
						case when data_saleitem.Quantity &lt; 0 then ISNULL((select top 1 1
																			from data_transaction
																			where data_transaction.transactiontype in (17, 18, 20, 40, 47)
																				and data_transaction.saleid = data_sale.saleid), 0)
								else 0
							end as UsageCheck

				from data_sale WITH(NOLOCK)
					LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
					INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
					LEFT  JOIN data_saleitem2Performance WITH(NOLOCK)			on data_saleitem2performance.saleitemid = data_saleitem.saleitemid
					LEFT  JOIN cnf_performance WITH(NOLOCK)						on cnf_Performance.performanceid = data_saleitem2performance.performanceid
					left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
					left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

					where data_sale.saleid = @INS_SaleID
					  and ISNULL(data_reservation.BillingAccountId, ODR.BillingAccountId) is not null

--Ticket Account
				Insert into data_shopcartitemlimit
				select  data_sale.saleid,
				        0 as B2B,
				        0 as BillingAccountId,
						0 as ReservationAccountID,
						data_ticket.accountid TicketAccountID,
						data_saleitem.Matrixcellid,
						case when data_ticket.ticketid is not null then case when data_saleitem.Quantity &lt; 0 then -1 else 1 end
										else data_saleitem.Quantity
									end Quantity,
						case when cnf_performance.PerformanceID is not null then cnf_performance.PerformanceID
												 else 9999999
						end ,
						case when cnf_performance.Eventid is not null then cnf_performance.Eventid
												 else  9999999
						end,
						data_sale.saleid,
						data_saleitem.saleitemid,
						case when data_saleitem.Quantity &lt; 0 then ISNULL((select top 1 1
																			from data_transaction
																			where data_transaction.transactiontype in (17, 18, 20, 40, 47)
																				and data_transaction.saleid = data_sale.saleid), 0)
								else 0
							end as UsageCheck

					from data_sale WITH(NOLOCK)
						LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
						INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
						LEFT  JOIN data_saleitem2ticket WITH(NOLOCK)				on data_saleitem2ticket.saleitemid = data_saleitem.saleitemid
						LEFT  JOIN data_saleitem2Performance WITH(NOLOCK)			on data_saleitem2performance.saleitemid = data_saleitem.saleitemid
						LEFT  JOIN cnf_performance WITH(NOLOCK)						on cnf_Performance.performanceid = data_saleitem2performance.performanceid
						LEFT  JOIN data_ticket WITH(NOLOCK)							on data_ticket.ticketid = data_saleitem2ticket.ticketid
						left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
						left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

					where data_sale.saleid = @INS_SaleID
					  and data_ticket.accountid is not null

--Reservation Account
				Insert into data_shopcartitemlimit
				select  data_sale.saleid,
				        0 as B2B,
						0 as  Billing,
						ISNULL(data_reservation.accountid, ODR.AccountID) as ReservationAccountID,
						0 TicketAccountID,
						data_saleitem.Matrixcellid,
						data_saleitem.Quantity,
						0,
						0,
						data_sale.saleid,
						data_saleitem.saleitemid,
						case when data_saleitem.Quantity &lt; 0 then ISNULL((select top 1 1
																			from data_transaction
																			where data_transaction.transactiontype in (17, 18, 20, 40, 47)
																				and data_transaction.saleid = data_sale.saleid), 0)
								else 0
							end as UsageCheck

				from data_sale WITH(NOLOCK)
					LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
					INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
					left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
					left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

					where data_sale.saleid = @INS_SaleID

--B2B Account
				Insert into data_shopcartitemlimit
				select  data_sale.saleid,
				        ISNULL(data_reservation.B2BAccountID, ODR.B2BAccountID) as B2B,
						0 as  Billing,
						0 as ReservationAccountID,
						0 TicketAccountID,
						data_saleitem.Matrixcellid,
						data_saleitem.Quantity,
						0,
						0,
						data_sale.saleid,
						data_saleitem.saleitemid,
						case when data_saleitem.Quantity &lt; 0 then ISNULL((select top 1 1
																			from data_transaction
																			where data_transaction.transactiontype in (17, 18, 20, 40, 47)
																				and data_transaction.saleid = data_sale.saleid), 0)
								else 0
							end as UsageCheck

				from data_sale WITH(NOLOCK)
					LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
					INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
					left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
					left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

					where data_sale.saleid = @INS_SaleID
					  and ISNULL(data_reservation.B2BAccountID, ODR.B2BAccountID) is not null

--Billing Account
				Insert into data_shopcartitemlimit
				select  data_sale.saleid,
				        0 as B2B,
				        ISNULL(data_reservation.BillingAccountId, ODR.BillingAccountId) as BillingAccountId,
						0 as ReservationAccountID,
						0 TicketAccountID,
						data_saleitem.Matrixcellid,
						data_saleitem.Quantity,
						0,
						0,
						data_sale.saleid,
						data_saleitem.saleitemid,
						case when data_saleitem.Quantity &lt; 0 then ISNULL((select top 1 1
																			from data_transaction
																			where data_transaction.transactiontype in (17, 18, 20, 40, 47)
																				and data_transaction.saleid = data_sale.saleid), 0)
								else 0
							end as UsageCheck

				from data_sale WITH(NOLOCK)
					LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
					INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
					left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
					left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

					where data_sale.saleid = @INS_SaleID
					  and ISNULL(data_reservation.BillingAccountId, ODR.BillingAccountId) is not null

--Ticket Account
				Insert into data_shopcartitemlimit
				select  data_sale.saleid,
				        0 as B2B,
				        0 as BillingAccountId,
						0 as ReservationAccountID,
						data_ticket.accountid TicketAccountID,
						data_saleitem.Matrixcellid,
						case when data_ticket.ticketid is not null then case when data_saleitem.Quantity &lt; 0 then -1 else 1 end
										else data_saleitem.Quantity
									end Quantity,
						0,
						0,
						data_sale.saleid,
						data_saleitem.saleitemid,
						case when data_saleitem.Quantity &lt; 0 then ISNULL((select top 1 1
																			from data_transaction
																			where data_transaction.transactiontype in (17, 18, 20, 40, 47)
																				and data_transaction.saleid = data_sale.saleid), 0)
								else 0
							end as UsageCheck

					from data_sale WITH(NOLOCK)
						LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
						INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
						LEFT  JOIN data_saleitem2ticket WITH(NOLOCK)				on data_saleitem2ticket.saleitemid = data_saleitem.saleitemid
						LEFT  JOIN data_ticket WITH(NOLOCK)							on data_ticket.ticketid = data_saleitem2ticket.ticketid
						left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
						left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

					where data_sale.saleid = @INS_SaleID
					  and data_ticket.accountid is not null	

			END

--Reservation Deletes
			if @DR_status = 1
			begin
			--Reservation Account
				Insert into data_shopcartitemlimit
				select  data_sale.saleid,
				        0 as B2B,
						0 as  Billing,
						ISNULL(data_reservation.accountid, ODR.AccountID) as ReservationAccountID,
						0 TicketAccountID,
						data_saleitem.Matrixcellid,
						data_saleitem.Quantity,
						case when cnf_performance.PerformanceID is not null then cnf_performance.PerformanceID
												 else 9999999
						end ,
						case when cnf_performance.Eventid is not null then cnf_performance.Eventid
												 else  9999999
						end,
						data_sale.saleid,
						data_saleitem.saleitemid,
						case when data_saleitem.Quantity &lt; 0 then ISNULL((select top 1 1
																			from data_transaction
																			where data_transaction.transactiontype in (17, 18, 20, 40, 47)
																				and data_transaction.saleid = data_sale.saleid), 0)
								else 0
							end as UsageCheck

				from data_sale WITH(NOLOCK)
					LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
					INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
					LEFT  JOIN data_saleitem2Performance WITH(NOLOCK)			on data_saleitem2performance.saleitemid = data_saleitem.saleitemid
					LEFT  JOIN cnf_performance WITH(NOLOCK)						on cnf_Performance.performanceid = data_saleitem2performance.performanceid
					left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
					left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

					where data_sale.saleid = @INS_SaleID
					  and data_saleitem.quantity &lt; 0

--B2B Account
				Insert into data_shopcartitemlimit
				select  data_sale.saleid,
				        ISNULL(data_reservation.B2BAccountID, ODR.B2BAccountID) as B2B,
						0 as  Billing,
						0 as ReservationAccountID,
						0 TicketAccountID,
						data_saleitem.Matrixcellid,
						data_saleitem.Quantity,
						case when cnf_performance.PerformanceID is not null then cnf_performance.PerformanceID
												 else 9999999
						end ,
						case when cnf_performance.Eventid is not null then cnf_performance.Eventid
												 else  9999999
						end,
						data_sale.saleid,
						data_saleitem.saleitemid,
						case when data_saleitem.Quantity &lt; 0 then ISNULL((select top 1 1
																			from data_transaction
																			where data_transaction.transactiontype in (17, 18, 20, 40, 47)
																				and data_transaction.saleid = data_sale.saleid), 0)
								else 0
							end as UsageCheck

				from data_sale WITH(NOLOCK)
					LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
					INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
					LEFT  JOIN data_saleitem2Performance WITH(NOLOCK)			on data_saleitem2performance.saleitemid = data_saleitem.saleitemid
					LEFT  JOIN cnf_performance WITH(NOLOCK)						on cnf_Performance.performanceid = data_saleitem2performance.performanceid
					left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
					left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

					where data_sale.saleid = @INS_SaleID
					  and ISNULL(data_reservation.B2BAccountID, ODR.B2BAccountID) is not null
					  and data_saleitem.quantity &lt; 0

--Billing Account
				Insert into data_shopcartitemlimit
				select  data_sale.saleid,
				        0 as B2B,
				        ISNULL(data_reservation.BillingAccountId, ODR.BillingAccountId) as BillingAccountId,
						0 as ReservationAccountID,
						0 TicketAccountID,
						data_saleitem.Matrixcellid,
						data_saleitem.Quantity,
						case when cnf_performance.PerformanceID is not null then cnf_performance.PerformanceID
												 else 9999999
						end ,
						case when cnf_performance.Eventid is not null then cnf_performance.Eventid
												 else  9999999
						end,
						data_sale.saleid,
						data_saleitem.saleitemid,
						case when data_saleitem.Quantity &lt; 0 then ISNULL((select top 1 1
																			from data_transaction
																			where data_transaction.transactiontype in (17, 18, 20, 40, 47)
																				and data_transaction.saleid = data_sale.saleid), 0)
								else 0
							end as UsageCheck

				from data_sale WITH(NOLOCK)
					LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
					INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
					LEFT  JOIN data_saleitem2Performance WITH(NOLOCK)			on data_saleitem2performance.saleitemid = data_saleitem.saleitemid
					LEFT  JOIN cnf_performance WITH(NOLOCK)						on cnf_Performance.performanceid = data_saleitem2performance.performanceid
					left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
					left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

					where data_sale.saleid = @INS_SaleID
					  and ISNULL(data_reservation.BillingAccountId, ODR.BillingAccountId) is not null
					  and data_saleitem.quantity &lt; 0

--Ticket Account
				Insert into data_shopcartitemlimit
				select  data_sale.saleid,
				        0 as B2B,
				        0 as BillingAccountId,
						0 as ReservationAccountID,
						data_ticket.accountid TicketAccountID,
						data_saleitem.Matrixcellid,
						case when data_ticket.ticketid is not null then case when data_saleitem.Quantity &lt; 0 then -1 else 1 end
										else data_saleitem.Quantity
									end Quantity,
						case when cnf_performance.PerformanceID is not null then cnf_performance.PerformanceID
												 else 9999999
						end ,
						case when cnf_performance.Eventid is not null then cnf_performance.Eventid
												 else  9999999
						end,
						data_sale.saleid,
						data_saleitem.saleitemid,
						case when data_saleitem.Quantity &lt; 0 then ISNULL((select top 1 1
																			from data_transaction
																			where data_transaction.transactiontype in (17, 18, 20, 40, 47)
																				and data_transaction.saleid = data_sale.saleid), 0)
								else 0
							end as UsageCheck

					from data_sale WITH(NOLOCK)
						LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
						INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
						LEFT  JOIN data_saleitem2ticket WITH(NOLOCK)				on data_saleitem2ticket.saleitemid = data_saleitem.saleitemid
						LEFT  JOIN data_saleitem2Performance WITH(NOLOCK)			on data_saleitem2performance.saleitemid = data_saleitem.saleitemid
						LEFT  JOIN cnf_performance WITH(NOLOCK)						on cnf_Performance.performanceid = data_saleitem2performance.performanceid
						LEFT  JOIN data_ticket WITH(NOLOCK)							on data_ticket.ticketid = data_saleitem2ticket.ticketid
						left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
						left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

					where data_sale.saleid = @INS_SaleID
					  and data_ticket.accountid is not null
					  and data_saleitem.quantity &lt; 0

--Reservation Account
				Insert into data_shopcartitemlimit
				select  data_sale.saleid,
				        0 as B2B,
						0 as  Billing,
						ISNULL(data_reservation.accountid, ODR.AccountID) as ReservationAccountID,
						0 TicketAccountID,
						data_saleitem.Matrixcellid,
						data_saleitem.Quantity,
						0,
						0,
						data_sale.saleid,
						data_saleitem.saleitemid,
						case when data_saleitem.Quantity &lt; 0 then ISNULL((select top 1 1
																			from data_transaction
																			where data_transaction.transactiontype in (17, 18, 20, 40, 47)
																				and data_transaction.saleid = data_sale.saleid), 0)
								else 0
							end as UsageCheck

				from data_sale WITH(NOLOCK)
					LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
					INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
					left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
					left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

					where data_sale.saleid = @INS_SaleID
					  and data_saleitem.quantity &lt; 0

--B2B Account
				Insert into data_shopcartitemlimit
				select  data_sale.saleid,
				        ISNULL(data_reservation.B2BAccountID, ODR.B2BAccountID) as B2B,
						0 as  Billing,
						0 as ReservationAccountID,
						0 TicketAccountID,
						data_saleitem.Matrixcellid,
						data_saleitem.Quantity,
						0,
						0,
						data_sale.saleid,
						data_saleitem.saleitemid,
						case when data_saleitem.Quantity &lt; 0 then ISNULL((select top 1 1
																			from data_transaction
																			where data_transaction.transactiontype in (17, 18, 20, 40, 47)
																				and data_transaction.saleid = data_sale.saleid), 0)
								else 0
							end as UsageCheck

				from data_sale WITH(NOLOCK)
					LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
					INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
					left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
					left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

					where data_sale.saleid = @INS_SaleID
					  and ISNULL(data_reservation.B2BAccountID, ODR.B2BAccountID) is not null
					  and data_saleitem.quantity &lt; 0

--Billing Account
				Insert into data_shopcartitemlimit
				select  data_sale.saleid,
				        0 as B2B,
				        ISNULL(data_reservation.BillingAccountId, ODR.BillingAccountId) as BillingAccountId,
						0 as ReservationAccountID,
						0 TicketAccountID,
						data_saleitem.Matrixcellid,
						data_saleitem.Quantity,
						0,
						0,
						data_sale.saleid,
						data_saleitem.saleitemid,
						case when data_saleitem.Quantity &lt; 0 then ISNULL((select top 1 1
																			from data_transaction
																			where data_transaction.transactiontype in (17, 18, 20, 40, 47)
																				and data_transaction.saleid = data_sale.saleid), 0)
								else 0
							end as UsageCheck

				from data_sale WITH(NOLOCK)
					LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
					INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
					left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
					left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

					where data_sale.saleid = @INS_SaleID
					  and ISNULL(data_reservation.BillingAccountId, ODR.BillingAccountId) is not null
					  and data_saleitem.quantity &lt; 0

--Ticket Account
				Insert into data_shopcartitemlimit
				select  data_sale.saleid,
				        0 as B2B,
				        0 as BillingAccountId,
						0 as ReservationAccountID,
						data_ticket.accountid TicketAccountID,
						data_saleitem.Matrixcellid,
						case when data_ticket.ticketid is not null then case when data_saleitem.Quantity &lt; 0 then -1 else 1 end
										else data_saleitem.Quantity
									end Quantity,
						0,
						0,
						data_sale.saleid,
						data_saleitem.saleitemid,
						case when data_saleitem.Quantity &lt; 0 then ISNULL((select top 1 1
																			from data_transaction
																			where data_transaction.transactiontype in (17, 18, 20, 40, 47)
																				and data_transaction.saleid = data_sale.saleid), 0)
								else 0
							end as UsageCheck

					from data_sale WITH(NOLOCK)
						LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
						INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
						LEFT  JOIN data_saleitem2ticket WITH(NOLOCK)				on data_saleitem2ticket.saleitemid = data_saleitem.saleitemid
						LEFT  JOIN data_ticket WITH(NOLOCK)							on data_ticket.ticketid = data_saleitem2ticket.ticketid
						left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
						left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

					where data_sale.saleid = @INS_SaleID
					  and data_ticket.accountid is not null	
					  and data_saleitem.quantity &lt; 0
			end

			delete from data_shopcartitemlimit where PerformanceID = 9999999
			delete from data_shopcartitemlimit where Quantity = 0
			--select * 		from data_shopcartitemlimit
			
			Exec otn_sp_CheckAccountRestrictions 0, @INS_SaleID


		end
	end
end</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT> ALTER TABLE [dbo].[DATA_Sale] ENABLE TRIGGER [data_sale_SalesRestriction]</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT * FROM sys.columns
          WHERE Name = N'Restrictiontype' 
          AND OBJECT_ID = OBJECT_ID(N'data_accountlimit'))

ALTER TABLE data_accountlimit DROP column Restrictiontype</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>3217</SQLVERSION><RMTRACKLINK>2603</RMTRACKLINK><REASON>Substitute the Temp Tables management in Account Restriction Process with a real table</REASON><TABLENAMES>DATA_ShopCartItemLimit=ShopCartItemLimitID</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND TABLE_NAME = 'DATA_ShopCartItemLimit')
BEGIN
Create table DATA_ShopCartItemLimit
(
	[ShopCartItemLimitID]    Integer IDENTITY(1,1) NOT NULL,
	[ShopCartGuid] [varchar](38) NULL,
	[B2B_Owner] [int] NULL,
	[Billing_Owner] [int] NULL,
	[Reservation_Owner] [int] NULL,
	[Ticket_Owner] [int] NULL,
	[MatrixCellId] [int] NULL,
	[Quantity] [int] NULL,
	[PerformanceID] [int] NULL,
	[EventID] [int] NULL,
	[SaleID] [int] NULL,
	[SaleItemID] [int] NULL,
	[CheckforRestrictionOnly] [int] NULL

Primary Key ([ShopCartItemLimitID])
) 
END
</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>3216</SQLVERSION><RMTRACKLINK>IDBOS-2552</RMTRACKLINK><REASON></REASON><TABLENAMES>CNF_AccountRestriction=AccountRestrictionId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
          WHERE Name = N'Limit' 
          AND OBJECT_ID = OBJECT_ID(N'CNF_AccountRestriction'))
BEGIN
  ALTER TABLE CNF_AccountRestriction
  ADD Limit [int]
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
          WHERE Name = N'AccountType' 
          AND OBJECT_ID = OBJECT_ID(N'CNF_AccountRestriction'))
BEGIN
  ALTER TABLE CNF_AccountRestriction
  ADD AccountType [smallint]
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
          WHERE Name = N'Code' 
          AND OBJECT_ID = OBJECT_ID(N'CNF_AccountRestriction'))
BEGIN
  ALTER TABLE CNF_AccountRestriction
  ADD Code [nvarchar](10)
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>3215</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_AR_ReservationOwner_Matrixcell]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_AR_ReservationOwner_Matrixcell</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>CREATE PROCEDURE [otn_sp_AR_ReservationOwner_Matrixcell]  (
                                                      @Restriction_Check         Restriction_Table READONLY,
													  @PreventSale int OUTPUT,
													  @RejectReasonErrorCode int OUTPUT,
													  @RejectType int OUTPUT,
													  @RejectRestrictionDescription varchar(100) OUTPUT,
													  @RejectRemainingAmount int OUTPUT
                                                    ) 
AS    
BEGIN

	DECLARE @SalesDate datetime = getdate();
	DECLARE @RestrictionType int
	DECLARE @Reservation_Owner int
	DECLARE @OldAccountRestrictionID int = 99999
	DECLARE @ReservationAccountLimit int
	DECLARE @AccountRestrictionID int
	DECLARE @Ticket_Owner int
	DECLARE @MatrixCellID int
	DECLARE @Quantity int
	DECLARE @FullQuantity int
	DECLARE @PerformanceID int
	DECLARE @EventID int
	DECLARE @SaleID int
	DECLARE @SaleitemID int
	DECLARE @CheckforRestrictionOnly int
	DECLARE @TicketAccountLimit int
	DECLARE @OLD_Resevation_Owner int
	DECLARE @ReservationorTicket int = 0
	DECLARE @CountofMatrixCells int = 0
	DECLARE @Prevent int = 0

	
--Reservation Owner	
	SET @RestrictionType = 1
	set @CountofMatrixCells = 0
	SET @OLD_Resevation_Owner = 99999

	DECLARE Check_Cursor CURSOR LOCAL FOR
		select  Reservation_Owner,
		        Ticket_Owner,
				Res_Table.MatrixCellID,
				sum(Quantity) as Quantity,
				SaleID,
				SaleitemID,
				CheckforRestrictionOnly,
				cnf_AccountRestriction.AccountRestrictionID,
				cnf_AccountRestriction.ReservationAccountLimit,
				cnf_AccountRestriction.TicketAccountLimit

		  from @Restriction_Check Res_Table
				INNER JOIN cnf_AccountRestriction2MatrixCell WITH(NOLOCK)				ON cnf_AccountRestriction2MatrixCell.MatrixCellID = Res_Table.MatrixCellID
				LEFT JOIN cnf_AccountRestriction2Account WITH(NOLOCK)					ON (cnf_AccountRestriction2Account.AccountID = Res_Table.Reservation_Owner)																							
					                                                                       and cnf_accountrestriction2Account.AccountRestrictionID = CNF_AccountRestriction2MatrixCell.AccountRestrictionId
																										
			    LEFT JOIN cnf_AccountRestriction2DMGCategory WITH(NOLOCK)				ON (cnf_AccountRestriction2DMGCategory.DMGCategoryID = (select DMGCategoryID from data_account WITH(NOLOCK) where data_account.accountid = Res_Table.Reservation_Owner))																							
					                                                                       and cnf_AccountRestriction2DMGCategory.AccountRestrictionID = CNF_AccountRestriction2MatrixCell.AccountRestrictionId				
				
				INNER JOIN cnf_AccountRestriction WITH(NOLOCK)							ON cnf_AccountRestriction.AccountRestrictionId = cnf_AccountRestriction2MatrixCell.AccountRestrictionId

	     where cnf_AccountRestriction.Enabled = 1
		   and Convert(date, GetDAte(), 120) between Convert(date, StartDateTime, 120) and Convert(date, EndDateTime, 120)
		   and CNF_AccountRestriction.RestrictionType = @RestrictionType
		   and Res_Table.Reservation_Owner is not null
		   and ReservationAccountLimit is not null
		   and Reservation_Owner &lt;&gt; 0
		   and ((cnf_AccountRestriction2Account.accountid is not null) or (cnf_AccountRestriction2DMGCategory.dmgcategoryid is not null))
		   and ISNULL(Res_Table.PerformanceID, 0) = 0

			 GROUP BY Reservation_Owner,
							 Ticket_Owner,
							 Res_Table.MatrixCellID,
							 SaleID,
							 SaleitemID,
							 CheckforRestrictionOnly,
							 cnf_AccountRestriction.AccountRestrictionID,
							 cnf_AccountRestriction.ReservationAccountLimit,
							 cnf_AccountRestriction.TicketAccountLimit
		 order by cnf_AccountRestriction.AccountRestrictionID

	OPEN Check_Cursor

	FETCH NEXT FROM Check_Cursor INTO
						@Reservation_Owner,
						@Ticket_Owner,
						@MatrixCellID,
						@Quantity,
						@SaleID,
						@SaleitemID,
						@CheckforRestrictionOnly,
	                    @AccountRestrictionID,
						@ReservationAccountLimit,
						@TicketAccountLimit


	WHILE @@FETCH_STATUS = 0
	BEGIN
		IF @OldAccountRestrictionID &lt;&gt; @AccountRestrictionID and @Reservation_Owner &lt;&gt; @OLD_Resevation_Owner and (@PreventSale = 0)
		BEGIN 
			If @ReservationAccountLimit &gt; 0 
				set @ReservationorTicket = 1

			SET @Prevent = 0;

			if @ReservationorTicket = 1 
			BEGIN
				select @FullQuantity = sum(Quantity),  
				       @CountofMatrixCells = Count(*)
					from @Restriction_Check
					where MatrixCellID in (select MatrixcellId 
											from cnf_AccountRestriction2MatrixCell WITH(NOLOCK)									
											where cnf_AccountRestriction2MatrixCell.AccountRestrictionId = @AccountRestrictionID)
					and Reservation_Owner = @Reservation_Owner
					and ISNULL(PerformanceID, 0) = 0

				if @FullQuantity &gt; 0
				Begin			  
					if @CountofMatrixCells = 1 						
						Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @ReservationorTicket, @RestrictionType, @Reservation_Owner, @Ticket_Owner, 
															null, null, @SaleID, @SaleitemID, @CheckforRestrictionOnly, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
					else
					begin
						Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @ReservationorTicket, @RestrictionType, @Reservation_Owner, @Ticket_Owner, 
															null, null, @SaleID, @SaleitemID, 1, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
						set @Prevent = @PreventSale

						if @Prevent = 0 and @CheckforRestrictionOnly = 0 
						begin
						    DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

							INSERT INTO [dbo].[DATA_AccountLimit]
											([AccountRestrictionId]
											,[AccountId]
											,[PerformanceId]
											,[SaleId]
											,[SaleItemId]
											,[SaleDate]
											,[ReservationAccountQuantity]
											,[TicketAccountQuantity])
										VALUES
											(@AccountRestrictionID
											,@Reservation_Owner
											,@PerformanceID
											,@SaleID
											,@SaleItemID
											,@SalesDate
											,@FullQuantity
											,0)						 
						end
					end
				end
				else
				begin
						if @Prevent = 0 and @CheckforRestrictionOnly = 0 
						begin

							INSERT INTO [dbo].[DATA_AccountLimit]
												([AccountRestrictionId]
												,[AccountId]
												,[PerformanceId]
												,[SaleId]
												,[SaleItemId]
												,[SaleDate]
												,[ReservationAccountQuantity]
												,[TicketAccountQuantity])
											VALUES
												(@AccountRestrictionID
												,@Reservation_Owner
												,@PerformanceID
												,@SaleID
												,@SaleItemID
												,@SalesDate
												,@Quantity
												,0)	
						end
				end
			END	
		END
		ELSE
		BEGIN
			IF @OldAccountRestrictionID = @AccountRestrictionID and @Reservation_Owner = @OLD_Resevation_Owner and @Quantity &lt; 0
			begin
								INSERT INTO [dbo].[DATA_AccountLimit]
												([AccountRestrictionId]
												,[AccountId]
												,[PerformanceId]
												,[SaleId]
												,[SaleItemId]
												,[SaleDate]
												,[ReservationAccountQuantity]
												,[TicketAccountQuantity])
											VALUES
												(@AccountRestrictionID
												,@Reservation_Owner
												,@PerformanceID
												,@SaleID
												,@SaleItemID
												,@SalesDate
												,@Quantity
												,0)	



			end 
			IF @OldAccountRestrictionID &lt;&gt; @AccountRestrictionID and @Reservation_Owner &lt;&gt; @OLD_Resevation_Owner
			begin
				if @Prevent = 0 and @CheckforRestrictionOnly = 0 
				begin
				    DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

					INSERT INTO [dbo].[DATA_AccountLimit]
									([AccountRestrictionId]
									,[AccountId]
									,[PerformanceId]
									,[SaleId]
									,[SaleItemId]
									,[SaleDate]
									,[ReservationAccountQuantity]
									,[TicketAccountQuantity])
								VALUES
									(@AccountRestrictionID
									,@Reservation_Owner
									,@PerformanceID
									,@SaleID
									,@SaleItemID
									,@SalesDate
									,@Quantity
									,0)						 
				end
			end
		END

		Set @OldAccountRestrictionID = @AccountRestrictionID
		SET @OLD_Resevation_Owner = @Reservation_Owner

		FETCH NEXT FROM Check_Cursor INTO
						@Reservation_Owner,
						@Ticket_Owner,
						@MatrixCellID,
						@Quantity,
						@SaleID,
						@SaleitemID,
						@CheckforRestrictionOnly,
	                    @AccountRestrictionID,
						@ReservationAccountLimit,
						@TicketAccountLimit
	END

	CLOSE Check_Cursor;
	DEALLOCATE Check_Cursor;


RETURN;

END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_AR_ReservationOwner_Performance]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_AR_ReservationOwner_Performance</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>CREATE PROCEDURE [otn_sp_AR_ReservationOwner_Performance]  (
                                                      @Restriction_Check         Restriction_Table READONLY,
													  @PreventSale int OUTPUT,
													  @RejectReasonErrorCode int OUTPUT,
													  @RejectType int OUTPUT,
													  @RejectRestrictionDescription varchar(100) OUTPUT,
													  @RejectRemainingAmount int OUTPUT
                                                    ) 
AS    
BEGIN

	DECLARE @SalesDate datetime = getdate();
	DECLARE @RestrictionType int
	DECLARE @Reservation_Owner int
	DECLARE @OldAccountRestrictionID int = 99999
	DECLARE @ReservationAccountLimit int
	DECLARE @AccountRestrictionID int
	DECLARE @Ticket_Owner int
	DECLARE @MatrixCellID int
	DECLARE @Quantity int
	DECLARE @FullQuantity int
	DECLARE @PerformanceID int
	DECLARE @EventID int
	DECLARE @SaleID int
	DECLARE @SaleitemID int
	DECLARE @CheckforRestrictionOnly int
	DECLARE @TicketAccountLimit int
	DECLARE @OLD_Resevation_Owner int
	DECLARE @ReservationorTicket int = 0
	DECLARE @CountofMatrixCells int = 0
	DECLARE @Prevent int = 0
	DECLARE @Old_PerformanceID int = 0
	DECLARE @Old_EventID int = 0

	
--Performance Reservation Owner Check
	SET @RestrictionType = 2
	Set @OldAccountRestrictionID = 99999
	DECLARE Check_Cursor CURSOR LOCAL FOR
		select   Reservation_Owner,
							Ticket_Owner,
							Res_Table.MatrixCellID,
							SUM(Quantity) as Quantity,
							SaleID,
							SaleitemID,
							CheckforRestrictionOnly,
							cnf_AccountRestriction.AccountRestrictionID,
							cnf_AccountRestriction.ReservationAccountLimit,
							cnf_AccountRestriction.TicketAccountLimit,
							Res_Table.PerformanceID,
							RES_Table.Eventid

			from @Restriction_Check Res_Table
				INNER JOIN CNF_AccountRestriction2Performance							ON CNF_AccountRestriction2Performance.PerformanceID = Res_Table.PerformanceID

				LEFT JOIN cnf_AccountRestriction2Account WITH(NOLOCK)					ON (cnf_AccountRestriction2Account.AccountID = Res_Table.Reservation_Owner)																							
					                     													and cnf_AccountRestriction2Account.AccountRestrictionId = CNF_AccountRestriction2Performance.AccountRestrictionId										
			        
				LEFT JOIN cnf_AccountRestriction2DMGCategory WITH(NOLOCK)				ON (cnf_AccountRestriction2DMGCategory.DMGCategoryID = (select DMGCategoryID from data_account WITH(NOLOCK) where data_account.accountid = Res_Table.Reservation_Owner))																							
					                                                                 		and cnf_AccountRestriction2DMGCategory.AccountRestrictionId = CNF_AccountRestriction2Performance.AccountRestrictionId
					
				INNER JOIN cnf_AccountRestriction WITH(NOLOCK)							ON cnf_AccountRestriction.AccountRestrictionId = CNF_AccountRestriction2Performance.AccountRestrictionId


			where cnf_AccountRestriction.Enabled = 1
				and Convert(date, GetDAte(), 120) between Convert(date, StartDateTime, 120) and Convert(date, EndDateTime, 120)
				and CNF_AccountRestriction.RestrictionType = @RestrictionType
				and Res_Table.Reservation_Owner is not null
				and ReservationAccountLimit is not null
				and Reservation_Owner &lt;&gt; 0
				and ((cnf_AccountRestriction2Account.accountid is not null) or (cnf_AccountRestriction2DMGCategory.dmgcategoryid is not null))

			GROUP BY Reservation_Owner,
							Ticket_Owner,
							Res_Table.MatrixCellID,
							SaleID,
							SaleitemID,
							CheckforRestrictionOnly,
							cnf_AccountRestriction.AccountRestrictionID,
							cnf_AccountRestriction.ReservationAccountLimit,
							cnf_AccountRestriction.TicketAccountLimit,
							Res_Table.PerformanceID,
							RES_Table.Eventid
	OPEN Check_Cursor

	FETCH NEXT FROM Check_Cursor INTO
						@Reservation_Owner,
						@Ticket_Owner,
						@MatrixCellID,
						@Quantity,
						@SaleID,
						@SaleitemID,
						@CheckforRestrictionOnly,
						@AccountRestrictionID,
						@ReservationAccountLimit,
						@TicketAccountLimit,
						@PerformanceID,
						@EventID


	WHILE @@FETCH_STATUS = 0
	BEGIN
		IF @OldAccountRestrictionID &lt;&gt; @AccountRestrictionID and (@PreventSale = 0) or ((@OldAccountRestrictionID = @AccountRestrictionID) and (@PreventSale = 0) and (@Old_PerformanceID &lt;&gt; @PerformanceID))
		BEGIN 
			If @ReservationAccountLimit &gt; 0 
				set @ReservationorTicket = 1

			SET @Prevent = 0;

			IF @ReservationorTicket = 1
			BEGIN
				select @FullQuantity = sum(Quantity),  @CountofMatrixCells = 1
					from @Restriction_Check
					where PerformanceID = @PerformanceID 	
						and Reservation_Owner = @Reservation_Owner

				if @FullQuantity &gt; 0
				Begin				
					if @CountofMatrixCells = 1 						 																
						Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @ReservationorTicket, @RestrictionType, @Reservation_Owner, @Ticket_Owner, 
															@PerformanceID, @EventID, @SaleID, @SaleitemID, @CheckforRestrictionOnly, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
					else
					begin
						Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @ReservationorTicket, @RestrictionType, @Reservation_Owner, @Ticket_Owner, 
															@PerformanceID, @EventID, @SaleID, @SaleitemID, 1, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
						set @Prevent = @PreventSale

						if @Prevent = 0 and @CheckforRestrictionOnly = 0 
						begin
							DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

							INSERT INTO [dbo].[DATA_AccountLimit]
											([AccountRestrictionId]
											,[AccountId]
											,[PerformanceId]
											,[SaleId]
											,[SaleItemId]
											,[SaleDate]
											,[ReservationAccountQuantity]
											,[TicketAccountQuantity])
										VALUES
											(@AccountRestrictionID
											,@Reservation_Owner
											,@PerformanceID
											,@SaleID
											,@SaleItemID
											,@SalesDate
											,@FullQuantity
											,0)							 
						end
					end
				end
				else
				begin
						if @Prevent = 0 and @CheckforRestrictionOnly = 0 
						begin

							INSERT INTO [dbo].[DATA_AccountLimit]
											([AccountRestrictionId]
											,[AccountId]
											,[PerformanceId]
											,[SaleId]
											,[SaleItemId]
											,[SaleDate]
											,[ReservationAccountQuantity]
											,[TicketAccountQuantity])
										VALUES
											(@AccountRestrictionID
											,@Reservation_Owner
											,@PerformanceID
											,@SaleID
											,@SaleItemID
											,@SalesDate
											,@Quantity
											,0)	
						end
				end
			END
		END
		ELSE
		BEGIN
			IF @OldAccountRestrictionID = @AccountRestrictionID and @Reservation_Owner = @OLD_Resevation_Owner and @Quantity &lt; 0
			begin
								INSERT INTO [dbo].[DATA_AccountLimit]
												([AccountRestrictionId]
												,[AccountId]
												,[PerformanceId]
												,[SaleId]
												,[SaleItemId]
												,[SaleDate]
												,[ReservationAccountQuantity]
												,[TicketAccountQuantity])
											VALUES
												(@AccountRestrictionID
												,@Reservation_Owner
												,@PerformanceID
												,@SaleID
												,@SaleItemID
												,@SalesDate
												,@Quantity
												,0)	



			end 
			IF @OldAccountRestrictionID &lt;&gt; @AccountRestrictionID and @Reservation_Owner &lt;&gt; @OLD_Resevation_Owner
			begin
				if @Prevent = 0 and @CheckforRestrictionOnly = 0 
				begin
					DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

					INSERT INTO [dbo].[DATA_AccountLimit]
									([AccountRestrictionId]
									,[AccountId]
									,[PerformanceId]
									,[SaleId]
									,[SaleItemId]
									,[SaleDate]
									,[ReservationAccountQuantity]
									,[TicketAccountQuantity])
								VALUES
									(@AccountRestrictionID
									,@Reservation_Owner
									,@PerformanceID
									,@SaleID
									,@SaleItemID
									,@SalesDate
									,@Quantity
									,0)						 
				end
			end
		END

		Set @OldAccountRestrictionID = @AccountRestrictionID
		SET @OLD_Resevation_Owner = @Reservation_Owner
		SET @Old_PerformanceID = @PerformanceID

		FETCH NEXT FROM Check_Cursor INTO
						@Reservation_Owner,
						@Ticket_Owner,
						@MatrixCellID,
						@Quantity,
						@SaleID,
						@SaleitemID,
						@CheckforRestrictionOnly,
						@AccountRestrictionID,
						@ReservationAccountLimit,
						@TicketAccountLimit,
						@PerformanceID,
						@EventID
	END

	CLOSE Check_Cursor;
	DEALLOCATE Check_Cursor;


--Event Reservation Owner Check
	IF @PreventSale = 0
	BEGIN
		SET @RestrictionType = 2
		Set @OldAccountRestrictionID = 99999
		DECLARE Check_Cursor CURSOR LOCAL FOR
			select   Reservation_Owner,
								Ticket_Owner,
								Res_Table.MatrixCellID,
								SUM(Quantity) as Quantity,
								SaleID,
								SaleitemID,
								CheckforRestrictionOnly,
								cnf_AccountRestriction.AccountRestrictionID,
								cnf_AccountRestriction.ReservationAccountLimit,
								cnf_AccountRestriction.TicketAccountLimit,
								Res_Table.PerformanceID,
								RES_Table.Eventid

				from @Restriction_Check Res_Table
					INNER JOIN CNF_AccountRestriction2Event WITH(NOLOCK)					ON CNF_AccountRestriction2Event.EventID = Res_Table.EventID

					LEFT JOIN cnf_AccountRestriction2Account WITH(NOLOCK)					ON (cnf_AccountRestriction2Account.AccountID = Res_Table.Reservation_Owner)																							
					                     														and CNF_AccountRestriction2Event.AccountRestrictionId = cnf_AccountRestriction2Account.AccountRestrictionId	
																								
					LEFT JOIN cnf_AccountRestriction2DMGCategory WITH(NOLOCK)				ON (cnf_AccountRestriction2DMGCategory.DMGCategoryID = (select DMGCategoryID from data_account WITH(NOLOCK) where data_account.accountid = Res_Table.Reservation_Owner))																							
					                         													and CNF_AccountRestriction2Event.AccountRestrictionId = cnf_AccountRestriction2DMGCategory.AccountRestrictionId	

					INNER JOIN cnf_AccountRestriction WITH(NOLOCK)							ON cnf_AccountRestriction.AccountRestrictionId = CNF_AccountRestriction2Event.AccountRestrictionId

				where cnf_AccountRestriction.Enabled = 1
				and Convert(date, GetDAte(), 120) between Convert(date, StartDateTime, 120) and Convert(date, EndDateTime, 120)
				and CNF_AccountRestriction.RestrictionType = @RestrictionType
				and Res_Table.Reservation_Owner is not null
				and ReservationAccountLimit is not null
				and Res_Table.Reservation_Owner &lt;&gt; 0
				and ((cnf_AccountRestriction2Account.accountid is not null) or (cnf_AccountRestriction2DMGCategory.dmgcategoryid is not null))

				GROUP BY Reservation_Owner,
								Ticket_Owner,
								Res_Table.MatrixCellID,
								SaleID,
								SaleitemID,
								CheckforRestrictionOnly,
								cnf_AccountRestriction.AccountRestrictionID,
								cnf_AccountRestriction.ReservationAccountLimit,
								cnf_AccountRestriction.TicketAccountLimit,
								Res_Table.PerformanceID,
								RES_Table.Eventid

		OPEN Check_Cursor

		FETCH NEXT FROM Check_Cursor INTO
							@Reservation_Owner,
							@Ticket_Owner,
							@MatrixCellID,
							@Quantity,
							@SaleID,
							@SaleitemID,
							@CheckforRestrictionOnly,
							@AccountRestrictionID,
							@ReservationAccountLimit,
							@TicketAccountLimit,
							@PerformanceID,
							@EventID


		WHILE @@FETCH_STATUS = 0
		BEGIN
			IF @OldAccountRestrictionID &lt;&gt; @AccountRestrictionID and (@PreventSale = 0) 
					or ((@OldAccountRestrictionID = @AccountRestrictionID) and (@PreventSale = 0) and (@OLD_PerformanceID &lt;&gt; @PerformanceID))
			BEGIN 
				If @ReservationAccountLimit &gt; 0 
					set @ReservationorTicket = 1

				SET @Prevent = 0;

				IF @ReservationorTicket = 1
				BEGIN
					select @FullQuantity = sum(Quantity),  @CountofMatrixCells = 1 
						from @Restriction_Check
						where PerformanceID = @PerformanceID	
							and Reservation_Owner = @Reservation_Owner
				
					if @FullQuantity &gt; 0
					Begin
						if @CountofMatrixCells = 1 
						
							Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @ReservationorTicket, @RestrictionType, @Reservation_Owner, @Ticket_Owner, 
																@PerformanceID, @EventID, @SaleID, @SaleitemID, @CheckforRestrictionOnly, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
						else
						begin
							Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @ReservationorTicket, @RestrictionType, @Reservation_Owner, @Ticket_Owner, 
																@PerformanceID, @EventID, @SaleID, @SaleitemID, 1, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
							set @Prevent = @PreventSale

							if @Prevent = 0 and @CheckforRestrictionOnly = 0 
							begin
								DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

								INSERT INTO [dbo].[DATA_AccountLimit]
												([AccountRestrictionId]
												,[AccountId]
												,[PerformanceId]
												,[SaleId]
												,[SaleItemId]
												,[SaleDate]
												,[ReservationAccountQuantity]
												,[TicketAccountQuantity])
											VALUES
												(@AccountRestrictionID
												,@Reservation_Owner
												,@PerformanceID
												,@SaleID
												,@SaleItemID
												,@SalesDate
												,@FullQuantity
												,0)							 
							end
						end
					end
					else
					begin
							if @Prevent = 0 and @CheckforRestrictionOnly = 0 
							begin
								INSERT INTO [dbo].[DATA_AccountLimit]
												([AccountRestrictionId]
												,[AccountId]
												,[PerformanceId]
												,[SaleId]
												,[SaleItemId]
												,[SaleDate]
												,[ReservationAccountQuantity]
												,[TicketAccountQuantity])
											VALUES
												(@AccountRestrictionID
												,@Reservation_Owner
												,@PerformanceID
												,@SaleID
												,@SaleItemID
												,@SalesDate
												,@Quantity
												,0)	
							end
					end
				END
			END	
			ELSE
			BEGIN
				IF @OldAccountRestrictionID = @AccountRestrictionID and @Reservation_Owner = @OLD_Resevation_Owner and @Quantity &lt; 0
				begin
									INSERT INTO [dbo].[DATA_AccountLimit]
													([AccountRestrictionId]
													,[AccountId]
													,[PerformanceId]
													,[SaleId]
													,[SaleItemId]
													,[SaleDate]
													,[ReservationAccountQuantity]
													,[TicketAccountQuantity])
												VALUES
													(@AccountRestrictionID
													,@Reservation_Owner
													,@PerformanceID
													,@SaleID
													,@SaleItemID
													,@SalesDate
													,@Quantity
													,0)	

				end 
				IF @OldAccountRestrictionID &lt;&gt; @AccountRestrictionID and @Reservation_Owner &lt;&gt; @OLD_Resevation_Owner
				begin
					if @Prevent = 0 and @CheckforRestrictionOnly = 0 
					begin
								DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

								INSERT INTO [dbo].[DATA_AccountLimit]
												([AccountRestrictionId]
												,[AccountId]
												,[PerformanceId]
												,[SaleId]
												,[SaleItemId]
												,[SaleDate]
												,[ReservationAccountQuantity]
												,[TicketAccountQuantity])
											VALUES
												(@AccountRestrictionID
												,@Ticket_Owner
												,@PerformanceID
												,@SaleID
												,@SaleItemID
												,@SalesDate
												,0
												,@Quantity)						 
					end
				end
			END			

			Set @OldAccountRestrictionID = @AccountRestrictionID
			SET @OLD_Resevation_Owner = @Reservation_Owner
			SET @Old_EventID = @EventID
			Set @Old_PerformanceID = @PerformanceID

		FETCH NEXT FROM Check_Cursor INTO
							@Reservation_Owner,
							@Ticket_Owner,
							@MatrixCellID,
							@Quantity,
							@SaleID,
							@SaleitemID,
							@CheckforRestrictionOnly,
							@AccountRestrictionID,
							@ReservationAccountLimit,
							@TicketAccountLimit,
							@PerformanceID,
							@EventID
		END

		CLOSE Check_Cursor;
		DEALLOCATE Check_Cursor;
	END

RETURN;
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_AR_TicketOwner_Performance]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_AR_TicketOwner_Performance</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>CREATE PROCEDURE [otn_sp_AR_TicketOwner_Performance]  (
                                                      @Restriction_Check         Restriction_Table READONLY,
													  @PreventSale int OUTPUT,
													  @RejectReasonErrorCode int OUTPUT,
													  @RejectType int OUTPUT,
													  @RejectRestrictionDescription varchar(100) OUTPUT,
													  @RejectRemainingAmount int OUTPUT
                                                    ) 
AS    
BEGIN

	DECLARE @SalesDate datetime = getdate();
	DECLARE @RestrictionType int
	DECLARE @Reservation_Owner int
	DECLARE @OldAccountRestrictionID int = 99999
	DECLARE @ReservationAccountLimit int
	DECLARE @AccountRestrictionID int
	DECLARE @Ticket_Owner int
	DECLARE @MatrixCellID int
	DECLARE @Quantity int
	DECLARE @FullQuantity int
	DECLARE @PerformanceID int
	DECLARE @EventID int
	DECLARE @SaleID int
	DECLARE @SaleitemID int
	DECLARE @CheckforRestrictionOnly int
	DECLARE @TicketAccountLimit int
	DECLARE @OLD_Ticket_Owner int
	DECLARE @ReservationorTicket int = 0
	DECLARE @CountofMatrixCells int = 0
	DECLARE @Prevent int = 0
	DECLARE @Old_PerformanceID int = 0
	DECLARE @Old_EventID int = 0

	
--Performance Reservation Owner Check
	SET @RestrictionType = 2
	Set @OldAccountRestrictionID = 99999
	Set @OLD_Ticket_Owner = 99999
	
	DECLARE Check_Cursor CURSOR LOCAL FOR
		select   Reservation_Owner,
							Ticket_Owner,
							Res_Table.MatrixCellID,
							SUM(Quantity) as Quantity,
							SaleID,
							SaleitemID,
							CheckforRestrictionOnly,
							cnf_AccountRestriction.AccountRestrictionID,
							cnf_AccountRestriction.ReservationAccountLimit,
							cnf_AccountRestriction.TicketAccountLimit,
							Res_Table.PerformanceID,
							RES_Table.Eventid

			from @Restriction_Check Res_Table
				INNER JOIN CNF_AccountRestriction2Performance							ON CNF_AccountRestriction2Performance.PerformanceID = Res_Table.PerformanceID

				LEFT JOIN cnf_AccountRestriction2Account WITH(NOLOCK)					ON (cnf_AccountRestriction2Account.AccountID = Res_Table.Ticket_Owner)
					                                                                        and cnf_AccountRestriction2Account.AccountRestrictionId = CNF_AccountRestriction2Performance.AccountRestrictionId
					                     																								
			    LEFT JOIN cnf_AccountRestriction2DMGCategory WITH(NOLOCK)				ON (cnf_AccountRestriction2DMGCategory.DMGCategoryID = (select DMGCategoryID from data_account WITH(NOLOCK) where data_account.accountid = Res_Table.Ticket_Owner))																							
					                                                                 		and cnf_AccountRestriction2DMGCategory.AccountRestrictionId = CNF_AccountRestriction2Performance.AccountRestrictionId
				INNER JOIN cnf_AccountRestriction WITH(NOLOCK)							ON cnf_AccountRestriction.AccountRestrictionId = CNF_AccountRestriction2Performance.AccountRestrictionId

			where cnf_AccountRestriction.Enabled = 1
			and Convert(date, GetDAte(), 120) between Convert(date, StartDateTime, 120) and Convert(date, EndDateTime, 120)
			and CNF_AccountRestriction.RestrictionType = @RestrictionType
			and Res_Table.Ticket_Owner is not null
			and TicketAccountLimit is not null
			and Res_Table.Ticket_Owner &lt;&gt; 0
			and ((cnf_AccountRestriction2Account.accountid is not null) or (cnf_AccountRestriction2DMGCategory.dmgcategoryid is not null))

			GROUP BY Reservation_Owner,
							Ticket_Owner,
							Res_Table.MatrixCellID,
							SaleID,
							SaleitemID,
							CheckforRestrictionOnly,
							cnf_AccountRestriction.AccountRestrictionID,
							cnf_AccountRestriction.ReservationAccountLimit,
							cnf_AccountRestriction.TicketAccountLimit,
							Res_Table.PerformanceID,
							RES_Table.Eventid

	OPEN Check_Cursor

	FETCH NEXT FROM Check_Cursor INTO
						@Reservation_Owner,
						@Ticket_Owner,
						@MatrixCellID,
						@Quantity,
						@SaleID,
						@SaleitemID,
						@CheckforRestrictionOnly,
						@AccountRestrictionID,
						@ReservationAccountLimit,
						@TicketAccountLimit,
						@PerformanceID,
						@EventID


	WHILE @@FETCH_STATUS = 0
	BEGIN
		IF @OldAccountRestrictionID &lt;&gt; @AccountRestrictionID and (@PreventSale = 0) or ((@OldAccountRestrictionID = @AccountRestrictionID) and (@PreventSale = 0) and ((@Old_PerformanceID &lt;&gt; @PerformanceID) or (@OLD_Ticket_Owner &lt;&gt; @Ticket_Owner)))
		BEGIN 
			If @TicketAccountLimit &gt; 0 
				set @ReservationorTicket = 2

			SET @Prevent = 0;

			IF @ReservationorTicket = 2
			BEGIN
				select @FullQuantity = sum(Quantity),  @CountofMatrixCells = 1
					from @Restriction_Check
					where PerformanceID = @PerformanceID 	
						and Ticket_Owner = @Ticket_Owner
				
				if @FullQuantity &gt; 0
				Begin
					if @CountofMatrixCells = 1 						 																
						Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @ReservationorTicket, @RestrictionType, @Reservation_Owner, @Ticket_Owner, 
															@PerformanceID, @EventID, @SaleID, @SaleitemID, @CheckforRestrictionOnly, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
					else
					begin
						Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @ReservationorTicket, @RestrictionType, @Reservation_Owner, @Ticket_Owner, 
															@PerformanceID, @EventID, @SaleID, @SaleitemID, 1, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
						set @Prevent = @PreventSale

						if @Prevent = 0 and @CheckforRestrictionOnly = 0 
						begin
							DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

							INSERT INTO [dbo].[DATA_AccountLimit]
											([AccountRestrictionId]
											,[AccountId]
											,[PerformanceId]
											,[SaleId]
											,[SaleItemId]
											,[SaleDate]
											,[ReservationAccountQuantity]
											,[TicketAccountQuantity])
										VALUES
											(@AccountRestrictionID
											,@Ticket_Owner
											,@PerformanceID
											,@SaleID
											,@SaleItemID
											,@SalesDate
											,0
											,@FullQuantity)								 
						end
					end
				end
				else
				begin
						if @Prevent = 0 and @CheckforRestrictionOnly = 0 
						begin
							INSERT INTO [dbo].[DATA_AccountLimit]
											([AccountRestrictionId]
											,[AccountId]
											,[PerformanceId]
											,[SaleId]
											,[SaleItemId]
											,[SaleDate]
											,[ReservationAccountQuantity]
											,[TicketAccountQuantity])
										VALUES
											(@AccountRestrictionID
											,@Ticket_Owner
											,@PerformanceID
											,@SaleID
											,@SaleItemID
											,@SalesDate
											,0
											,@Quantity)	
						end
				end
			END
		END
		ELSE
		BEGIN
			IF @OldAccountRestrictionID = @AccountRestrictionID and @Ticket_Owner = @OLD_Ticket_Owner and @Quantity &lt; 0
			begin
								INSERT INTO [dbo].[DATA_AccountLimit]
												([AccountRestrictionId]
												,[AccountId]
												,[PerformanceId]
												,[SaleId]
												,[SaleItemId]
												,[SaleDate]
												,[ReservationAccountQuantity]
												,[TicketAccountQuantity])
											VALUES
												(@AccountRestrictionID
												,@Reservation_Owner
												,@PerformanceID
												,@SaleID
												,@SaleItemID
												,@SalesDate
												,@Quantity
												,0)	

			end 
				
			IF @OldAccountRestrictionID &lt;&gt; @AccountRestrictionID and @Ticket_Owner &lt;&gt; @OLD_Ticket_Owner
			begin
				if @Prevent = 0 and @CheckforRestrictionOnly = 0 
				begin
							DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

							INSERT INTO [dbo].[DATA_AccountLimit]
											([AccountRestrictionId]
											,[AccountId]
											,[PerformanceId]
											,[SaleId]
											,[SaleItemId]
											,[SaleDate]
											,[ReservationAccountQuantity]
											,[TicketAccountQuantity])
										VALUES
											(@AccountRestrictionID
											,@Ticket_Owner
											,@PerformanceID
											,@SaleID
											,@SaleItemID
											,@SalesDate
											,0
											,@Quantity)						 
				end
			end
		END
		Set @OldAccountRestrictionID = @AccountRestrictionID
		Set @OLD_Ticket_Owner = @Ticket_Owner

	FETCH NEXT FROM Check_Cursor INTO
						@Reservation_Owner,
						@Ticket_Owner,
						@MatrixCellID,
						@Quantity,
						@SaleID,
						@SaleitemID,
						@CheckforRestrictionOnly,
						@AccountRestrictionID,
						@ReservationAccountLimit,
						@TicketAccountLimit,
						@PerformanceID,
						@EventID
	END

	CLOSE Check_Cursor;
	DEALLOCATE Check_Cursor;


--Event Ticket Owner Check
	IF @PreventSale = 0
	BEGIN
		SET @RestrictionType = 2
		Set @OldAccountRestrictionID = 99999
		Set @OLD_Ticket_Owner = 99999
		DECLARE Check_Cursor CURSOR LOCAL FOR
			select   Reservation_Owner,
							 Ticket_Owner,
							 Res_Table.MatrixCellID,
							 SUM(Quantity),
							 SaleID,
							 SaleitemID,
							 CheckforRestrictionOnly,
							 cnf_AccountRestriction.AccountRestrictionID,
							 cnf_AccountRestriction.ReservationAccountLimit,
							 cnf_AccountRestriction.TicketAccountLimit,
							 Res_Table.PerformanceID,
							 RES_Table.Eventid

		
				from @Restriction_Check Res_Table
					INNER JOIN CNF_AccountRestriction2Event WITH(NOLOCK)					ON CNF_AccountRestriction2Event.EventID = Res_Table.EventID

					LEFT JOIN cnf_AccountRestriction2Account WITH(NOLOCK)					ON (cnf_AccountRestriction2Account.AccountID = Res_Table.Ticket_Owner)																							
					                     														and CNF_AccountRestriction2Event.AccountRestrictionId = cnf_AccountRestriction2Account.AccountRestrictionId	
																								
			        LEFT JOIN cnf_AccountRestriction2DMGCategory WITH(NOLOCK)				ON (cnf_AccountRestriction2DMGCategory.DMGCategoryID = (select DMGCategoryID from data_account WITH(NOLOCK) where data_account.accountid = Res_Table.Ticket_Owner))																							
					                         													and CNF_AccountRestriction2Event.AccountRestrictionId = cnf_AccountRestriction2DMGCategory.AccountRestrictionId	

					INNER JOIN cnf_AccountRestriction WITH(NOLOCK)							ON cnf_AccountRestriction.AccountRestrictionId = CNF_AccountRestriction2Event.AccountRestrictionId


			 where cnf_AccountRestriction.Enabled = 1
			   and Convert(date, GetDAte(), 120) between Convert(date, StartDateTime, 120) and Convert(date, EndDateTime, 120)
			   and CNF_AccountRestriction.RestrictionType = @RestrictionType
			   and Res_Table.Ticket_Owner is not null
			   and TicketAccountLimit is not null
			   and Res_Table.Ticket_Owner &lt;&gt; 0
			   and ((cnf_AccountRestriction2Account.accountid is not null) or (cnf_AccountRestriction2DMGCategory.dmgcategoryid is not null))


			 GROUP BY Reservation_Owner,
							 Ticket_Owner,
							 Res_Table.MatrixCellID,
							 SaleID,
							 SaleitemID,
							 CheckforRestrictionOnly,
							 cnf_AccountRestriction.AccountRestrictionID,
							 cnf_AccountRestriction.ReservationAccountLimit,
							 cnf_AccountRestriction.TicketAccountLimit,
							 Res_Table.PerformanceID,
							 RES_Table.Eventid

		OPEN Check_Cursor

		FETCH NEXT FROM Check_Cursor INTO
							@Reservation_Owner,
							@Ticket_Owner,
							@MatrixCellID,
							@Quantity,
							@SaleID,
							@SaleitemID,
							@CheckforRestrictionOnly,
							@AccountRestrictionID,
							@ReservationAccountLimit,
							@TicketAccountLimit,
							@PerformanceID,
							@EventID


		WHILE @@FETCH_STATUS = 0
		BEGIN
			IF @OldAccountRestrictionID &lt;&gt; @AccountRestrictionID  and (@PreventSale = 0) 
			     or ((@OldAccountRestrictionID = @AccountRestrictionID) and (@PreventSale = 0)  and ((@OLD_PerformanceID &lt;&gt; @PerformanceID) or (@OLD_Ticket_Owner &lt;&gt; @Ticket_Owner)))			  
			BEGIN 
				If @TicketAccountLimit &gt; 0 
				  set @ReservationorTicket = 2

				SET @Prevent = 0;

				IF @ReservationorTicket = 2
				BEGIN
					select @FullQuantity = sum(Quantity),  @CountofMatrixCells = 1
						from @Restriction_Check
						where PerformanceID = @PerformanceID  	
						  and Ticket_Owner = @Ticket_Owner
				
					if @FullQuantity &gt; 0
					Begin
						if @CountofMatrixCells = 1 						 																
							Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @ReservationorTicket, @RestrictionType, @Reservation_Owner, @Ticket_Owner, 
															   @PerformanceID, @EventID, @SaleID, @SaleitemID, @CheckforRestrictionOnly, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
						else
						begin
							Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @ReservationorTicket, @RestrictionType, @Reservation_Owner, @Ticket_Owner, 
																@PerformanceID, @EventID, @SaleID, @SaleitemID, 1, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
							set @Prevent = @PreventSale

							if @Prevent = 0 and @CheckforRestrictionOnly = 0 
							begin
							    DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

								INSERT INTO [dbo].[DATA_AccountLimit]
												([AccountRestrictionId]
												,[AccountId]
												,[PerformanceId]
												,[SaleId]
												,[SaleItemId]
												,[SaleDate]
												,[ReservationAccountQuantity]
												,[TicketAccountQuantity])
											VALUES
												(@AccountRestrictionID
												,@Ticket_Owner
												,@PerformanceID
												,@SaleID
												,@SaleItemID
												,@SalesDate
												,0
												,@FullQuantity)							 
							end
						end
					end
					else
					begin
							if @Prevent = 0 and @CheckforRestrictionOnly = 0 
							begin
									INSERT INTO [dbo].[DATA_AccountLimit]
													([AccountRestrictionId]
													,[AccountId]
													,[PerformanceId]
													,[SaleId]
													,[SaleItemId]
													,[SaleDate]
													,[ReservationAccountQuantity]
													,[TicketAccountQuantity])
												VALUES
													(@AccountRestrictionID
													,@Ticket_Owner
													,@PerformanceID
													,@SaleID
													,@SaleItemID
													,@SalesDate
													,0
													,@Quantity)	
							end
					end
				END

			END
			ELSE
			BEGIN
				IF @OldAccountRestrictionID = @AccountRestrictionID and @Ticket_Owner = @OLD_Ticket_Owner and @Quantity &lt; 0
				begin
									INSERT INTO [dbo].[DATA_AccountLimit]
													([AccountRestrictionId]
													,[AccountId]
													,[PerformanceId]
													,[SaleId]
													,[SaleItemId]
													,[SaleDate]
													,[ReservationAccountQuantity]
													,[TicketAccountQuantity])
												VALUES
													(@AccountRestrictionID
													,@Reservation_Owner
													,@PerformanceID
													,@SaleID
													,@SaleItemID
													,@SalesDate
													,@Quantity
													,0)	

				end 
				IF @OldAccountRestrictionID &lt;&gt; @AccountRestrictionID and @Ticket_Owner &lt;&gt; @OLD_Ticket_Owner
				begin
					if @Prevent = 0 and @CheckforRestrictionOnly = 0 
					begin
								DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

								INSERT INTO [dbo].[DATA_AccountLimit]
												([AccountRestrictionId]
												,[AccountId]
												,[PerformanceId]
												,[SaleId]
												,[SaleItemId]
												,[SaleDate]
												,[ReservationAccountQuantity]
												,[TicketAccountQuantity])
											VALUES
												(@AccountRestrictionID
												,@Ticket_Owner
												,@PerformanceID
												,@SaleID
												,@SaleItemID
												,@SalesDate
												,0
												,@Quantity)						 
					end
				end
			END
			

			Set @OldAccountRestrictionID = @AccountRestrictionID
			Set @OLD_Ticket_Owner = @Ticket_Owner
			SET @OLD_EventID = @EventID
			Set @Old_PerformanceID = @PerformanceID

		FETCH NEXT FROM Check_Cursor INTO
							@Reservation_Owner,
							@Ticket_Owner,
							@MatrixCellID,
							@Quantity,
							@SaleID,
							@SaleitemID,
							@CheckforRestrictionOnly,
							@AccountRestrictionID,
							@ReservationAccountLimit,
							@TicketAccountLimit,
							@PerformanceID,
							@EventID
		END

		CLOSE Check_Cursor;
		DEALLOCATE Check_Cursor;
	END

RETURN;
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_AR_TicketOwner_Matrixcell]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_AR_TicketOwner_Matrixcell</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>CREATE PROCEDURE [otn_sp_AR_TicketOwner_Matrixcell]  (
                                                      @Restriction_Check         Restriction_Table READONLY,
													  @PreventSale int OUTPUT,
													  @RejectReasonErrorCode int OUTPUT,
													  @RejectType int OUTPUT,
													  @RejectRestrictionDescription varchar(100) OUTPUT,
													  @RejectRemainingAmount int OUTPUT
                                                    ) 
AS    
BEGIN


	DECLARE @SalesDate datetime = getdate();
	DECLARE @RestrictionType int
	DECLARE @Reservation_Owner int
	DECLARE @OldAccountRestrictionID int = 99999
	DECLARE @ReservationAccountLimit int
	DECLARE @AccountRestrictionID int
	DECLARE @Ticket_Owner int
	DECLARE @MatrixCellID int
	DECLARE @Quantity int
	DECLARE @FullQuantity int
	DECLARE @PerformanceID int
	DECLARE @EventID int
	DECLARE @SaleID int
	DECLARE @SaleitemID int
	DECLARE @CheckforRestrictionOnly int
	DECLARE @TicketAccountLimit int
	DECLARE @OLD_Ticket_Owner int
	DECLARE @ReservationorTicket int = 0
	DECLARE @CountofMatrixCells int = 0
	DECLARE @Prevent int = 0

	SET @RestrictionType = 1
	Set @OldAccountRestrictionID = 99999
	SET @OLD_Ticket_Owner = 99999

	DECLARE Check_Cursor CURSOR LOCAL FOR
		select   Reservation_Owner,
							Ticket_Owner,
							Res_Table.MatrixCellID,
							SUM(Quantity) as Quantity,
							SaleID,
							SaleitemID,
							CheckforRestrictionOnly,
							cnf_AccountRestriction.AccountRestrictionID,
							cnf_AccountRestriction.ReservationAccountLimit,
							cnf_AccountRestriction.TicketAccountLimit

			from @Restriction_Check Res_Table
				INNER JOIN cnf_AccountRestriction2MatrixCell WITH(NOLOCK)				ON cnf_AccountRestriction2MatrixCell.MatrixCellID = Res_Table.MatrixCellID
					
				LEFT JOIN cnf_AccountRestriction2Account WITH(NOLOCK)					ON (cnf_AccountRestriction2Account.AccountID = Res_Table.Ticket_Owner)																							
					                                                                    and cnf_accountrestriction2Account.AccountRestrictionID = CNF_AccountRestriction2MatrixCell.AccountRestrictionId
																										
			    LEFT JOIN cnf_AccountRestriction2DMGCategory WITH(NOLOCK)				ON (cnf_AccountRestriction2DMGCategory.DMGCategoryID = (select DMGCategoryID from data_account WITH(NOLOCK) where data_account.accountid = Res_Table.Ticket_Owner))																							
					                                                                    and cnf_AccountRestriction2DMGCategory.AccountRestrictionID = CNF_AccountRestriction2MatrixCell.AccountRestrictionId				
				
				INNER JOIN cnf_AccountRestriction WITH(NOLOCK)							ON cnf_AccountRestriction.AccountRestrictionId = cnf_AccountRestriction2MatrixCell.AccountRestrictionId

			where cnf_AccountRestriction.Enabled = 1
			and Convert(date, GetDAte(), 120) between Convert(date, StartDateTime, 120) and Convert(date, EndDateTime, 120)
			and CNF_AccountRestriction.RestrictionType = @RestrictionType
			and Res_Table.Ticket_Owner is not null
			and TicketAccountLimit is not null
			and Res_Table.Ticket_Owner &lt;&gt; 0
			and ((cnf_AccountRestriction2Account.accountid is not null) or (cnf_AccountRestriction2DMGCategory.dmgcategoryid is not null))
			and ISNULL(Res_Table.PerformanceID, 0) = 0

			GROUP BY Reservation_Owner,
							Ticket_Owner,
							Res_Table.MatrixCellID,
							SaleID,
							SaleitemID,
							CheckforRestrictionOnly,
							cnf_AccountRestriction.AccountRestrictionID,
							cnf_AccountRestriction.ReservationAccountLimit,
							cnf_AccountRestriction.TicketAccountLimit
			order by Ticket_Owner, AccountRestrictionID

	OPEN Check_Cursor

	FETCH NEXT FROM Check_Cursor INTO
						@Reservation_Owner,
						@Ticket_Owner,
						@MatrixCellID,
						@Quantity,
						@SaleID,
						@SaleitemID,
						@CheckforRestrictionOnly,
						@AccountRestrictionID,
						@ReservationAccountLimit,
						@TicketAccountLimit


	WHILE @@FETCH_STATUS = 0
	BEGIN
		IF @OldAccountRestrictionID &lt;&gt; @AccountRestrictionID and (@PreventSale = 0)  or ((@OldAccountRestrictionID = @AccountRestrictionID) and (@PreventSale = 0) and (@Ticket_Owner &lt;&gt; @OLD_Ticket_Owner))
		BEGIN 
			If @TicketAccountLimit &gt; 0 
				set @ReservationorTicket = 2

			SET @Prevent = 0;

			IF @ReservationorTicket = 2
			BEGIN
				select @FullQuantity = sum(Quantity),  @CountofMatrixCells = Count(*) 
					from @Restriction_Check
					where MatrixCellID in (select MatrixcellId 
											from cnf_AccountRestriction2MatrixCell WITH(NOLOCK)									
											where cnf_AccountRestriction2MatrixCell.AccountRestrictionId = @AccountRestrictionID)	
						and Ticket_Owner = @Ticket_Owner
						and ISNULL(PerformanceID, 0) = 0

				if @FullQuantity &gt; 0
				Begin				
					if @CountofMatrixCells = 1 						 																
						Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @ReservationorTicket, @RestrictionType, @Reservation_Owner, @Ticket_Owner, 
															null, null, @SaleID, @SaleitemID, @CheckforRestrictionOnly, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
					ELSE
					begin
						Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @ReservationorTicket, @RestrictionType, @Reservation_Owner, @Ticket_Owner, 
															null, null, @SaleID, @SaleitemID, 1, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
						set @Prevent = @PreventSale

						if @Prevent = 0 and @CheckforRestrictionOnly = 0 
						begin
							DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

							INSERT INTO [dbo].[DATA_AccountLimit]
											([AccountRestrictionId]
											,[AccountId]
											,[PerformanceId]
											,[SaleId]
											,[SaleItemId]
											,[SaleDate]
											,[ReservationAccountQuantity]
											,[TicketAccountQuantity])
										VALUES
											(@AccountRestrictionID
											,@Ticket_Owner
											,@PerformanceID
											,@SaleID
											,@SaleItemID
											,@SalesDate
											,0
											,@FullQuantity)							 
						end
					end
				end
				else
				begin
						if @Prevent = 0 and @CheckforRestrictionOnly = 0 
						begin

							INSERT INTO [dbo].[DATA_AccountLimit]
												([AccountRestrictionId]
												,[AccountId]
												,[PerformanceId]
												,[SaleId]
												,[SaleItemId]
												,[SaleDate]
												,[ReservationAccountQuantity]
												,[TicketAccountQuantity])
											VALUES
												(@AccountRestrictionID
												,@Ticket_Owner
												,@PerformanceID
												,@SaleID
												,@SaleItemID
												,@SalesDate
												,0
												,@Quantity)	
					end
				end
			END
		END
		ELSE
		BEGIN
			IF @OldAccountRestrictionID = @AccountRestrictionID and @Ticket_Owner = @OLD_Ticket_Owner and @Quantity &lt; 0
			begin
								INSERT INTO [dbo].[DATA_AccountLimit]
												([AccountRestrictionId]
												,[AccountId]
												,[PerformanceId]
												,[SaleId]
												,[SaleItemId]
												,[SaleDate]
												,[ReservationAccountQuantity]
												,[TicketAccountQuantity])
											VALUES
												(@AccountRestrictionID
												,@Reservation_Owner
												,@PerformanceID
												,@SaleID
												,@SaleItemID
												,@SalesDate
												,@Quantity
												,0)	

			end 
			IF @OldAccountRestrictionID &lt;&gt; @AccountRestrictionID and @Ticket_Owner &lt;&gt; @OLD_Ticket_Owner
			begin
				if @Prevent = 0 and @CheckforRestrictionOnly = 0 
				begin
							DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

							INSERT INTO [dbo].[DATA_AccountLimit]
											([AccountRestrictionId]
											,[AccountId]
											,[PerformanceId]
											,[SaleId]
											,[SaleItemId]
											,[SaleDate]
											,[ReservationAccountQuantity]
											,[TicketAccountQuantity])
										VALUES
											(@AccountRestrictionID
											,@Ticket_Owner
											,@PerformanceID
											,@SaleID
											,@SaleItemID
											,@SalesDate
											,0
											,@Quantity)						 
				end
			end
		END

		Set @OldAccountRestrictionID = @AccountRestrictionID
		SET @OLD_Ticket_Owner = @Ticket_Owner

		FETCH NEXT FROM Check_Cursor INTO
						@Reservation_Owner,
						@Ticket_Owner,
						@MatrixCellID,
						@Quantity,
						@SaleID,
						@SaleitemID,
						@CheckforRestrictionOnly,
						@AccountRestrictionID,
						@ReservationAccountLimit,
						@TicketAccountLimit
	END

	CLOSE Check_Cursor;
	DEALLOCATE Check_Cursor;


RETURN;

END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_GetAccountRestrictions_Performance]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_GetAccountRestrictions_Performance</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>CREATE Procedure [dbo].[otn_sp_GetAccountRestrictions_Performance]( @AccountRestrictionID int,
																	@Quantity int,														
																	@ReservationorTicket int,
																	@RestrictionType int,
																	@Reservation_AccountID int,
																	@Ticket_AccountID int,
																	@PerformanceID int,
																	@EventID int,
																	@SaleID int,
																	@SaleItemID int,
																	@CheckforRestrictionOnly int,
																	@PreventSale int OUTPUT,
																	@RejectReasonErrorCode int OUTPUT,
																	@RejectType int OUTPUT,
																	@RejectRestrictionDescription varchar(100) OUTPUT,
																	@RejectRemainingAmount int OUTPUT
																	)  

AS    
BEGIN

	DECLARE @SalesDate datetime = getdate();
	DECLARE @ReservationLimit int
	DECLARE @TicketLimit int
	DECLARE	@PerDayLimit int
	DECLARE	@PerWeekLimit int
	DECLARE	@PerMonthLimit int
	DECLARE	@PerQuarterLimit int
	DECLARE	@PerSemiAnnualLimit int
	DECLARE	@PerYearLimit int
	DECLARE @ReservationAccountQuantity_DayofYear int
	DECLARE @ReservationAccountQuantity_WeekofYear int
	DECLARE @ReservationAccountQuantity_MonthofYear int
	DECLARE @ReservationAccountQuantity_QuarterofYear int
	DECLARE @ReservationAccountQuantity_SemiAnnualofYear int
	DECLARE @ReservationAccountQuantity_Year int
	DECLARE @TicketAccountQuantity_DayofYear int
	DECLARE @TicketAccountQuantity_WeekofYear int
	DECLARE @TicketAccountQuantity_MonthofYear int
	DECLARE @TicketAccountQuantity_QuarterofYear int
	DECLARE @TicketAccountQuantity_SemiAnnualofYear int
	DECLARE @TicketAccountQuantity_Year int

	DECLARE @RestrictLimit int = 99999
	DECLARE @ReservationAccountOwner int = 1
	DECLARE @TicketAccountOwner int = 2
    DECLARE @Description varchar(max)
	DECLARE @CheckOnly int = 1
	DECLARE @EX_Quantity int = 0
	DECLARE @RestrictionLimit int

	SET @PreventSale = 0  
	SET @RejectReasonErrorCode = 0
	SET @RejectType = 0
	SET	@RejectRestrictionDescription = ''
	SET @RejectRemainingAmount = 0


	if ((@PerformanceID is not null) and (@EventID is not null))
	BEGIN
		DECLARE Restriction_Cursor CURSOR LOCAL FOR
				select AccountRestrictionID,
			       Description,
					ReservationAccountLimit,
					TicketAccountLimit,
					PerDayLimit,
					PerWeekLimit,
					PerMonthLimit,
					PerQuarterLimit,
					PerSemiAnnualLimit,
					PerYearLimit,
					case when ReservationAccountQuantity_DayofYear &gt; 0 then ReservationAccountQuantity_DayofYear
						else 0
					end ReservationAccountQuantity_DayofYear,
					case when ReservationAccountQuantity_WeekofYear &gt; 0 then ReservationAccountQuantity_WeekofYear
						else 0
					end ReservationAccountQuantity_WeekofYear,
					case when ReservationAccountQuantity_MonthofYear &gt; 0 then ReservationAccountQuantity_MonthofYear
						else 0
					end ReservationAccountQuantity_MonthofYear,
					case when ReservationAccountQuantity_QuarterofYear &gt; 0 then ReservationAccountQuantity_QuarterofYear
						else 0
					end ReservationAccountQuantity_QuarterofYear,
					case when ReservationAccountQuantity_SemiAnnualofYear &gt; 0 then ReservationAccountQuantity_SemiAnnualofYear
						else 0
					end ReservationAccountQuantity_SemiAnnualofYear,
					case when ReservationAccountQuantity_Year &gt; 0 then ReservationAccountQuantity_Year
						else 0
					end ReservationAccountQuantity_Year,
					case when TicketAccountQuantity_DayofYear &gt; 0 then TicketAccountQuantity_DayofYear
						else 0
					end TicketAccountQuantity_DayofYear,
					case when TicketAccountQuantity_WeekofYear &gt; 0 then TicketAccountQuantity_WeekofYear
						else 0
					end TicketAccountQuantity_WeekofYear,
					case when TicketAccountQuantity_MonthofYear &gt; 0 then TicketAccountQuantity_MonthofYear
						else 0
					end TicketAccountQuantity_MonthofYear,
					case when TicketAccountQuantity_QuarterofYear &gt; 0 then TicketAccountQuantity_QuarterofYear
						else 0
					end TicketAccountQuantity_QuarterofYear,
					case when TicketAccountQuantity_SemiAnnualofYear &gt; 0 then TicketAccountQuantity_SemiAnnualofYear
						else 0
					end TicketAccountQuantity_SemiAnnualofYear,
					case when TicketAccountQuantity_Year &gt; 0 then TicketAccountQuantity_Year
						else 0
					end TicketAccountQuantity_Year
		from (
				select distinct CNF_AccountRestriction.AccountRestrictionID,
				        CNF_AccountRestriction.Description,
						CNF_AccountRestriction.ReservationAccountLimit,
						CNF_AccountRestriction.TicketAccountLimit,
						ISNULL(CNF_AccountRestriction.PerDayLimit, @RestrictLimit) as PerDayLimit,
						ISNULL(CNF_AccountRestriction.PerWeekLimit, @RestrictLimit) as PerWeekLimit,
						ISNULL(CNF_AccountRestriction.PerMonthLimit, @RestrictLimit) as PerMonthLimit,
						ISNULL(CNF_AccountRestriction.PerQuarterLimit, @RestrictLimit) as PerQuarterLimit,
						ISNULL(CNF_AccountRestriction.PerSemiAnnualLimit, @RestrictLimit) as PerSemiAnnualLimit,
						ISNULL(CNF_AccountRestriction.PerYearLimit, @RestrictLimit) as PerYearLimit,
						ISNULL((select sum(case when cast(saledate as date) = cast(@SalesDate as date) then ReservationAccountQuantity
										else 0
									end)
								from DATA_AccountLimit
									INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
								where (DATA_AccountLimit.Accountid = @Reservation_AccountID)
									and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
									and DATA_AccountLimit.SaleDate &gt;= CNF_AccountRestriction.StartDateTime
									and data_accountLimit.PerformanceID = @PerformanceID
									and data_accountlimit.Saleid &lt;&gt; @Saleid
									and Data_accountlimit.Saleitemid &lt;&gt; @Saleitemid
						), 0) ReservationAccountQuantity_DayofYear,
						ISNULL((select sum(case when (cast(datepart(yy, saledate) as varchar(4)) + '-' + cast(datepart(wk, saledate) as varchar(2))) = cast(datepart(yy, @SalesDate) as varchar(4)) + '-' + cast(datepart(wk, @SalesDate) as varchar(2)) then ReservationAccountQuantity
											else 0
										end)
								from DATA_AccountLimit
												INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
								where (DATA_AccountLimit.Accountid = @Reservation_AccountID)
								and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
								and DATA_AccountLimit.SaleDate &gt;= CNF_AccountRestriction.StartDateTime
								and data_accountLimit.PerformanceID = @PerformanceID
								and data_accountlimit.Saleid &lt;&gt; @Saleid
								and Data_accountlimit.Saleitemid &lt;&gt; @Saleitemid
						), 0) ReservationAccountQuantity_WeekofYear,
						ISNULL((select sum(case when (cast(datepart(yy, saledate) as varchar(4)) + '-' + cast(datepart(mm, saledate) as varchar(2))) = cast(datepart(yy, @SalesDate) as varchar(4)) + '-' + cast(datepart(mm, @SalesDate) as varchar(2)) then ReservationAccountQuantity
											else 0
										end)
								from DATA_AccountLimit
												INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
								where (DATA_AccountLimit.Accountid = @Reservation_AccountID)
								and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
								and DATA_AccountLimit.SaleDate &gt;= CNF_AccountRestriction.StartDateTime
								and data_accountLimit.PerformanceID = @PerformanceID
								and data_accountlimit.Saleid &lt;&gt; @Saleid
								and Data_accountlimit.Saleitemid &lt;&gt; @Saleitemid
						), 0) ReservationAccountQuantity_MonthofYear,

						ISNULL((select sum(case when (DATEPART(year, SaleDate) = DATEPART(year, @SalesDate)) then 
																	CASE when (DATEPART(QUARTER, SaleDate) = DATEPART(QUARTER, @SalesDate)) then ReservationAccountQuantity
																		 else 0
																	end
												else 0
											end)
								from DATA_AccountLimit
												INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
								where (DATA_AccountLimit.Accountid = @Reservation_AccountID)
								and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
								and DATA_AccountLimit.SaleDate &gt;= CNF_AccountRestriction.StartDateTime
								and data_accountLimit.PerformanceID = @PerformanceID
								and data_accountlimit.Saleid &lt;&gt; @Saleid
								and Data_accountlimit.Saleitemid &lt;&gt; @Saleitemid
						), 0) ReservationAccountQuantity_QuarterofYear,

						ISNULL((select sum(case when (DATEPART(year, SaleDate) = DATEPART(year, @SalesDate)) then 
															CASE WHEN ((CASE when DATEPART(QUARTER, SaleDate) in (1, 2) then 1
																			else 2
																	end) =
																	(CASE when DATEPART(QUARTER, @SalesDate) in (1, 2) then 1
																			else 2
																	end))  then ReservationAccountQuantity
																else 0
															end 

										else 0
									end)
								from DATA_AccountLimit
												INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
								where (DATA_AccountLimit.Accountid = @Reservation_AccountID)
								and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
								and DATA_AccountLimit.SaleDate &gt;= CNF_AccountRestriction.StartDateTime
								and data_accountLimit.PerformanceID = @PerformanceID
								and data_accountlimit.Saleid &lt;&gt; @Saleid
								and Data_accountlimit.Saleitemid &lt;&gt; @Saleitemid
						), 0) ReservationAccountQuantity_SemiAnnualofYear,

						ISNULL((select sum(case when (cast(datepart(yy, saledate) as varchar(4))) = cast(datepart(yy, @SalesDate) as varchar(4)) then ReservationAccountQuantity
											else 0
										end)
								from DATA_AccountLimit
												INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
								where (DATA_AccountLimit.Accountid = @Reservation_AccountID)
								and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
								and DATA_AccountLimit.SaleDate &gt;= CNF_AccountRestriction.StartDateTime
								and data_accountLimit.PerformanceID = @PerformanceID
								and data_accountlimit.Saleid &lt;&gt; @Saleid
								and Data_accountlimit.Saleitemid &lt;&gt; @Saleitemid
						), 0) ReservationAccountQuantity_Year,

						ISNULL((select sum(case when cast(saledate as date) = cast(@SalesDate as date) then TicketAccountQuantity
										else 0
									end)
								from DATA_AccountLimit
												INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
								where (DATA_AccountLimit.Accountid = @Ticket_AccountID)
								and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
								and DATA_AccountLimit.SaleDate &gt;= CNF_AccountRestriction.StartDateTime
								and data_accountLimit.PerformanceID = @PerformanceID
								and data_accountlimit.Saleid &lt;&gt; @Saleid
								and Data_accountlimit.Saleitemid &lt;&gt; @Saleitemid
						), 0) TicketAccountQuantity_DayofYear,
						ISNULL((select sum(case when (cast(datepart(yy, saledate) as varchar(4)) + '-' + cast(datepart(wk, saledate) as varchar(2))) = cast(datepart(yy, @SalesDate) as varchar(4)) + '-' + cast(datepart(wk, @SalesDate) as varchar(2)) then TicketAccountQuantity
											else 0
										end)
								from DATA_AccountLimit
												INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
								where (DATA_AccountLimit.Accountid = @Ticket_AccountID)
								and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
								and DATA_AccountLimit.SaleDate &gt;= CNF_AccountRestriction.StartDateTime
								and data_accountLimit.PerformanceID = @PerformanceID
								and data_accountlimit.Saleid &lt;&gt; @Saleid
								and Data_accountlimit.Saleitemid &lt;&gt; @Saleitemid
						), 0) TicketAccountQuantity_WeekofYear,
						ISNULL((select sum(case when (cast(datepart(yy, saledate) as varchar(4)) + '-' + cast(datepart(mm, saledate) as varchar(2))) = cast(datepart(yy, @SalesDate) as varchar(4)) + '-' + cast(datepart(mm, @SalesDate) as varchar(2)) then TicketAccountQuantity
											else 0
										end)
								from DATA_AccountLimit
												INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
								where (DATA_AccountLimit.Accountid = @Ticket_AccountID)
								and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
								and DATA_AccountLimit.SaleDate &gt;= CNF_AccountRestriction.StartDateTime
								and data_accountLimit.PerformanceID = @PerformanceID
								and data_accountlimit.Saleid &lt;&gt; @Saleid
								and Data_accountlimit.Saleitemid &lt;&gt; @Saleitemid
						), 0) TicketAccountQuantity_MonthofYear,

						ISNULL((select sum(case when (DATEPART(year, SaleDate) = DATEPART(year, @SalesDate)) then 
																	CASE when (DATEPART(QUARTER, SaleDate) = DATEPART(QUARTER, @SalesDate)) then TicketAccountQuantity
																		 else 0
																	end
												else 0
											end)
								from DATA_AccountLimit
												INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
								where (DATA_AccountLimit.Accountid = @Ticket_AccountID)
								and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
								and DATA_AccountLimit.SaleDate &gt;= CNF_AccountRestriction.StartDateTime
								and data_accountLimit.PerformanceID = @PerformanceID
								and data_accountlimit.Saleid &lt;&gt; @Saleid
								and Data_accountlimit.Saleitemid &lt;&gt; @Saleitemid
						), 0) TicketAccountQuantity_QuarterofYear,

						ISNULL((select sum(case when (DATEPART(year, SaleDate) = DATEPART(year, @SalesDate)) then 
															CASE WHEN ((CASE when DATEPART(QUARTER, SaleDate) in (1, 2) then 1
																			else 2
																	end) =
																	(CASE when DATEPART(QUARTER, @SalesDate) in (1, 2) then 1
																			else 2
																	end))  then TicketAccountQuantity
																else 0
															end 

										else 0
									end)
								from DATA_AccountLimit
												INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
								where (DATA_AccountLimit.Accountid = @Ticket_AccountID)
								and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
								and DATA_AccountLimit.SaleDate &gt;= CNF_AccountRestriction.StartDateTime
								and data_accountLimit.PerformanceID = @PerformanceID
								and data_accountlimit.Saleid &lt;&gt; @Saleid
								and Data_accountlimit.Saleitemid &lt;&gt; @Saleitemid
						), 0) TicketAccountQuantity_SemiAnnualofYear,

						ISNULL((select sum(case when (cast(datepart(yy, saledate) as varchar(4))) = cast(datepart(yy, @SalesDate) as varchar(4)) then TicketAccountQuantity
											else 0
										end)
								from DATA_AccountLimit
												INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
								where (DATA_AccountLimit.Accountid = @Ticket_AccountID)
								and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
								and DATA_AccountLimit.SaleDate &gt;= CNF_AccountRestriction.StartDateTime
								and data_accountLimit.PerformanceID = @PerformanceID
								and data_accountlimit.Saleid &lt;&gt; @Saleid
								and Data_accountlimit.Saleitemid &lt;&gt; @Saleitemid
						), 0) TicketAccountQuantity_Year

				from CNF_AccountRestriction WITH(NOLOCK)
					LEFT JOIN CNF_AccountRestriction2Account WITH(NOLOCK)			on CNF_AccountRestriction2Account.AccountRestrictionId = CNF_AccountRestriction.AccountRestrictionId
																						and CNF_AccountRestriction2Account.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionid
																						and CNF_AccountRestriction2Account.Accountid = case when @ReservationorTicket = @ReservationAccountOwner then @Reservation_AccountID
																																							  else @Ticket_AccountID
																																						  end
					LEFT JOIN CNF_AccountRestriction2DMGCategory WITH(NOLOCK)		ON CNF_AccountRestriction2DMGCategory.dmgcategoryID = (SELECT dmgcategoryid  
																																			 from data_account DA
																																			 where DA.AccountID =  case when @ReservationorTicket = @ReservationAccountOwner then @Reservation_AccountID
																																										else @Ticket_AccountID
																																									 end
																																		   )
																						and CNF_AccountRestriction2DMGCategory.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionid
																						
				

				where CNF_AccountRestriction.AccountRestrictionID = @AccountRestrictionID
				  and ((cnf_AccountRestriction2Account.accountid is not null) or (cnf_AccountRestriction2DMGCategory.dmgcategoryid is not null))
				

			)p

		where ((ISNULL(ReservationAccountLimit, 0) &gt; 0) or (ISNULL(TicketAccountLimit, 0) &gt; 0))

	


		OPEN Restriction_Cursor

		FETCH NEXT FROM Restriction_Cursor INTO
							@AccountRestrictionID, 
							@Description,
							@ReservationLimit,
							@TicketLimit,
							@PerDayLimit,
							@PerWeekLimit,
							@PerMonthLimit,
							@PerQuarterLimit,
							@PerSemiAnnualLimit,
							@PerYearLimit,
							@ReservationAccountQuantity_DayofYear,
							@ReservationAccountQuantity_WeekofYear,
							@ReservationAccountQuantity_MonthofYear,
							@ReservationAccountQuantity_QuarterofYear,
							@ReservationAccountQuantity_SemiAnnualofYear,
							@ReservationAccountQuantity_Year,
							@TicketAccountQuantity_DayofYear,
							@TicketAccountQuantity_WeekofYear,
							@TicketAccountQuantity_MonthofYear,
							@TicketAccountQuantity_QuarterofYear,
							@TicketAccountQuantity_SemiAnnualofYear,
							@TicketAccountQuantity_Year


		WHILE @@FETCH_STATUS = 0
		BEGIN	
			if @ReservationorTicket = @ReservationAccountOwner and @ReservationLimit is not null and @PerformanceId is not null 
			BEGIN
				if @Quantity &lt;= @ReservationLimit and @Quantity &lt;= (@ReservationLimit - @ReservationAccountQuantity_Year)
				BEGIN
					If @CheckforRestrictionOnly &lt;&gt; @CheckOnly
					BEGIN
							DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

							INSERT INTO [dbo].[DATA_AccountLimit]
											([AccountRestrictionId]
											,[AccountId]
											,[PerformanceId]
											,[SaleId]
											,[SaleItemId]
											,[SaleDate]
											,[ReservationAccountQuantity]
											,[TicketAccountQuantity])
										VALUES
											(@AccountRestrictionID
											,@Reservation_AccountID
											,@PerformanceID
											,@SaleID
											,@SaleItemID
											,@SalesDate
											,@Quantity
											,0)
					END
				END
				ELSE
				BEGIN
					Set @PreventSale = 1
					Set @RejectType = 3
					if (@PerformanceID is not null) and (@EventID is not null)
					BEGIN
						if @RejectReasonErrorCode = 0
						begin
							SET @RejectRemainingAmount =  (@ReservationLimit - @ReservationAccountQuantity_Year)
							SET @RejectRestrictionDescription = @Description
							if @RejectRemainingAmount &lt; 0 
								SET @RejectRemainingAmount = 0

							if @RejectRemainingAmount = 0	   						 
								Set @RejectReasonErrorCode = 5087
							else
								Set @RejectReasonErrorCode = 5088
						end
					END
				END			
			END

	--Performance Ticket Owner Check
			if @ReservationorTicket = @TicketAccountOwner and @TicketLimit is not null and @PerformanceId is not null 
			BEGIN
				if @Quantity &lt;= @TicketLimit and @Quantity &lt;= (@TicketLimit - @TicketAccountQuantity_Year)
				BEGIN
					If @CheckforRestrictionOnly &lt;&gt; @CheckOnly
					BEGIN
							DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

							INSERT INTO [dbo].[DATA_AccountLimit]
											([AccountRestrictionId]
											,[AccountId]
											,[PerformanceId]
											,[SaleId]
											,[SaleItemId]
											,[SaleDate]
											,[ReservationAccountQuantity]
											,[TicketAccountQuantity])
										VALUES
											(@AccountRestrictionID
											,@Ticket_AccountID
											,@PerformanceID
											,@SaleID
											,@SaleItemID
											,@SalesDate
											,0
											,@Quantity)
					END
				END
				ELSE
				BEGIN
					Set @PreventSale = 1
					Set @RejectType = 3
					if (@PerformanceID is not null) and (@EventID is not null)
					BEGIN
						if @RejectReasonErrorCode = 0
						begin
							SET @RejectRemainingAmount =  (@TicketLimit - @TicketAccountQuantity_Year)
							SET @RejectRestrictionDescription = @Description 
							if @RejectRemainingAmount &lt; 0 
								SET @RejectRemainingAmount = 0

							if @RejectRemainingAmount = 0	 
								Set @RejectReasonErrorCode = 5087
							else
								Set @RejectReasonErrorCode = 5088
						end
					END
				END
			
			END

		FETCH NEXT FROM Restriction_Cursor INTO
							@AccountRestrictionID, 
							@Description,
							@ReservationLimit,
							@TicketLimit,
							@PerDayLimit,
							@PerWeekLimit,
							@PerMonthLimit,
							@PerQuarterLimit,
							@PerSemiAnnualLimit,
							@PerYearLimit,
							@ReservationAccountQuantity_DayofYear,
							@ReservationAccountQuantity_WeekofYear,
							@ReservationAccountQuantity_MonthofYear,
							@ReservationAccountQuantity_QuarterofYear,
							@ReservationAccountQuantity_SemiAnnualofYear,
							@ReservationAccountQuantity_Year,
							@TicketAccountQuantity_DayofYear,
							@TicketAccountQuantity_WeekofYear,
							@TicketAccountQuantity_MonthofYear,
							@TicketAccountQuantity_QuarterofYear,
							@TicketAccountQuantity_SemiAnnualofYear,
							@TicketAccountQuantity_Year


		END	
	
		CLOSE Restriction_Cursor;
		DEALLOCATE Restriction_Cursor;
	END	

RETURN
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_GetAccountRestrictions_MatrixCell]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_GetAccountRestrictions_MatrixCell</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>CREATE Procedure [dbo].[otn_sp_GetAccountRestrictions_MatrixCell](  @AccountRestrictionID int,
																	@Quantity int,														
																	@ReservationorTicket int,
																	@RestrictionType int,
																	@Reservation_AccountID int,
																	@Ticket_AccountID int,
																	@PerformanceID int,
																	@EventID int,
																	@SaleID int,
																	@SaleItemID int,
																	@CheckforRestrictionOnly int,
																	@PreventSale int OUTPUT,
																	@RejectReasonErrorCode int OUTPUT,
																	@RejectType int OUTPUT,
																	@RejectRestrictionDescription varchar(100) OUTPUT,
																	@RejectRemainingAmount int OUTPUT
																	)  

AS    
BEGIN

	DECLARE @SalesDate datetime = getdate();
	DECLARE @ReservationLimit int
	DECLARE @TicketLimit int
	DECLARE	@PerDayLimit int
	DECLARE	@PerWeekLimit int
	DECLARE	@PerMonthLimit int
	DECLARE	@PerQuarterLimit int
	DECLARE	@PerSemiAnnualLimit int
	DECLARE	@PerYearLimit int
	DECLARE @ReservationAccountQuantity_DayofYear int
	DECLARE @ReservationAccountQuantity_WeekofYear int
	DECLARE @ReservationAccountQuantity_MonthofYear int
	DECLARE @ReservationAccountQuantity_QuarterofYear int
	DECLARE @ReservationAccountQuantity_SemiAnnualofYear int
	DECLARE @ReservationAccountQuantity_Year int
	DECLARE @TicketAccountQuantity_DayofYear int
	DECLARE @TicketAccountQuantity_WeekofYear int
	DECLARE @TicketAccountQuantity_MonthofYear int
	DECLARE @TicketAccountQuantity_QuarterofYear int
	DECLARE @TicketAccountQuantity_SemiAnnualofYear int
	DECLARE @TicketAccountQuantity_Year int

	DECLARE @RestrictLimit int = 99999
	DECLARE @ReservationAccountOwner int = 1
	DECLARE @TicketAccountOwner int = 2
    DECLARE @Description varchar(max)
	DECLARE @CheckOnly int = 1
	DECLARE @EX_Quantity int = 0
	DECLARE @RestrictionLimit int

	SET @PreventSale = 0  
	SET @RejectReasonErrorCode = 0
	SET @RejectType = 0
	SET	@RejectRestrictionDescription = ''
	SET @RejectRemainingAmount = 0


	if ((@PerformanceID is null) and (@EventID is null))
	BEGIN
		DECLARE Restriction_Cursor CURSOR LOCAL FOR
			select  AccountRestrictionID,
			        Description,
					ReservationAccountLimit,
					TicketAccountLimit,
					PerDayLimit,
					PerWeekLimit,
					PerMonthLimit,
					PerQuarterLimit,
					PerSemiAnnualLimit,
					PerYearLimit,
					case when ReservationAccountQuantity_DayofYear &gt; 0 then ReservationAccountQuantity_DayofYear
						else 0
					end ReservationAccountQuantity_DayofYear,
					case when ReservationAccountQuantity_WeekofYear &gt; 0 then ReservationAccountQuantity_WeekofYear
						else 0
					end ReservationAccountQuantity_WeekofYear,
					case when ReservationAccountQuantity_MonthofYear &gt; 0 then ReservationAccountQuantity_MonthofYear
						else 0
					end ReservationAccountQuantity_MonthofYear,

					case when ReservationAccountQuantity_QuarterofYear &gt; 0 then ReservationAccountQuantity_QuarterofYear
						else 0
					end ReservationAccountQuantity_QuarterofYear,
					case when ReservationAccountQuantity_SemiAnnualofYear &gt; 0 then ReservationAccountQuantity_SemiAnnualofYear
						else 0
					end ReservationAccountQuantity_SemiAnnualofYear,


					case when ReservationAccountQuantity_Year &gt; 0 then ReservationAccountQuantity_Year
						else 0
					end ReservationAccountQuantity_Year,
					case when TicketAccountQuantity_DayofYear &gt; 0 then TicketAccountQuantity_DayofYear
						else 0
					end TicketAccountQuantity_DayofYear,
					case when TicketAccountQuantity_WeekofYear &gt; 0 then TicketAccountQuantity_WeekofYear
						else 0
					end TicketAccountQuantity_WeekofYear,
					case when TicketAccountQuantity_MonthofYear &gt; 0 then TicketAccountQuantity_MonthofYear
						else 0
					end TicketAccountQuantity_MonthofYear,

					case when TicketAccountQuantity_QuarterofYear &gt; 0 then TicketAccountQuantity_QuarterofYear
						else 0
					end TicketAccountQuantity_QuarterofYear,
					case when TicketAccountQuantity_SemiAnnualofYear &gt; 0 then TicketAccountQuantity_SemiAnnualofYear
						else 0
					end TicketAccountQuantity_SemiAnnualofYear,

					case when TicketAccountQuantity_Year &gt; 0 then TicketAccountQuantity_Year
						else 0
					end TicketAccountQuantity_Year
		from (
				select distinct CNF_AccountRestriction.AccountRestrictionID,
				        CNF_AccountRestriction.Description,
						CNF_AccountRestriction.ReservationAccountLimit,
						CNF_AccountRestriction.TicketAccountLimit,
						ISNULL(CNF_AccountRestriction.PerDayLimit, @RestrictLimit) as PerDayLimit,
						ISNULL(CNF_AccountRestriction.PerWeekLimit, @RestrictLimit) as PerWeekLimit,
						ISNULL(CNF_AccountRestriction.PerMonthLimit, @RestrictLimit) as PerMonthLimit,
						ISNULL(CNF_AccountRestriction.PerQuarterLimit, @RestrictLimit) as PerQuarterLimit,
						ISNULL(CNF_AccountRestriction.PerSemiAnnualLimit, @RestrictLimit) as PerSemiAnnualLimit,
						ISNULL(CNF_AccountRestriction.PerYearLimit, @RestrictLimit) as PerYearLimit,
						ISNULL((select sum(case when cast(saledate as date) = cast(@SalesDate as date) then ReservationAccountQuantity
										else 0
									end)
								from DATA_AccountLimit
								INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
								where (DATA_AccountLimit.Accountid = @Reservation_AccountID)
									and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
									and DATA_AccountLimit.SaleDate &gt;= CNF_AccountRestriction.StartDateTime
									and data_accountlimit.Saleid &lt;&gt; @Saleid
									and Data_accountlimit.Saleitemid &lt;&gt; @Saleitemid
						), 0) ReservationAccountQuantity_DayofYear,
						ISNULL((select sum(case when (cast(datepart(yy, saledate) as varchar(4)) + '-' + cast(datepart(wk, saledate) as varchar(2))) = cast(datepart(yy, @SalesDate) as varchar(4)) + '-' + cast(datepart(wk, @SalesDate) as varchar(2)) then ReservationAccountQuantity
											else 0
										end)
								from DATA_AccountLimit
									INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
								where (DATA_AccountLimit.Accountid = @Reservation_AccountID)
								and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
								and DATA_AccountLimit.SaleDate &gt;= CNF_AccountRestriction.StartDateTime
								and data_accountlimit.Saleid &lt;&gt; @Saleid
								and Data_accountlimit.Saleitemid &lt;&gt; @Saleitemid
						), 0) ReservationAccountQuantity_WeekofYear,
						ISNULL((select sum(case when (cast(datepart(yy, saledate) as varchar(4)) + '-' + cast(datepart(mm, saledate) as varchar(2))) = cast(datepart(yy, @SalesDate) as varchar(4)) + '-' + cast(datepart(mm, @SalesDate) as varchar(2)) then ReservationAccountQuantity
											else 0
										end)
								from DATA_AccountLimit
									INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
								where (DATA_AccountLimit.Accountid = @Reservation_AccountID)
								and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
								and DATA_AccountLimit.SaleDate &gt;= CNF_AccountRestriction.StartDateTime
								and data_accountlimit.Saleid &lt;&gt; @Saleid
								and Data_accountlimit.Saleitemid &lt;&gt; @Saleitemid
						), 0) ReservationAccountQuantity_MonthofYear,

						ISNULL((select sum(case when (DATEPART(year, SaleDate) = DATEPART(year, @SalesDate)) then 
																	CASE when (DATEPART(QUARTER, SaleDate) = DATEPART(QUARTER, @SalesDate)) then ReservationAccountQuantity
																		 else 0
																	end
												else 0
											end)
								from DATA_AccountLimit
									INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
								where (DATA_AccountLimit.Accountid = @Reservation_AccountID)
								and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
								and DATA_AccountLimit.SaleDate &gt;= CNF_AccountRestriction.StartDateTime
								and data_accountlimit.Saleid &lt;&gt; @Saleid
								and Data_accountlimit.Saleitemid &lt;&gt; @Saleitemid
						), 0) ReservationAccountQuantity_QuarterofYear,

						ISNULL((select sum(case when (DATEPART(year, SaleDate) = DATEPART(year, @SalesDate)) then 
															CASE WHEN ((CASE when DATEPART(QUARTER, SaleDate) in (1, 2) then 1
																			else 2
																	end) =
																	(CASE when DATEPART(QUARTER, @SalesDate) in (1, 2) then 1
																			else 2
																	end))  then ReservationAccountQuantity
																else 0
															end 

										else 0
									end)
								from DATA_AccountLimit
									INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
								where (DATA_AccountLimit.Accountid = @Reservation_AccountID)
								and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
								and DATA_AccountLimit.SaleDate &gt;= CNF_AccountRestriction.StartDateTime
								and data_accountlimit.Saleid &lt;&gt; @Saleid
								and Data_accountlimit.Saleitemid &lt;&gt; @Saleitemid
						), 0) ReservationAccountQuantity_SemiAnnualofYear,

						ISNULL((select sum(case when (cast(datepart(yy, saledate) as varchar(4))) = cast(datepart(yy, @SalesDate) as varchar(4)) then ReservationAccountQuantity
											else 0
										end)
								from DATA_AccountLimit
								INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
								where (DATA_AccountLimit.Accountid = @Reservation_AccountID)
								and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
								and DATA_AccountLimit.SaleDate &gt;= CNF_AccountRestriction.StartDateTime
								and data_accountlimit.Saleid &lt;&gt; @Saleid
								and Data_accountlimit.Saleitemid &lt;&gt; @Saleitemid
						), 0) ReservationAccountQuantity_Year,

						ISNULL((select sum(case when cast(saledate as date) = cast(@SalesDate as date) then TicketAccountQuantity
										else 0
									end)
								from DATA_AccountLimit
									INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
								where (DATA_AccountLimit.Accountid = @Ticket_AccountID)
								and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
								and DATA_AccountLimit.SaleDate &gt;= CNF_AccountRestriction.StartDateTime
								and data_accountlimit.Saleid &lt;&gt; @Saleid
								and Data_accountlimit.Saleitemid &lt;&gt; @Saleitemid
						), 0) TicketAccountQuantity_DayofYear,
						ISNULL((select sum(case when (cast(datepart(yy, saledate) as varchar(4)) + '-' + cast(datepart(wk, saledate) as varchar(2))) = cast(datepart(yy, @SalesDate) as varchar(4)) + '-' + cast(datepart(wk, @SalesDate) as varchar(2)) then TicketAccountQuantity
											else 0
										end)
								from DATA_AccountLimit
								INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
								where (DATA_AccountLimit.Accountid = @Ticket_AccountID)
								and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
								and DATA_AccountLimit.SaleDate &gt;= CNF_AccountRestriction.StartDateTime
								and data_accountlimit.Saleid &lt;&gt; @Saleid
								and Data_accountlimit.Saleitemid &lt;&gt; @Saleitemid
						), 0) TicketAccountQuantity_WeekofYear,
						ISNULL((select sum(case when (cast(datepart(yy, saledate) as varchar(4)) + '-' + cast(datepart(mm, saledate) as varchar(2))) = cast(datepart(yy, @SalesDate) as varchar(4)) + '-' + cast(datepart(mm, @SalesDate) as varchar(2)) then TicketAccountQuantity
											else 0
										end)
								from DATA_AccountLimit
									INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
								where (DATA_AccountLimit.Accountid = @Ticket_AccountID)
								and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
								and DATA_AccountLimit.SaleDate &gt;= CNF_AccountRestriction.StartDateTime
								and data_accountlimit.Saleid &lt;&gt; @Saleid
								and Data_accountlimit.Saleitemid &lt;&gt; @Saleitemid
						), 0) TicketAccountQuantity_MonthofYear,

						ISNULL((select sum(case when (DATEPART(year, SaleDate) = DATEPART(year, @SalesDate)) then 
																	CASE when (DATEPART(QUARTER, SaleDate) = DATEPART(QUARTER, @SalesDate)) then TicketAccountQuantity
																		 else 0
																	end
												else 0
											end)
								from DATA_AccountLimit
									INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
								where (DATA_AccountLimit.Accountid = @Ticket_AccountID)
								and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
								and DATA_AccountLimit.SaleDate &gt;= CNF_AccountRestriction.StartDateTime
								and data_accountlimit.Saleid &lt;&gt; @Saleid
								and Data_accountlimit.Saleitemid &lt;&gt; @Saleitemid
						), 0) TicketAccountQuantity_QuarterofYear,

						ISNULL((select sum(case when (DATEPART(year, SaleDate) = DATEPART(year, @SalesDate)) then 
															CASE WHEN ((CASE when DATEPART(QUARTER, SaleDate) in (1, 2) then 1
																			else 2
																	end) =
																	(CASE when DATEPART(QUARTER, @SalesDate) in (1, 2) then 1
																			else 2
																	end))  then TicketAccountQuantity
																else 0
															end 

										else 0
									end)
								from DATA_AccountLimit
									INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
								where (DATA_AccountLimit.Accountid = @Ticket_AccountID)
								and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
								and DATA_AccountLimit.SaleDate &gt;= CNF_AccountRestriction.StartDateTime
								and data_accountlimit.Saleid &lt;&gt; @Saleid
								and Data_accountlimit.Saleitemid &lt;&gt; @Saleitemid
						), 0) TicketAccountQuantity_SemiAnnualofYear,


						ISNULL((select sum(case when (cast(datepart(yy, saledate) as varchar(4))) = cast(datepart(yy, @SalesDate) as varchar(4)) then TicketAccountQuantity
											else 0
										end)
								from DATA_AccountLimit
									INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
								where (DATA_AccountLimit.Accountid = @Ticket_AccountID)
								and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
								and DATA_AccountLimit.SaleDate &gt;= CNF_AccountRestriction.StartDateTime
								and data_accountlimit.Saleid &lt;&gt; @Saleid
								and Data_accountlimit.Saleitemid &lt;&gt; @Saleitemid
						), 0) TicketAccountQuantity_Year

			from CNF_AccountRestriction WITH(NOLOCK)
					LEFT JOIN CNF_AccountRestriction2Account WITH(NOLOCK)			on CNF_AccountRestriction2Account.AccountRestrictionId = CNF_AccountRestriction.AccountRestrictionId
																						and CNF_AccountRestriction2Account.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionid
																						and CNF_AccountRestriction2Account.Accountid = case when @ReservationorTicket = @ReservationAccountOwner then @Reservation_AccountID
																																							  else @Ticket_AccountID
																																						  end
					LEFT JOIN CNF_AccountRestriction2DMGCategory WITH(NOLOCK)		ON CNF_AccountRestriction2DMGCategory.dmgcategoryID = (SELECT dmgcategoryid  
																																			 from data_account DA
																																			 where DA.AccountID =  case when @ReservationorTicket = @ReservationAccountOwner then @Reservation_AccountID
																																										else @Ticket_AccountID
																																									 end
																																		   )
																						and CNF_AccountRestriction2DMGCategory.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionid


				where CNF_AccountRestriction.AccountRestrictionID = @AccountRestrictionID
					  and ((cnf_AccountRestriction2Account.accountid is not null) or (cnf_AccountRestriction2DMGCategory.dmgcategoryid is not null))
			)p
		where ((ISNULL(ReservationAccountLimit, 0) &gt; 0) or (ISNULL(TicketAccountLimit, 0) &gt; 0))


		OPEN Restriction_Cursor

		FETCH NEXT FROM Restriction_Cursor INTO
							@AccountRestrictionID, 
							@Description,
							@ReservationLimit,
							@TicketLimit,
							@PerDayLimit,
							@PerWeekLimit,
							@PerMonthLimit,
							@PerQuarterLimit,
							@PerSemiAnnualLimit,
							@PerYearLimit,
							@ReservationAccountQuantity_DayofYear,
							@ReservationAccountQuantity_WeekofYear,
							@ReservationAccountQuantity_MonthofYear,
							@ReservationAccountQuantity_QuarterofYear,
							@ReservationAccountQuantity_SemiAnnualofYear,
							@ReservationAccountQuantity_Year,
							@TicketAccountQuantity_DayofYear,
							@TicketAccountQuantity_WeekofYear,
							@TicketAccountQuantity_MonthofYear,
							@TicketAccountQuantity_QuarterofYear,
							@TicketAccountQuantity_SemiAnnualofYear,
							@TicketAccountQuantity_Year


		WHILE @@FETCH_STATUS = 0
		BEGIN
	
		IF @Quantity &lt; 0  --Always Accept a negative amounts
			BEGIN
				Set @PreventSale = 0  
				If @ReservationorTicket = @ReservationAccountOwner
				BEGIN
					INSERT INTO [dbo].[DATA_AccountLimit]
										([AccountRestrictionId]
										,[AccountId]
										,[PerformanceId]
										,[SaleId]
										,[SaleItemId]
										,[SaleDate]
										,[ReservationAccountQuantity]
										,[TicketAccountQuantity])
								VALUES
									(@AccountRestrictionID
									,@Reservation_AccountID
									,@PerformanceID
									,@SaleID
									,@SaleItemID
									,@SalesDate
									,@Quantity
									,0)
				END
				ELSE
				BEGIN
				  If @ReservationorTicket = @TicketAccountOwner
				  BEGIN

					INSERT INTO [dbo].[DATA_AccountLimit]
										([AccountRestrictionId]
										,[AccountId]
										,[PerformanceId]
										,[SaleId]
										,[SaleItemId]
										,[SaleDate]
										,[ReservationAccountQuantity]
										,[TicketAccountQuantity])
								VALUES
									(@AccountRestrictionID
									,@Reservation_AccountID
									,@PerformanceID
									,@SaleID
									,@SaleItemID
									,@SalesDate
									,0
									,@Quantity)
				  END
				  ELSE
				  BEGIN
					DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

					INSERT INTO [dbo].[DATA_AccountLimit]
										([AccountRestrictionId]
										,[AccountId]
										,[PerformanceId]
										,[SaleId]
										,[SaleItemId]
										,[SaleDate]
										,[ReservationAccountQuantity]
										,[TicketAccountQuantity])
								VALUES
									(@AccountRestrictionID
									,@Reservation_AccountID
									,@PerformanceID
									,@SaleID
									,@SaleItemID
									,@SalesDate
									,@Quantity
									,@Quantity)
					END
				END
			END


			--ReservationOwnerCheck
			If @ReservationorTicket = @ReservationAccountOwner and @ReservationLimit is not null and @PerformanceId is null 
			BEGIN
				if @Quantity &lt;= @ReservationLimit
				BEGIN
					if (((@Quantity + @ReservationAccountQuantity_DayofYear) &lt;= @PerDayLimit)   and
						((@Quantity + @ReservationAccountQuantity_WeekofYear) &lt;= @PerWeekLimit)  and
						((@Quantity + @ReservationAccountQuantity_MonthofYear) &lt;= @PerMonthLimit) and
						((@Quantity + @ReservationAccountQuantity_QuarterofYear) &lt;= @PerQuarterLimit) and
						((@Quantity + @ReservationAccountQuantity_SemiAnnualofYear) &lt;= @PerSemiAnnualLimit) and
						((@Quantity + @ReservationAccountQuantity_Year) &lt;= @PerYearLimit)) and
						 (@Quantity &lt;= (@ReservationLimit - @ReservationAccountQuantity_Year))
					BEGIN
							If @CheckforRestrictionOnly &lt;&gt; @CheckOnly
							BEGIN
									if @Ticket_AccountID is not null and @TicketLimit is null
									BEGIN
										  select @EX_Quantity = count(*)
											from data_saleitem WITH(NOLOCK)	
												INNER JOIN DATA_SaleItem2Ticket	WITH(NOLOCK)			ON data_saleitem2ticket.SaleItemId = data_saleitem.saleitemid
												INNER JOIN data_ticket WITH(NOLOCK)						ON data_ticket.ticketid = data_saleitem2ticket.ticketid

											where data_saleitem.saleitemid = @SaleitemID
											  and data_ticket.Accountid = @Ticket_AccountID	

									END

									DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

									INSERT INTO [dbo].[DATA_AccountLimit]
													([AccountRestrictionId]
													,[AccountId]
													,[PerformanceId]
													,[SaleId]
													,[SaleItemId]
													,[SaleDate]
													,[ReservationAccountQuantity]
													,[TicketAccountQuantity])
												VALUES
													(@AccountRestrictionID
													,@Reservation_AccountID
													,@PerformanceID
													,@SaleID
													,@SaleItemID
													,@SalesDate
													,@Quantity
													,@EX_Quantity)
							END
					END
					ELSE
					BEGIN
						Set @PreventSale = 1
						Set @RejectType = 1
						if @RejectReasonErrorCode = 0
						begin					    
							if ((@Quantity + @ReservationAccountQuantity_DayofYear) &gt; @PerDayLimit)
							begin
								SET @RejectRemainingAmount =  (@PerDayLimit - @ReservationAccountQuantity_DayofYear)
								SET @RejectRestrictionDescription = @Description
							
								if @RejectRemainingAmount &lt; 0 
								   SET @RejectRemainingAmount = 0

								if @RejectRemainingAmount = 0
									Set @RejectReasonErrorCode = 5075
								else
									Set @RejectReasonErrorCode = 5076
							end
						end

						if @RejectReasonErrorCode = 0
						begin
							if ((@Quantity + @ReservationAccountQuantity_WeekofYear) &gt; @PerWeekLimit)
							begin
								SET @RejectRemainingAmount =  (@PerWeekLimit - @ReservationAccountQuantity_WeekofYear) 
								SET @RejectRestrictionDescription = @Description
								if @RejectRemainingAmount &lt; 0 
								   SET @RejectRemainingAmount = 0

								if @RejectRemainingAmount = 0
									Set @RejectReasonErrorCode = 5077
								else
									Set @RejectReasonErrorCode = 5078
							end
						end

						if @RejectReasonErrorCode = 0
						begin
							if ((@Quantity + @ReservationAccountQuantity_MonthofYear) &gt; @PerMonthLimit)
							begin
								SET @RejectRemainingAmount =  (@PerMonthLimit - @ReservationAccountQuantity_MonthofYear) 
								SET @RejectRestrictionDescription = @Description
								if @RejectRemainingAmount &lt; 0 
								   SET @RejectRemainingAmount = 0

								if @RejectRemainingAmount = 0   							 
									Set @RejectReasonErrorCode = 5079
								else
									Set @RejectReasonErrorCode = 5080	
							end
						end

						if @RejectReasonErrorCode = 0
						begin
							if ((@Quantity + @ReservationAccountQuantity_QuarterofYear) &gt; @PerQuarterLimit)
							begin
								SET @RejectRemainingAmount =  (@PerQuarterLimit - @ReservationAccountQuantity_QuarterofYear) 
								SET @RejectRestrictionDescription = @Description
								if @RejectRemainingAmount &lt; 0 
								   SET @RejectRemainingAmount = 0

								if @RejectRemainingAmount = 0   							 
									Set @RejectReasonErrorCode = 5090
								else
									Set @RejectReasonErrorCode = 5091	
							end
						end

						if @RejectReasonErrorCode = 0
						begin
							if ((@Quantity + @ReservationAccountQuantity_SemiAnnualofYear) &gt; @PerSemiAnnualLimit)
							begin
								SET @RejectRemainingAmount =  (@PerSemiAnnualLimit - @ReservationAccountQuantity_SemiAnnualofYear) 
								SET @RejectRestrictionDescription = @Description
								if @RejectRemainingAmount &lt; 0 
								   SET @RejectRemainingAmount = 0

								if @RejectRemainingAmount = 0   							 
									Set @RejectReasonErrorCode = 5092
								else
									Set @RejectReasonErrorCode = 5093	
							end
						end

						if @RejectReasonErrorCode = 0
						begin
							if ((@Quantity + @ReservationAccountQuantity_Year) &gt; @PerYearLimit) 
							begin
								SET @RejectRemainingAmount =  (@PerYearLimit - @ReservationAccountQuantity_Year)
								SET @RejectRestrictionDescription = @Description 
								if @RejectRemainingAmount &lt; 0 
								   SET @RejectRemainingAmount = 0

								if @RejectRemainingAmount = 0
									Set @RejectReasonErrorCode = 5081
								else
									Set @RejectReasonErrorCode = 5082
							end
						end

						if @RejectReasonErrorCode = 0
						begin
							if ((@Quantity + @ReservationAccountQuantity_Year) &gt; @ReservationLimit) 
							begin
								SET @RejectRemainingAmount =  (@ReservationLimit - @ReservationAccountQuantity_Year)
								SET @RejectRestrictionDescription = @Description 
								if @RejectRemainingAmount &lt; 0 
								   SET @RejectRemainingAmount = 0

								if @RejectRemainingAmount = 0
									Set @RejectReasonErrorCode = 5083
								else
									Set @RejectReasonErrorCode = 5084
							end
						end

					END
				END
				ELSE
				BEGIN
					Set @PreventSale = 1
					Set @RejectType = 1
					if @RejectReasonErrorCode = 0
					begin
						SET @RejectRemainingAmount =  (@ReservationLimit - @ReservationAccountQuantity_Year)
						SET @RejectRestrictionDescription = @Description 
						if @RejectRemainingAmount &lt; 0 
							SET @RejectRemainingAmount = 0

						if @RejectRemainingAmount = 0
							Set @RejectReasonErrorCode = 5085
						else
							Set @RejectReasonErrorCode = 5086
					end
				END
			END

	--TicketOwnerCheck
			if @ReservationorTicket = @TicketAccountOwner and @TicketLimit is not null and @PerformanceId is null 
			BEGIN
				if @Quantity &lt;= @TicketLimit
				BEGIN
					if (((@Quantity + @TicketAccountQuantity_DayofYear) &lt;= @PerDayLimit)   and
						((@Quantity + @TicketAccountQuantity_WeekofYear) &lt;= @PerWeekLimit)  and
						((@Quantity + @TicketAccountQuantity_MonthofYear) &lt;= @PerMonthLimit) and
						((@Quantity + @TicketAccountQuantity_QuarterofYear) &lt;= @PerQuarterLimit) and
						((@Quantity + @TicketAccountQuantity_SemiAnnualofYear) &lt;= @PerSemiAnnualLimit) and
						((@Quantity + @TicketAccountQuantity_Year) &lt;= @PerYearLimit)) and
						(@Quantity &lt;= (@TicketLimit - @TicketAccountQuantity_Year))
					BEGIN
							If @CheckforRestrictionOnly &lt;&gt; @CheckOnly
							BEGIN

									if @Reservation_AccountID is not null and @ReservationLimit is null
									BEGIN
										  select @EX_Quantity = count(*)
											from data_reservation

											where data_reservation.saleid = @SaleID
											  and data_reservation.Accountid = @Reservation_AccountID	

									END

									DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

									INSERT INTO [dbo].[DATA_AccountLimit]
													([AccountRestrictionId]
													,[AccountId]
													,[PerformanceId]
													,[SaleId]
													,[SaleItemId]
													,[SaleDate]
													,[ReservationAccountQuantity]
													,[TicketAccountQuantity])
												VALUES
													(@AccountRestrictionID
													,@Ticket_AccountID
													,@PerformanceID
													,@SaleID
													,@SaleItemID
													,@SalesDate
													,@EX_Quantity
													,@Quantity)
							END
					END
					ELSE
					BEGIN
						Set @PreventSale = 1
						Set @RejectType = 2
						if @RejectReasonErrorCode = 0
						begin
							if ((@Quantity + @TicketAccountQuantity_DayofYear) &gt; @PerDayLimit)
							begin
								SET @RejectRemainingAmount =  (@PerDayLimit - @TicketAccountQuantity_DayofYear)
								SET @RejectRestrictionDescription = @Description
								if @RejectRemainingAmount &lt; 0 
								   SET @RejectRemainingAmount = 0

								if @RejectRemainingAmount = 0
									Set @RejectReasonErrorCode = 5075
								else
									Set @RejectReasonErrorCode = 5076
							end
						end
						if @RejectReasonErrorCode = 0
						begin
							if ((@Quantity + @TicketAccountQuantity_WeekofYear) &gt; @PerWeekLimit) 
							begin
								SET @RejectRemainingAmount =  (@PerWeekLimit - @TicketAccountQuantity_WeekofYear)
								SET @RejectRestrictionDescription = @Description
								if @RejectRemainingAmount &lt; 0 
								   SET @RejectRemainingAmount = 0

								if @RejectRemainingAmount = 0
									Set @RejectReasonErrorCode = 5077
								else
									Set @RejectReasonErrorCode = 5078
							end
						end
						if @RejectReasonErrorCode = 0
						begin
							if ((@Quantity + @TicketAccountQuantity_MonthofYear) &gt; @PerMonthLimit) 
							Begin
								SET @RejectRemainingAmount =  (@PerMonthLimit - @TicketAccountQuantity_MonthofYear)
								SET @RejectRestrictionDescription = @Description
								if @RejectRemainingAmount &lt; 0 
								   SET @RejectRemainingAmount = 0
							
								if @RejectRemainingAmount = 0
									Set @RejectReasonErrorCode = 5079
								else
									Set @RejectReasonErrorCode = 5080
							end
						end

						if @RejectReasonErrorCode = 0
						begin
							if ((@Quantity + @TicketAccountQuantity_QuarterofYear) &gt; @PerQuarterLimit) 
							Begin
								SET @RejectRemainingAmount =  (@PerQuarterLimit - @TicketAccountQuantity_QuarterofYear)
								SET @RejectRestrictionDescription = @Description
								if @RejectRemainingAmount &lt; 0 
								   SET @RejectRemainingAmount = 0
							
								if @RejectRemainingAmount = 0
									Set @RejectReasonErrorCode = 5090
								else
									Set @RejectReasonErrorCode = 5091
							end
						end

						if @RejectReasonErrorCode = 0
						begin
							if ((@Quantity + @TicketAccountQuantity_SemiAnnualofYear) &gt; @PerSemiAnnualLimit) 
							Begin
								SET @RejectRemainingAmount =  (@PerSemiAnnualLimit - @TicketAccountQuantity_SemiAnnualofYear)
								SET @RejectRestrictionDescription = @Description
								if @RejectRemainingAmount &lt; 0 
								   SET @RejectRemainingAmount = 0
							
								if @RejectRemainingAmount = 0
									Set @RejectReasonErrorCode = 5092
								else
									Set @RejectReasonErrorCode = 5093
							end
						end

						if @RejectReasonErrorCode = 0
						begin
							if ((@Quantity + @TicketAccountQuantity_Year) &gt; @PerYearLimit) 
							begin
								SET @RejectRemainingAmount =  (@PerYearLimit - @TicketAccountQuantity_Year)
								SET @RejectRestrictionDescription = @Description
								if @RejectRemainingAmount &lt; 0 
								   SET @RejectRemainingAmount = 0
							
								if @RejectRemainingAmount = 0
									Set @RejectReasonErrorCode = 5081
								else
									Set @RejectReasonErrorCode = 5082
							end
						end
						if @RejectReasonErrorCode = 0
						begin
							if ((@Quantity + @TicketAccountQuantity_Year) &gt; @TicketLimit) 
							begin
								SET @RejectRemainingAmount =  (@TicketLimit - @TicketAccountQuantity_Year)
								SET @RejectRestrictionDescription = @Description 
								if @RejectRemainingAmount &lt; 0 
								   SET @RejectRemainingAmount = 0

								if @RejectRemainingAmount = 0
									Set @RejectReasonErrorCode = 5083
								else
									Set @RejectReasonErrorCode = 5084
							end
						end
					END
				END
				ELSE
				BEGIN
					Set @PreventSale = 1
					Set @RejectType = 2
					if @RejectReasonErrorCode = 0
					begin
						SET @RejectRemainingAmount =  (@TicketLimit - @TicketAccountQuantity_Year)
						SET @RejectRestrictionDescription = @Description
						if @RejectRemainingAmount &lt; 0 
							SET @RejectRemainingAmount = 0

						if @RejectRemainingAmount = 0		   					 
							Set @RejectReasonErrorCode = 5085
						else
							Set @RejectReasonErrorCode = 5086
					end
				END
			END





		FETCH NEXT FROM Restriction_Cursor INTO
							@AccountRestrictionID, 
							@Description,
							@ReservationLimit,
							@TicketLimit,
							@PerDayLimit,
							@PerWeekLimit,
							@PerMonthLimit,
							@PerQuarterLimit,
							@PerSemiAnnualLimit,
							@PerYearLimit,
							@ReservationAccountQuantity_DayofYear,
							@ReservationAccountQuantity_WeekofYear,
							@ReservationAccountQuantity_MonthofYear,
							@ReservationAccountQuantity_QuarterofYear,
							@ReservationAccountQuantity_SemiAnnualofYear,
							@ReservationAccountQuantity_Year,
							@TicketAccountQuantity_DayofYear,
							@TicketAccountQuantity_WeekofYear,
							@TicketAccountQuantity_MonthofYear,
							@TicketAccountQuantity_QuarterofYear,
							@TicketAccountQuantity_SemiAnnualofYear,
							@TicketAccountQuantity_Year


		END	
	
		CLOSE Restriction_Cursor;
		DEALLOCATE Restriction_Cursor;
	END

RETURN
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_CheckAccountRestrictions]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_CheckAccountRestrictions</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>CREATE PROCEDURE [otn_sp_CheckAccountRestrictions]  (
                                                      @Restriction_Check         Restriction_Table READONLY,
													  @GUID                      varchar(100)
                                                    ) 
AS    
BEGIN

	DECLARE @PreventSale int = 0
	DECLARE @RejectReasonErrorCode int = 0
	DECLARE @RejectRestrictionDescription varchar(100) = ''
	DECLARE @RejectRemainingAmount int = 0
	DECLARE @RejectType int = 0
	DECLARE @sql varchar(250) = ''


--Reservation Owner Check by Ticket
	exec otn_sp_AR_ReservationOwner_Matrixcell @Restriction_Check, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT

--Ticket Owner Check by Ticket
  	If @PreventSale = 0  
       exec otn_sp_AR_TicketOwner_Matrixcell @Restriction_Check, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT

--Reservation Owner Check by Performance/Event
  	If @PreventSale = 0  
	   exec otn_sp_AR_ReservationOwner_Performance @Restriction_Check, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT

--Ticket Owner Check by Performance/Event
  	If @PreventSale = 0  
	   exec otn_sp_AR_TicketOwner_Performance @Restriction_Check, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT


	SET @sql =  'IF OBJECT_ID(''tempdb..#' + @GUID + ''') IS NOT NULL drop table #' + @GUID

	EXEC(@sql)

	select @PreventSale as PreventSale, 
	       @RejectReasonErrorCode as RejectReasonErrorCode, 
		   @RejectType as RejectType,
	       @RejectRestrictionDescription as RejectRestrictionDescription,
	       @RejectRemainingAmount as RejectRemainingAmount

END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_GetAccountRestrictions]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_GetAccountRestrictions</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>CREATE Procedure [dbo].[otn_sp_GetAccountRestrictions]( @AccountRestrictionID int,
                                                        @Quantity int,														
														@ReservationorTicket int,
														@RestrictionType int,
														@Reservation_AccountID int,
														@Ticket_AccountID int,
														@PerformanceID int,
														@EventID int,
														@SaleID int,
														@SaleItemID int,
														@CheckforRestrictionOnly int,
														@PreventSale int OUTPUT,
														@RejectReasonErrorCode int OUTPUT,
														@RejectType int OUTPUT,
														@RejectRestrictionDescription varchar(100) OUTPUT,
														@RejectRemainingAmount int OUTPUT
														)  

AS    
BEGIN

	Exec otn_sp_GetAccountRestrictions_MatrixCell   @AccountRestrictionID,
													@Quantity,														
													@ReservationorTicket,
													@RestrictionType,
													@Reservation_AccountID,
													@Ticket_AccountID,
													@PerformanceID,
													@EventID,
													@SaleID,
													@SaleItemID,
													@CheckforRestrictionOnly,
													@PreventSale OUTPUT,
													@RejectReasonErrorCode OUTPUT,
													@RejectType OUTPUT,
													@RejectRestrictionDescription OUTPUT,
													@RejectRemainingAmount OUTPUT

	if @PreventSale = 0 
	BEGIN
		Exec otn_sp_GetAccountRestrictions_Performance   @AccountRestrictionID,
														 @Quantity,														
														 @ReservationorTicket,
														 @RestrictionType,
														 @Reservation_AccountID,
														 @Ticket_AccountID,
														 @PerformanceID,
														 @EventID,
														 @SaleID,
														 @SaleItemID,
														 @CheckforRestrictionOnly,
														 @PreventSale OUTPUT,
														 @RejectReasonErrorCode OUTPUT,
														 @RejectType OUTPUT,
														 @RejectRestrictionDescription OUTPUT,
														 @RejectRemainingAmount OUTPUT

	END
	
RETURN;
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fdipalma</ADDEDBY><SQLVERSION>3214</SQLVERSION><RMTRACKLINK>IDBOS-2600</RMTRACKLINK><REASON>White List Enhancement for the Offline (API)</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT 1 FROM sys.procedures 
          WHERE Name = 'otn_sp_WhiteList_Import')
	DROP PROCEDURE otn_sp_WhiteList_Import</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>create procedure [otn_sp_WhiteList_Import]
	@IdentifierCode varchar(400),
    @IdentifierType smallint,
	@VoidType smallint,
	@MatrixCellId int,
	@ValidityXML ntext
as
begin
	DECLARE @c int

	select @c = COUNT(IdentifierCode) from OFF_WhiteListTck where IdentifierCode = @IdentifierCode

	IF (@c = 0)
	begin
		insert into OFF_WhiteListTck (
		IdentifierCode,
		IdentifierType,
        VoidType,
		MatrixCellId,
		ValidityXML
		) values (
		@IdentifierCode,
        @IdentifierType,
		@VoidType,
		@MatrixCellId,
		@ValidityXML
		)
	end
	else
	begin
		update OFF_WhiteListTck
		set
        IdentifierType=@IdentifierType,
		VoidType=@VoidType,
		MatrixCellId=@MatrixCellId,
		ValidityXML=@ValidityXML
		where
		IdentifierCode=@IdentifierCode
	end

end</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>scoluccia</ADDEDBY><SQLVERSION>3213</SQLVERSION><RMTRACKLINK>IDBOS-2598</RMTRACKLINK><REASON>Add Field "IdentifierType" in table OFF_WhiteListTck</REASON><TABLENAMES>OFF_WhiteListTck=WhiteListTckId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
          WHERE Name = N'IdentifierType' 
          AND OBJECT_ID = OBJECT_ID(N'OFF_WhiteListTck'))
BEGIN
  ALTER TABLE OFF_WhiteListTck
  ADD IdentifierType Smallint Default 5 NOT NULL
END      </SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fdipalma</ADDEDBY><SQLVERSION>3212</SQLVERSION><RMTRACKLINK>IDBOS-2600</RMTRACKLINK><REASON>White List Enhancement for the Offline (API)</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT 1 FROM sys.procedures 
          WHERE Name = 'otn_sp_WhiteList_Import')
	DROP PROCEDURE otn_sp_WhiteList_Import</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>create procedure [otn_sp_WhiteList_Import]
	@IdentifierCode varchar(400),
	@VoidType smallint,
	@MatrixCellId int,
	@ValidityXML ntext
as
begin
	DECLARE @c int

	select @c = COUNT(IdentifierCode) from OFF_WhiteListTck where IdentifierCode = @IdentifierCode

	IF (@c = 0)
	begin
		insert into OFF_WhiteListTck (
		IdentifierCode,
        VoidType,
		MatrixCellId,
		ValidityXML
		) values (
		@IdentifierCode,
		@VoidType,
		@MatrixCellId,
		@ValidityXML
		)
	end
	else
	begin
		update OFF_WhiteListTck
		set
		VoidType=@VoidType,
		MatrixCellId=@MatrixCellId,
		ValidityXML=@ValidityXML
		where
		IdentifierCode=@IdentifierCode
	end

end</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>scoluccia</ADDEDBY><SQLVERSION>3211</SQLVERSION><RMTRACKLINK>IDBOS-2598</RMTRACKLINK><REASON>Created a new table OFF_WhiteLIstTck in order to manage the external tickets for the access control in offline mode.</REASON><TABLENAMES>OFF_WhiteListTck=WhiteListTckId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND TABLE_NAME = 'OFF_WhiteListTck')
BEGIN
Create table OFF_WhiteListTck
(
	[WhiteListTckId]    Integer IDENTITY(1,1) NOT NULL,
	[IdentifierCode] [varchar](400) NOT NULL,
        [VoidType] [smallint] NOT NULL,
	[MatrixCellId] [int] NULL,
	[ValidityXML] [ntext] NULL
Primary Key ([WhiteListTckId])
) 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT object_id
               FROM sys.indexes
               WHERE Name = 'Idx_OFF_WhiteListTck_IdentifierCode')
BEGIN
	CREATE NONCLUSTERED INDEX [Idx_OFF_WhiteListTck_IdentifierCode] ON [dbo].[OFF_WhiteListTck]
	(
		[IdentifierCode] ASC
	)
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>ecandido</ADDEDBY><SQLVERSION>3210</SQLVERSION><RMTRACKLINK>IDBOS-1468</RMTRACKLINK><REASON>Resource Management - Flag instructor as 'requested by guest'</REASON><TABLENAMES>RES_Schedule=ScheduleId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
          WHERE Name = N'ResourceReqByGuest' 
          AND OBJECT_ID = OBJECT_ID(N'RES_Schedule'))
BEGIN
  ALTER TABLE RES_Schedule
  ADD ResourceReqByGuest Integer
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>3209</SQLVERSION><RMTRACKLINK>IDBOS-2432</RMTRACKLINK><REASON>Sale Restriction cyclical validity ( Staff Tickets )</REASON><TABLENAMES>CNF_AccountRestriction=AccountRestrictionId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
          WHERE Name = N'PerQuarterLimit' 
          AND OBJECT_ID = OBJECT_ID(N'CNF_AccountRestriction'))
BEGIN
  ALTER TABLE CNF_AccountRestriction
  ADD PerQuarterLimit Integer
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
          WHERE Name = N'PerSemiAnnualLimit' 
          AND OBJECT_ID = OBJECT_ID(N'CNF_AccountRestriction'))
BEGIN
  ALTER TABLE CNF_AccountRestriction
  ADD PerSemiAnnualLimit Integer
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>scoluccia</ADDEDBY><SQLVERSION>3208</SQLVERSION><RMTRACKLINK>IDBOS-769</RMTRACKLINK><REASON>Renamed Field "SalesTimeCounter"  to ""SaleElapsedTime" in table DATA_Sale</REASON><TABLENAMES>DATA_Sale=SaleId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT * FROM sys.columns
          WHERE Name = N'SalesTimeCounter' 
          AND OBJECT_ID = OBJECT_ID(N'DATA_Sale'))
BEGIN
  ALTER TABLE DATA_Sale
  DROP COLUMN SalesTimeCounter
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
          WHERE Name = N'SalesElapsedTime' 
          AND OBJECT_ID = OBJECT_ID(N'DATA_Sale'))
BEGIN
  ALTER TABLE DATA_Sale
  ADD SalesElapsedTime Time(0)
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>scoluccia</ADDEDBY><SQLVERSION>3207</SQLVERSION><RMTRACKLINK>IDBOS-769</RMTRACKLINK><REASON>Add Field "SalesTimeCounter" in table DATA_Sale</REASON><TABLENAMES>DATA_Sale=SaleId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
          WHERE Name = N'SalesTimeCounter' 
          AND OBJECT_ID = OBJECT_ID(N'DATA_Sale'))
BEGIN
  ALTER TABLE DATA_Sale
  ADD SalesTimeCounter Time(0)
END             </SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dchen</ADDEDBY><SQLVERSION>3206</SQLVERSION><RMTRACKLINK>IDBOS-2093</RMTRACKLINK><REASON>IDBOS-2093 - Wait List for sold out Events / Performances
  *   Add columns for SpaceStructureID and EnvelopeID
  ** Add non-clustered index for CNF_Performance.WaitListEnabled</REASON><TABLENAMES>DATA_WaitList_Subscriptions=WaitListSubscriptionId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'WaitListSubscriptionSpaceStructureID' 
                      AND OBJECT_ID = OBJECT_ID(N'DATA_WaitList_Subscriptions'))
BEGIN
  ALTER TABLE DATA_WaitList_Subscriptions
  ADD WaitListSubscriptionSpaceStructureID integer 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'WaitListSubscriptionEnvelopeID' 
                      AND OBJECT_ID = OBJECT_ID(N'DATA_WaitList_Subscriptions'))
BEGIN
  ALTER TABLE DATA_WaitList_Subscriptions
  ADD WaitListSubscriptionEnvelopeID integer 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS ( SELECT * FROM sys.indexes 
                WHERE name='idx_CNF_Performance_WaitListEnabled' AND object_id = OBJECT_ID('CNF_Performance'))
BEGIN                          
  CREATE NONCLUSTERED INDEX [idx_CNF_Performance_WaitListEnabled] 
  ON [CNF_Performance]([WaitListEnabled] DESC,[PerformanceId] ASC,[PerformanceAK] ASC)
END
</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>3205</SQLVERSION><RMTRACKLINK>IDBOS-2262</RMTRACKLINK><REASON>Adding and modifying some indexes

[0] Idx_DATA_SaleItemRule_SaleItem
[1] Idx_DATA_SaleItemRule_DATA_SaleItemId
[2] Idx_DATA_SI2T_TicketId_SaleItemId
[3] idxTicket2Media_TicketId
[4] Idx_Trn2Tck_TrnId_TckId
[5] Idx_Ticket2Media_TicketId_MediaId
[6] Idx_Account_Id_BillingId
[7] Idx_Ledger_AccountId_RefId
[8] FKIdx1</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT object_id
               FROM sys.indexes
               WHERE Name = 'Idx_DATA_SaleItemRule_SaleItem')
BEGIN
	CREATE NONCLUSTERED INDEX [Idx_DATA_SaleItemRule_SaleItem] ON [dbo].[DATA_SaleItemRule]
	(
		[SaleItemRuleId] DESC,
		[PromotionItemRuleId] DESC,
		[SaleItemId] DESC
	)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT object_id
           FROM sys.indexes
           WHERE Name = 'Idx_DATA_SaleItemRule_DATA_SaleItemId')
BEGIN
	DROP INDEX [Idx_DATA_SaleItemRule_DATA_SaleItemId] ON [dbo].[DATA_SaleItemRule]
END 

IF NOT EXISTS (SELECT object_id
               FROM sys.indexes
               WHERE Name = 'Idx_DATA_SaleItemRule_DATA_SaleItemId')
BEGIN
	CREATE NONCLUSTERED INDEX [Idx_DATA_SaleItemRule_DATA_SaleItemId] ON [dbo].[DATA_SaleItemRule]
	(
		[SaleItemId] DESC
	)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT object_id
               FROM sys.indexes
               WHERE Name = 'Idx_DATA_SI2T_TicketId_SaleItemId')
BEGIN
	CREATE NONCLUSTERED INDEX [Idx_DATA_SI2T_TicketId_SaleItemId] ON [dbo].[DATA_SaleItem2Ticket]
	(
		[TicketId] DESC,
		[SaleItemId] DESC
	)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT object_id
           FROM sys.indexes
           WHERE Name = 'idxTicket2Media_TicketId')
BEGIN
	DROP INDEX [idxTicket2Media_TicketId] ON [dbo].[DATA_Ticket2Media]
END

IF NOT EXISTS (SELECT object_id
               FROM sys.indexes
               WHERE Name = 'idxTicket2Media_TicketId')
BEGIN
	CREATE NONCLUSTERED INDEX [idxTicket2Media_TicketId] ON [dbo].[DATA_Ticket2Media]
	(
		[TicketId] DESC
	)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT object_id
               FROM sys.indexes
               WHERE Name = 'Idx_Trn2Tck_TrnId_TckId')
BEGIN
	CREATE NONCLUSTERED INDEX [Idx_Trn2Tck_TrnId_TckId] ON [dbo].[DATA_Transaction2Ticket]
	(
		[TransactionId] DESC,
		[TicketId] DESC
	)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT object_id
               FROM sys.indexes
               WHERE Name = 'Idx_Ticket2Media_TicketId_MediaId')
BEGIN
	CREATE NONCLUSTERED INDEX [Idx_Ticket2Media_TicketId_MediaId] ON [dbo].[DATA_Ticket2Media]
	(
		[MediaId] DESC,
		[TicketId] DESC
	)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT object_id
               FROM sys.indexes
               WHERE Name = 'Idx_Account_Id_BillingId')
BEGIN
	CREATE NONCLUSTERED INDEX [Idx_Account_Id_BillingId] ON [dbo].[DATA_Account]
	(
		[AccountId] DESC,
		[BillingAccountId] DESC
	)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT> IF NOT EXISTS (SELECT object_id
               FROM sys.indexes
               WHERE Name = 'Idx_Ledger_AccountId_RefId')
BEGIN
	CREATE NONCLUSTERED INDEX [Idx_Ledger_AccountId_RefId] ON [dbo].[DATA_Ledger]
	(
		[AccountId] DESC,
		[ReferenceId] DESC
	)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (select 1
from sys.objects t
    inner join sys.indexes i
        on t.object_id = i.object_id
    cross apply (select col.[name] + ', '
                    from sys.index_columns ic
                        inner join sys.columns col
                            on ic.object_id = col.object_id
                            and ic.column_id = col.column_id
                    where ic.object_id = t.object_id
                        and ic.index_id = i.index_id
                            order by col.column_id
                            for xml path ('') ) D (column_names)
where t.is_ms_shipped &lt;&gt; 1
and index_id &gt; 0
and i.[name] = 'FKIdx1'
and t.[name] = 'DATA_Payment')
BEGIN
	DROP INDEX [FKIdx1] ON [dbo].[DATA_Payment]
END 

IF NOT EXISTS (select 1
from sys.objects t
    inner join sys.indexes i
        on t.object_id = i.object_id
    cross apply (select col.[name] + ', '
                    from sys.index_columns ic
                        inner join sys.columns col
                            on ic.object_id = col.object_id
                            and ic.column_id = col.column_id
                    where ic.object_id = t.object_id
                        and ic.index_id = i.index_id
                            order by col.column_id
                            for xml path ('') ) D (column_names)
where t.is_ms_shipped &lt;&gt; 1
and index_id &gt; 0
and i.[name] = 'FKIdx1'
and t.[name] = 'DATA_Payment')
BEGIN
	CREATE NONCLUSTERED INDEX [FKIdx1] ON [dbo].[DATA_Payment]
	(
		[TransactionId] DESC
	)
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>3204</SQLVERSION><RMTRACKLINK>IDBOS-2300</RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND TABLE_NAME = 'Data_SaleLimitRestriction')
BEGIN
	DROP table Data_SaleLimitRestriction
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND TABLE_NAME = 'Data_SaleLimit2Matrixcell')
BEGIN
	DROP table Data_SaleLimit2Matrixcell
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND TABLE_NAME = 'Data_SaleLimit')
BEGIN
	DROP table Data_SaleLimit
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND TABLE_NAME = 'CNF_SaleRestrictionValidity')
BEGIN
	DROP table CNF_SaleRestrictionValidity
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND TABLE_NAME = 'CNF_SaleRestriction2MatrixCell')
BEGIN
	DROP table CNF_SaleRestriction2MatrixCell
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND TABLE_NAME = 'CNF_SaleRestriction')
BEGIN
	DROP table CNF_SaleRestriction
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dchen</ADDEDBY><SQLVERSION>3203</SQLVERSION><RMTRACKLINK>IDBOS-2093</RMTRACKLINK><REASON>IDBOS-2093 - Wait List for sold out Events / Performances
  * Adding column WaitListSubscriptionSeatCategoryID to DATA_WaitList_Subscriptions</REASON><TABLENAMES>DATA_WaitList_Subscriptions=WaitListSubscriptionId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'WaitListSubscriptionSeatCategoryID' 
                      AND OBJECT_ID = OBJECT_ID(N'DATA_WaitList_Subscriptions'))
BEGIN
  ALTER TABLE DATA_WaitList_Subscriptions
  ADD WaitListSubscriptionSeatCategoryID integer
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3202</SQLVERSION><RMTRACKLINK>IDBOS-2420</RMTRACKLINK><REASON>0) Changed dimension of  FormName Column</REASON><TABLENAMES>CNF_FormSettings=SettingId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT * FROM sys.columns
          WHERE Name = N'FormName' 
          AND OBJECT_ID = OBJECT_ID(N'CNF_FormSettings'))
BEGIN
  ALTER TABLE CNF_FormSettings
  ALTER COLUMN FormName VarChar(100) NOT NULL 
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dchen</ADDEDBY><SQLVERSION>3201</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>IDBOS-2093 - Wait List for sold out Events / Performances
  * Alter column WaitListEnabled to CNF_Event and CNF_Performance removing not null</REASON><TABLENAMES>CNF_Performance=PerformanceId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT * FROM sys.columns
          WHERE Name = N'WaitListEnabled' 
          AND OBJECT_ID = OBJECT_ID(N'CNF_Performance'))
BEGIN
  ALTER TABLE CNF_Performance ALTER COLUMN WaitListEnabled Smallint
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT * FROM sys.columns
          WHERE Name = N'WaitListEnabled' 
          AND OBJECT_ID = OBJECT_ID(N'CNF_Event'))
BEGIN
  ALTER TABLE CNF_Event ALTER COLUMN WaitListEnabled Smallint
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dchen</ADDEDBY><SQLVERSION>3200</SQLVERSION><RMTRACKLINK>IDBOS-2093</RMTRACKLINK><REASON>IDBOS-2093 - Wait List for sold out Events / Performances
  * Adding column WaitListEnabled to CNF_Event and CNF_Performance</REASON><TABLENAMES>CNF_Event=EventId
CNF_Performance=PerformanceId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
          WHERE Name = N'WaitListEnabled' 
          AND OBJECT_ID = OBJECT_ID(N'CNF_Event'))
BEGIN
  ALTER TABLE CNF_Event ADD WaitListEnabled Smallint Default 0 NOT NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
          WHERE Name = N'WaitListEnabled' 
          AND OBJECT_ID = OBJECT_ID(N'CNF_Performance'))
BEGIN
  ALTER TABLE CNF_Performance ADD WaitListEnabled Smallint Default 0 NOT NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3199</SQLVERSION><RMTRACKLINK>IDBOS-2461</RMTRACKLINK><REASON>0) Removed Column DllName from CNF_Driver</REASON><TABLENAMES>CNF_Driver=DriverId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT * FROM sys.columns
          WHERE Name = N'DllName' 
          AND OBJECT_ID = OBJECT_ID(N'CNF_Driver'))
BEGIN
  ALTER TABLE CNF_Driver
  DROP COLUMN DllName
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3198</SQLVERSION><RMTRACKLINK>IDBOS-2420</RMTRACKLINK><REASON>Created a new table in order to save the forms layout settings in Json format.</REASON><TABLENAMES>CNF_FormSettings=SettingId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND TABLE_NAME = 'CNF_FormSettings')
BEGIN
Create table CNF_FormSettings
(
	[SettingId]    Integer IDENTITY(1,1) NOT NULL,
	[UserName]     VarChar(50) NOT NULL,
	[FormName]     VarChar(25) NOT NULL,
	[SettingValue] VarChar(4000) NULL
Primary Key ([SettingId])
) 
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>scoluccia</ADDEDBY><SQLVERSION>3197</SQLVERSION><RMTRACKLINK>IDBOS-2377</RMTRACKLINK><REASON>Add Field "ItemGuid" in table DATA_SaleItem</REASON><TABLENAMES>DATA_SaleItem=SaleItemId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'ItemGuid' AND
                Object_ID  = Object_ID(N'DATA_SaleItem'))
BEGIN
  ALTER TABLE DATA_SaleItem 
  ADD ItemGuid varchar(38) NULL
END
</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dchen</ADDEDBY><SQLVERSION>3196</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>IDBOS-2093 - Wait List for sold out Events / Performances
  * Missed Tables modified</REASON><TABLENAMES>DATA_WaitList_Subscriptions=WaitListSubscriptionId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'WaitListSubscriptionPerformanceAK' 
                      AND OBJECT_ID = OBJECT_ID(N'DATA_WaitList_Subscriptions'))
BEGIN
  ALTER TABLE DATA_WaitList_Subscriptions
  ADD WaitListSubscriptionPerformanceAK nvarchar(100) NOT NULL 
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dchen</ADDEDBY><SQLVERSION>3195</SQLVERSION><RMTRACKLINK>IDBOS-2093</RMTRACKLINK><REASON>IDBOS-2093 - Wait List for sold out Events / Performances
  * Alter Column</REASON><TABLENAMES>DATA_WaitList_Subscriptions=WaitListSubscriptionId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS ( SELECT * FROM sys.indexes 
            WHERE name='IX_DATA_WaitList_Subscriptions_Subscriber' AND object_id = OBJECT_ID('DATA_WaitList_Subscriptions'))
BEGIN
  DROP INDEX IX_DATA_WaitList_Subscriptions_Subscriber ON DATA_WaitList_Subscriptions
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT * FROM sys.columns
          WHERE Name = N'WaitListSubscriptionPerformanceID' 
          AND OBJECT_ID = OBJECT_ID(N'DATA_WaitList_Subscriptions'))
BEGIN
  ALTER TABLE DATA_WaitList_Subscriptions
  DROP COLUMN WaitListSubscriptionPerformanceID
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'WaitListSubscriptionPerformanceAK' 
                      AND OBJECT_ID = OBJECT_ID(N'DATA_WaitList_Subscriptions'))
BEGIN
  ALTER TABLE DATA_WaitList_Subscriptions
  ADD WaitListSubscriptionPerformanceAK nvarchar(100) NOT NULL 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT> IF NOT EXISTS (	SELECT object_id 
		FROM sys.indexes
		WHERE Name = 'IX_DATA_WaitList_Subscriptions_Subscriber')
BEGIN
    CREATE UNIQUE NONCLUSTERED INDEX [IX_DATA_WaitList_Subscriptions_Subscriber] 
    ON [dbo].[DATA_WaitList_Subscriptions]
    (
	[WaitListSubscriptionEmail] ASC,
	[WaitListSubscriptionPerformanceAK] ASC
    )
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>3194</SQLVERSION><RMTRACKLINK>IDBOS-2220</RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT> IF EXISTS (SELECT * FROM sys.objects WHERE [name] = N'data_sale_SalesRestriction' AND [type] = 'TR')
BEGIN
      DROP TRIGGER [dbo].[data_sale_SalesRestriction];
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>Create trigger [dbo].[data_sale_SalesRestriction] on [dbo].[DATA_Sale] FOR update
	 as
begin
	SET NOCOUNT ON;
    IF UPDATE(Approved) or Update(StatusCode)
    BEGIN

		Declare @Temp Restriction_Table

		DECLARE @INS_SaleID int
		DECLARE @status int = 0 
		DECLARE @DR_status int

		DECLARE	@ReservationAccountID int
		DECLARE	@B2BAccountID int  
		DECLARE	@TicketAccountID int
		DECLARE	@SaleID int
		DECLARE	@SaleItemID int
		DECLARE @UsageCheck int
		DECLARE	@PerformanceID int
		DECLARE	@Quantity int
		DECLARE @MatrixCellID int
		DECLARE @EventID int

		DECLARE @RestrictionType int	
			
		DECLARE @ReservationAccountOwner int = 1
		DECLARE @TicketAccountOwner int = 2
		DECLARE @CheckforRestraintOnly int = 0

		SELECT @status=i.Approved, @INS_SaleID = i.Saleid 
				FROM inserted i
				    JOIN deleted d
					         ON i.SaleID = d.SaleID
					         AND ((d.paid = 0) or (i.paid &lt;&gt; d.Paid))
							 AND i.statuscode = 1

		if @status = 0 
		begin
			SELECT @DR_status = CASE WHEN i.StatusCode = 2 then  1
			                         else 0
					             end, 
			       @INS_SaleID = i.Saleid 
					FROM inserted i
					      JOIN deleted d
						          ON i.[SaleID] = d.[SaleID]
						             AND i.[StatusCode] &lt;&gt; d.[StatusCode]
		end


		if @status = 1
		begin

			Insert into @Temp
			select  ISNULL(data_reservation.accountid, ODR.AccountID) as ReservationAccountID,
					data_ticket.accountid TicketAccountID,
					data_saleitem.Matrixcellid,
					case when data_ticket.ticketid is not null then case when data_saleitem.Quantity &lt; 0 then -1 else 1 end
									else data_saleitem.Quantity
								end Quantity,
					case when cnf_performance.PerformanceID is not null then cnf_performance.PerformanceID
                                             else 9999999
     end ,
					case when cnf_performance.Eventid is not null then cnf_performance.Eventid
                                             else  9999999
     end,
					data_sale.saleid,
					data_saleitem.saleitemid,
					case when data_saleitem.Quantity &lt; 0 then ISNULL((select top 1 1
																		from data_transaction
																		where data_transaction.transactiontype in (17, 18, 20, 40, 47)
																			and data_transaction.saleid = data_sale.saleid), 0)
							else 0
						end as UsageCheck

			from data_sale WITH(NOLOCK)
				LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
				INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
				LEFT  JOIN data_saleitem2ticket WITH(NOLOCK)				on data_saleitem2ticket.saleitemid = data_saleitem.saleitemid
				LEFT  JOIN data_saleitem2Performance WITH(NOLOCK)			on data_saleitem2performance.saleitemid = data_saleitem.saleitemid
				LEFT  JOIN cnf_performance WITH(NOLOCK)						on cnf_Performance.performanceid = data_saleitem2performance.performanceid
				LEFT  JOIN data_ticket WITH(NOLOCK)							on data_ticket.ticketid = data_saleitem2ticket.ticketid
				left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
				left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

				where data_sale.saleid = @INS_SaleID


			Insert into @Temp
			select  ISNULL(data_reservation.accountid, ODR.AccountID) as ReservationAccountID,
					data_ticket.accountid TicketAccountID,
					data_saleitem.Matrixcellid,
					case when data_ticket.ticketid is not null then case when data_saleitem.Quantity &lt; 0 then -1 else 1 end
									else data_saleitem.Quantity
								end Quantity,
					0,
					0,
					data_sale.saleid,
					data_saleitem.saleitemid,
					case when data_saleitem.Quantity &lt; 0 then ISNULL((select top 1 1
																		from data_transaction
																		where data_transaction.transactiontype in (17, 18, 20, 40, 47)
																			and data_transaction.saleid = data_sale.saleid), 0)
							else 0
						end as UsageCheck

			from data_sale WITH(NOLOCK)
				LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
				INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
				LEFT  JOIN data_saleitem2ticket WITH(NOLOCK)				on data_saleitem2ticket.saleitemid = data_saleitem.saleitemid
				LEFT  JOIN data_saleitem2Performance WITH(NOLOCK)			on data_saleitem2performance.saleitemid = data_saleitem.saleitemid
				LEFT  JOIN cnf_performance WITH(NOLOCK)						on cnf_Performance.performanceid = data_saleitem2performance.performanceid
				LEFT  JOIN data_ticket WITH(NOLOCK)							on data_ticket.ticketid = data_saleitem2ticket.ticketid
				left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
				left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

				where data_sale.saleid = @INS_SaleID
		END

		if @DR_status = 1
		begin

			Insert into @Temp
			select  ISNULL(data_reservation.accountid, ODR.AccountID) as ReservationAccountID,
					data_ticket.accountid TicketAccountID,
					data_saleitem.Matrixcellid,
					case when data_ticket.ticketid is not null then case when data_saleitem.Quantity &lt; 0 then -1 else 1 end
									else data_saleitem.Quantity
								end Quantity,
					case when cnf_performance.PerformanceID is not null then cnf_performance.PerformanceID
                                             else 9999999
     end ,
					case when cnf_performance.Eventid is not null then cnf_performance.Eventid
                                             else  9999999
     end,
					data_sale.saleid,
					data_saleitem.saleitemid,
					case when data_saleitem.Quantity &lt; 0 then ISNULL((select top 1 1
																		from data_transaction
																		where data_transaction.transactiontype in (17, 18, 20, 40, 47)
																			and data_transaction.saleid = data_sale.saleid), 0)
							else 0
						end as UsageCheck

			from data_sale WITH(NOLOCK)
				LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
				INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
				LEFT  JOIN data_saleitem2ticket WITH(NOLOCK)				on data_saleitem2ticket.saleitemid = data_saleitem.saleitemid
				LEFT  JOIN data_saleitem2Performance WITH(NOLOCK)			on data_saleitem2performance.saleitemid = data_saleitem.saleitemid
				LEFT  JOIN cnf_performance WITH(NOLOCK)						on cnf_Performance.performanceid = data_saleitem2performance.performanceid
				LEFT  JOIN data_ticket WITH(NOLOCK)							on data_ticket.ticketid = data_saleitem2ticket.ticketid
				left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
				left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

				where data_sale.saleid = @INS_SaleID
				and data_saleitem.quantity &lt; 0

			Insert into @Temp
			select  ISNULL(data_reservation.accountid, ODR.AccountID) as ReservationAccountID,
					data_ticket.accountid TicketAccountID,
					data_saleitem.Matrixcellid,
					case when data_ticket.ticketid is not null then case when data_saleitem.Quantity &lt; 0 then -1 else 1 end
									else data_saleitem.Quantity
								end Quantity,
					0,
					0,
					data_sale.saleid,
					data_saleitem.saleitemid,
					case when data_saleitem.Quantity &lt; 0 then ISNULL((select top 1 1
																		from data_transaction
																		where data_transaction.transactiontype in (17, 18, 20, 40, 47)
																			and data_transaction.saleid = data_sale.saleid), 0)
							else 0
						end as UsageCheck

			from data_sale WITH(NOLOCK)
				LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
				INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
				LEFT  JOIN data_saleitem2ticket WITH(NOLOCK)				on data_saleitem2ticket.saleitemid = data_saleitem.saleitemid
				LEFT  JOIN data_saleitem2Performance WITH(NOLOCK)			on data_saleitem2performance.saleitemid = data_saleitem.saleitemid
				LEFT  JOIN cnf_performance WITH(NOLOCK)						on cnf_Performance.performanceid = data_saleitem2performance.performanceid
				LEFT  JOIN data_ticket WITH(NOLOCK)							on data_ticket.ticketid = data_saleitem2ticket.ticketid
				left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
				left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

				where data_sale.saleid = @INS_SaleID
				and data_saleitem.quantity &lt; 0

		end

		delete from @Temp where PerformanceID = 9999999

		Exec otn_sp_CheckAccountRestrictions @Temp, 'Temp'
	end
end</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>ALTER TABLE [dbo].[DATA_Sale] ENABLE TRIGGER [data_sale_SalesRestriction]</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dchen</ADDEDBY><SQLVERSION>3193</SQLVERSION><RMTRACKLINK>IDBOS-2093</RMTRACKLINK><REASON>IDBOS-2093 - Wait List for sold out Events / Performances
  * Creating the table DATA_WAITLIST_SUBSCRIPTIONS</REASON><TABLENAMES>DATA_WaitList_Subscriptions=WaitListSubscriptionId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND TABLE_NAME = 'DATA_WaitList_Subscriptions')
BEGIN
	Drop Table DATA_WaitList_Subscriptions
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND TABLE_NAME = 'DATA_WaitList_Subscriptions')
BEGIN
  CREATE TABLE DATA_WaitList_Subscriptions
  (
	[WaitListSubscriptionID] [int] IDENTITY(1,1) NOT NULL,
	[WaitListSubscriptionDateTime] [datetime] NOT NULL,
	[WaitListSubscriptionEmail] [nchar](100) NOT NULL,
	[WaitListSubscriptionPerformanceID] [int] NOT NULL,
	[WaitListSubscriptionQtdSeats] [int] NOT NULL,
	[WaitListSubscriptionQtdNotifications] [int] NULL,
	[WaitListSubscriptionLastNotificationDateTime] [datetime] NULL,
	[WaitListSubscriptionPurge] [int] NULL,
	[WaitListSubscriptionSaleId] [int] NULL,
        Primary Key ([WaitListSubscriptionID])
  ) ON [PRIMARY]

END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (	SELECT object_id 
		FROM sys.indexes
		WHERE Name = 'IX_DATA_WaitList_Subscriptions_DateTime')
BEGIN
    CREATE NONCLUSTERED INDEX [IX_DATA_WaitList_Subscriptions_DateTime] 
    ON [dbo].[DATA_WaitList_Subscriptions]
    (
	[WaitListSubscriptionDateTime] ASC
    )
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (	SELECT object_id 
		FROM sys.indexes
		WHERE Name = 'IX_DATA_WaitList_Subscriptions_Subscriber')
BEGIN
    CREATE UNIQUE NONCLUSTERED INDEX [IX_DATA_WaitList_Subscriptions_Subscriber] 
    ON [dbo].[DATA_WaitList_Subscriptions]
    (
	[WaitListSubscriptionEmail] ASC,
	[WaitListSubscriptionPerformanceID] ASC
    )
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>3192</SQLVERSION><RMTRACKLINK>IDBOS-2220</RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT> IF EXISTS (SELECT * FROM sys.objects WHERE [name] = N'data_sale_SalesRestriction' AND [type] = 'TR')
BEGIN
      DROP TRIGGER [dbo].[data_sale_SalesRestriction];
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>Create trigger [dbo].[data_sale_SalesRestriction] on [dbo].[DATA_Sale] FOR update
	 as
begin
	SET NOCOUNT ON;
    IF UPDATE(Approved) or Update(StatusCode)
    BEGIN

		Declare @Temp Restriction_Table

		DECLARE @INS_SaleID int
		DECLARE @status int = 0 
		DECLARE @DR_status int

		DECLARE	@ReservationAccountID int
		DECLARE	@B2BAccountID int  
		DECLARE	@TicketAccountID int
		DECLARE	@SaleID int
		DECLARE	@SaleItemID int
		DECLARE @UsageCheck int
		DECLARE	@PerformanceID int
		DECLARE	@Quantity int
		DECLARE @MatrixCellID int
		DECLARE @EventID int

		DECLARE @RestrictionType int	
			
		DECLARE @ReservationAccountOwner int = 1
		DECLARE @TicketAccountOwner int = 2
		DECLARE @CheckforRestraintOnly int = 0

		SELECT @status=i.Approved, @INS_SaleID = i.Saleid 
				FROM inserted i
				JOIN deleted d
					ON i.SaleID = d.SaleID
					AND ((d.paid = 0) or (i.paid &lt;&gt; d.Paid))

		if @status = 0 
		begin
			SELECT @DR_status = CASE WHEN i.StatusCode = 2 then  1
			            else 0
					end, 
			       @INS_SaleID = i.Saleid 
					FROM inserted i
					JOIN deleted d
						ON i.[SaleID] = d.[SaleID]
						AND i.[StatusCode] &lt;&gt; d.[StatusCode]
		end


		if @status = 1
		begin
			Insert into @Temp
			select  ISNULL(data_reservation.accountid, ODR.AccountID) as ReservationAccountID,
					data_ticket.accountid TicketAccountID,
					data_saleitem.Matrixcellid,
					case when data_ticket.ticketid is not null then case when data_saleitem.Quantity &lt; 0 then -1 else 1 end
									else data_saleitem.Quantity
								end Quantity,
					case when cnf_performance.PerformanceID is not null then cnf_performance.PerformanceID
                                             else 9999999
     end ,
					case when cnf_performance.Eventid is not null then cnf_performance.Eventid
                                             else  9999999
     end,
					data_sale.saleid,
					data_saleitem.saleitemid,
					case when data_saleitem.Quantity &lt; 0 then ISNULL((select top 1 1
																		from data_transaction
																		where data_transaction.transactiontype in (17, 18, 20, 40, 47)
																			and data_transaction.saleid = data_sale.saleid), 0)
							else 0
						end as UsageCheck

			from data_sale WITH(NOLOCK)
				LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
				INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
				LEFT  JOIN data_saleitem2ticket WITH(NOLOCK)				on data_saleitem2ticket.saleitemid = data_saleitem.saleitemid
				LEFT  JOIN data_saleitem2Performance WITH(NOLOCK)			on data_saleitem2performance.saleitemid = data_saleitem.saleitemid
				LEFT  JOIN cnf_performance WITH(NOLOCK)						on cnf_Performance.performanceid = data_saleitem2performance.performanceid
				LEFT  JOIN data_ticket WITH(NOLOCK)							on data_ticket.ticketid = data_saleitem2ticket.ticketid
				left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
				left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

				where data_sale.saleid = @INS_SaleID


			Insert into @Temp
			select  ISNULL(data_reservation.accountid, ODR.AccountID) as ReservationAccountID,
					data_ticket.accountid TicketAccountID,
					data_saleitem.Matrixcellid,
					case when data_ticket.ticketid is not null then case when data_saleitem.Quantity &lt; 0 then -1 else 1 end
									else data_saleitem.Quantity
								end Quantity,
					0,
					0,
					data_sale.saleid,
					data_saleitem.saleitemid,
					case when data_saleitem.Quantity &lt; 0 then ISNULL((select top 1 1
																		from data_transaction
																		where data_transaction.transactiontype in (17, 18, 20, 40, 47)
																			and data_transaction.saleid = data_sale.saleid), 0)
							else 0
						end as UsageCheck

			from data_sale WITH(NOLOCK)
				LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
				INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
				LEFT  JOIN data_saleitem2ticket WITH(NOLOCK)				on data_saleitem2ticket.saleitemid = data_saleitem.saleitemid
				LEFT  JOIN data_saleitem2Performance WITH(NOLOCK)			on data_saleitem2performance.saleitemid = data_saleitem.saleitemid
				LEFT  JOIN cnf_performance WITH(NOLOCK)						on cnf_Performance.performanceid = data_saleitem2performance.performanceid
				LEFT  JOIN data_ticket WITH(NOLOCK)							on data_ticket.ticketid = data_saleitem2ticket.ticketid
				left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
				left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

				where data_sale.saleid = @INS_SaleID
		END

		if @DR_status = 1
		begin
			Insert into @Temp
			select  ISNULL(data_reservation.accountid, ODR.AccountID) as ReservationAccountID,
					data_ticket.accountid TicketAccountID,
					data_saleitem.Matrixcellid,
					case when data_ticket.ticketid is not null then case when data_saleitem.Quantity &lt; 0 then -1 else 1 end
									else data_saleitem.Quantity
								end Quantity,
					case when cnf_performance.PerformanceID is not null then cnf_performance.PerformanceID
                                             else 9999999
     end ,
					case when cnf_performance.Eventid is not null then cnf_performance.Eventid
                                             else  9999999
     end,
					data_sale.saleid,
					data_saleitem.saleitemid,
					case when data_saleitem.Quantity &lt; 0 then ISNULL((select top 1 1
																		from data_transaction
																		where data_transaction.transactiontype in (17, 18, 20, 40, 47)
																			and data_transaction.saleid = data_sale.saleid), 0)
							else 0
						end as UsageCheck

			from data_sale WITH(NOLOCK)
				LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
				INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
				LEFT  JOIN data_saleitem2ticket WITH(NOLOCK)				on data_saleitem2ticket.saleitemid = data_saleitem.saleitemid
				LEFT  JOIN data_saleitem2Performance WITH(NOLOCK)			on data_saleitem2performance.saleitemid = data_saleitem.saleitemid
				LEFT  JOIN cnf_performance WITH(NOLOCK)						on cnf_Performance.performanceid = data_saleitem2performance.performanceid
				LEFT  JOIN data_ticket WITH(NOLOCK)							on data_ticket.ticketid = data_saleitem2ticket.ticketid
				left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
				left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

				where data_sale.saleid = @INS_SaleID
				and data_saleitem.quantity &lt; 0

			Insert into @Temp
			select  ISNULL(data_reservation.accountid, ODR.AccountID) as ReservationAccountID,
					data_ticket.accountid TicketAccountID,
					data_saleitem.Matrixcellid,
					case when data_ticket.ticketid is not null then case when data_saleitem.Quantity &lt; 0 then -1 else 1 end
									else data_saleitem.Quantity
								end Quantity,
					0,
					0,
					data_sale.saleid,
					data_saleitem.saleitemid,
					case when data_saleitem.Quantity &lt; 0 then ISNULL((select top 1 1
																		from data_transaction
																		where data_transaction.transactiontype in (17, 18, 20, 40, 47)
																			and data_transaction.saleid = data_sale.saleid), 0)
							else 0
						end as UsageCheck

			from data_sale WITH(NOLOCK)
				LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
				INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
				LEFT  JOIN data_saleitem2ticket WITH(NOLOCK)				on data_saleitem2ticket.saleitemid = data_saleitem.saleitemid
				LEFT  JOIN data_saleitem2Performance WITH(NOLOCK)			on data_saleitem2performance.saleitemid = data_saleitem.saleitemid
				LEFT  JOIN cnf_performance WITH(NOLOCK)						on cnf_Performance.performanceid = data_saleitem2performance.performanceid
				LEFT  JOIN data_ticket WITH(NOLOCK)							on data_ticket.ticketid = data_saleitem2ticket.ticketid
				left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
				left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

				where data_sale.saleid = @INS_SaleID
				and data_saleitem.quantity &lt; 0

		end

		Exec otn_sp_CheckAccountRestrictions @Temp, 'Temp'
	end
end</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>ALTER TABLE [dbo].[DATA_Sale] ENABLE TRIGGER [data_sale_SalesRestriction]</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>3191</SQLVERSION><RMTRACKLINK>88742</RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT> IF EXISTS (SELECT * FROM sys.objects WHERE [name] = N'data_sale_SalesRestriction' AND [type] = 'TR')
BEGIN
      DROP TRIGGER [dbo].[data_sale_SalesRestriction];
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>  Create trigger [dbo].[data_sale_SalesRestriction] on [dbo].[DATA_Sale] FOR update
	 as
begin
	SET NOCOUNT ON;
    IF UPDATE(Approved) or Update(StatusCode)
    BEGIN

		Declare @Temp Restriction_Table

		DECLARE @INS_SaleID int
		DECLARE @status int = 0 
		DECLARE @DR_status int

		DECLARE	@ReservationAccountID int
		DECLARE	@B2BAccountID int  
		DECLARE	@TicketAccountID int
		DECLARE	@SaleID int
		DECLARE	@SaleItemID int
		DECLARE @UsageCheck int
		DECLARE	@PerformanceID int
		DECLARE	@Quantity int
		DECLARE @MatrixCellID int
		DECLARE @EventID int

		DECLARE @RestrictionType int	
			
		DECLARE @ReservationAccountOwner int = 1
		DECLARE @TicketAccountOwner int = 2
		DECLARE @CheckforRestraintOnly int = 0

		SELECT @status=i.Approved, @INS_SaleID = i.Saleid 
				FROM inserted i
				JOIN deleted d
					ON i.SaleID = d.SaleID
					AND i.Approved &lt;&gt; d.Approved

		if @status = 0 
		begin
			SELECT @DR_status = CASE WHEN i.StatusCode = 2 then  1
			            else 0
					end, 
			       @INS_SaleID = i.Saleid 
					FROM inserted i
					JOIN deleted d
						ON i.[SaleID] = d.[SaleID]
						AND i.[StatusCode] &lt;&gt; d.[StatusCode]
		end


		if @status = 1
		begin
			Insert into @Temp
			select  ISNULL(data_reservation.accountid, ODR.AccountID) as ReservationAccountID,
					data_ticket.accountid TicketAccountID,
					data_saleitem.Matrixcellid,
					case when data_ticket.ticketid is not null then case when data_saleitem.Quantity &lt; 0 then -1 else 1 end
									else data_saleitem.Quantity
								end Quantity,
					case when cnf_performance.PerformanceID is not null then cnf_performance.PerformanceID
                                             else 9999999
     end ,
					case when cnf_performance.Eventid is not null then cnf_performance.Eventid
                                             else  9999999
     end,
					data_sale.saleid,
					data_saleitem.saleitemid,
					case when data_saleitem.Quantity &lt; 0 then ISNULL((select top 1 1
																		from data_transaction
																		where data_transaction.transactiontype in (17, 18, 20, 40, 47)
																			and data_transaction.saleid = data_sale.saleid), 0)
							else 0
						end as UsageCheck

			from data_sale WITH(NOLOCK)
				LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
				INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
				LEFT  JOIN data_saleitem2ticket WITH(NOLOCK)				on data_saleitem2ticket.saleitemid = data_saleitem.saleitemid
				LEFT  JOIN data_saleitem2Performance WITH(NOLOCK)			on data_saleitem2performance.saleitemid = data_saleitem.saleitemid
				LEFT  JOIN cnf_performance WITH(NOLOCK)						on cnf_Performance.performanceid = data_saleitem2performance.performanceid
				LEFT  JOIN data_ticket WITH(NOLOCK)							on data_ticket.ticketid = data_saleitem2ticket.ticketid
				left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
				left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

				where data_sale.saleid = @INS_SaleID


			Insert into @Temp
			select  ISNULL(data_reservation.accountid, ODR.AccountID) as ReservationAccountID,
					data_ticket.accountid TicketAccountID,
					data_saleitem.Matrixcellid,
					case when data_ticket.ticketid is not null then case when data_saleitem.Quantity &lt; 0 then -1 else 1 end
									else data_saleitem.Quantity
								end Quantity,
					0,
					0,
					data_sale.saleid,
					data_saleitem.saleitemid,
					case when data_saleitem.Quantity &lt; 0 then ISNULL((select top 1 1
																		from data_transaction
																		where data_transaction.transactiontype in (17, 18, 20, 40, 47)
																			and data_transaction.saleid = data_sale.saleid), 0)
							else 0
						end as UsageCheck

			from data_sale WITH(NOLOCK)
				LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
				INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
				LEFT  JOIN data_saleitem2ticket WITH(NOLOCK)				on data_saleitem2ticket.saleitemid = data_saleitem.saleitemid
				LEFT  JOIN data_saleitem2Performance WITH(NOLOCK)			on data_saleitem2performance.saleitemid = data_saleitem.saleitemid
				LEFT  JOIN cnf_performance WITH(NOLOCK)						on cnf_Performance.performanceid = data_saleitem2performance.performanceid
				LEFT  JOIN data_ticket WITH(NOLOCK)							on data_ticket.ticketid = data_saleitem2ticket.ticketid
				left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
				left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

				where data_sale.saleid = @INS_SaleID
		END

		if @DR_status = 1
		begin
			Insert into @Temp
			select  ISNULL(data_reservation.accountid, ODR.AccountID) as ReservationAccountID,
					data_ticket.accountid TicketAccountID,
					data_saleitem.Matrixcellid,
					case when data_ticket.ticketid is not null then case when data_saleitem.Quantity &lt; 0 then -1 else 1 end
									else data_saleitem.Quantity
								end Quantity,
					case when cnf_performance.PerformanceID is not null then cnf_performance.PerformanceID
                                             else 9999999
     end ,
					case when cnf_performance.Eventid is not null then cnf_performance.Eventid
                                             else  9999999
     end,
					data_sale.saleid,
					data_saleitem.saleitemid,
					case when data_saleitem.Quantity &lt; 0 then ISNULL((select top 1 1
																		from data_transaction
																		where data_transaction.transactiontype in (17, 18, 20, 40, 47)
																			and data_transaction.saleid = data_sale.saleid), 0)
							else 0
						end as UsageCheck

			from data_sale WITH(NOLOCK)
				LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
				INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
				LEFT  JOIN data_saleitem2ticket WITH(NOLOCK)				on data_saleitem2ticket.saleitemid = data_saleitem.saleitemid
				LEFT  JOIN data_saleitem2Performance WITH(NOLOCK)			on data_saleitem2performance.saleitemid = data_saleitem.saleitemid
				LEFT  JOIN cnf_performance WITH(NOLOCK)						on cnf_Performance.performanceid = data_saleitem2performance.performanceid
				LEFT  JOIN data_ticket WITH(NOLOCK)							on data_ticket.ticketid = data_saleitem2ticket.ticketid
				left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
				left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

				where data_sale.saleid = @INS_SaleID
				and data_saleitem.quantity &lt; 0

			Insert into @Temp
			select  ISNULL(data_reservation.accountid, ODR.AccountID) as ReservationAccountID,
					data_ticket.accountid TicketAccountID,
					data_saleitem.Matrixcellid,
					case when data_ticket.ticketid is not null then case when data_saleitem.Quantity &lt; 0 then -1 else 1 end
									else data_saleitem.Quantity
								end Quantity,
					0,
					0,
					data_sale.saleid,
					data_saleitem.saleitemid,
					case when data_saleitem.Quantity &lt; 0 then ISNULL((select top 1 1
																		from data_transaction
																		where data_transaction.transactiontype in (17, 18, 20, 40, 47)
																			and data_transaction.saleid = data_sale.saleid), 0)
							else 0
						end as UsageCheck

			from data_sale WITH(NOLOCK)
				LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
				INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
				LEFT  JOIN data_saleitem2ticket WITH(NOLOCK)				on data_saleitem2ticket.saleitemid = data_saleitem.saleitemid
				LEFT  JOIN data_saleitem2Performance WITH(NOLOCK)			on data_saleitem2performance.saleitemid = data_saleitem.saleitemid
				LEFT  JOIN cnf_performance WITH(NOLOCK)						on cnf_Performance.performanceid = data_saleitem2performance.performanceid
				LEFT  JOIN data_ticket WITH(NOLOCK)							on data_ticket.ticketid = data_saleitem2ticket.ticketid
				left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
				left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

				where data_sale.saleid = @INS_SaleID
				and data_saleitem.quantity &lt; 0

		end

		Exec otn_sp_CheckAccountRestrictions @Temp, 'Temp'
	end
end</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>ALTER TABLE [dbo].[DATA_Sale] ENABLE TRIGGER [data_sale_SalesRestriction]</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>3190</SQLVERSION><RMTRACKLINK>IDBOS-2362</RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.objects WHERE [name] = N'data_sale_SalesRestriction' AND [type] = 'TR')
BEGIN
      DROP TRIGGER [dbo].[data_sale_SalesRestriction];
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>Create trigger [dbo].[data_sale_SalesRestriction] on [dbo].[DATA_Sale] FOR update
	 as
begin
	SET NOCOUNT ON;
    IF UPDATE(Approved) or Update(StatusCode)
    BEGIN

		Declare @Temp Restriction_Table

		DECLARE @INS_SaleID int
		DECLARE @status int = 0 
		DECLARE @DR_status int

		DECLARE	@ReservationAccountID int
		DECLARE	@B2BAccountID int  
		DECLARE	@TicketAccountID int
		DECLARE	@SaleID int
		DECLARE	@SaleItemID int
		DECLARE @UsageCheck int
		DECLARE	@PerformanceID int
		DECLARE	@Quantity int
		DECLARE @MatrixCellID int
		DECLARE @EventID int

		DECLARE @RestrictionType int	
			
		DECLARE @ReservationAccountOwner int = 1
		DECLARE @TicketAccountOwner int = 2
		DECLARE @CheckforRestraintOnly int = 0

		SELECT @status=i.Approved, @INS_SaleID = i.Saleid 
				FROM inserted i
				JOIN deleted d
					ON i.SaleID = d.SaleID
					AND i.Approved &lt;&gt; d.Approved

		if @status = 0 
		begin
			SELECT @DR_status = CASE WHEN i.StatusCode = 2 then  1
			            else 0
					end, 
			       @INS_SaleID = i.Saleid 
					FROM inserted i
					JOIN deleted d
						ON i.[SaleID] = d.[SaleID]
						AND i.[StatusCode] &lt;&gt; d.[StatusCode]
		end


		if @status = 1
		begin
			Insert into @Temp
			select  ISNULL(data_reservation.accountid, ODR.AccountID) as ReservationAccountID,
					data_ticket.accountid TicketAccountID,
					data_saleitem.Matrixcellid,
					case when data_ticket.ticketid is not null then case when data_saleitem.Quantity &lt; 0 then -1 else 1 end
									else data_saleitem.Quantity
								end Quantity,
					cnf_performance.PerformanceID,
					cnf_performance.Eventid,
					data_sale.saleid,
					data_saleitem.saleitemid,
					case when data_saleitem.Quantity &lt; 0 then ISNULL((select top 1 1
																		from data_transaction
																		where data_transaction.transactiontype in (17, 18, 20, 40, 47)
																			and data_transaction.saleid = data_sale.saleid), 0)
							else 0
						end as UsageCheck

			from data_sale WITH(NOLOCK)
				LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
				INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
				LEFT  JOIN data_saleitem2ticket WITH(NOLOCK)				on data_saleitem2ticket.saleitemid = data_saleitem.saleitemid
				LEFT  JOIN data_saleitem2Performance WITH(NOLOCK)			on data_saleitem2performance.saleitemid = data_saleitem.saleitemid
				LEFT  JOIN cnf_performance WITH(NOLOCK)						on cnf_Performance.performanceid = data_saleitem2performance.performanceid
				LEFT  JOIN data_ticket WITH(NOLOCK)							on data_ticket.ticketid = data_saleitem2ticket.ticketid
				left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
				left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

				where data_sale.saleid = @INS_SaleID


			Insert into @Temp
			select  ISNULL(data_reservation.accountid, ODR.AccountID) as ReservationAccountID,
					data_ticket.accountid TicketAccountID,
					data_saleitem.Matrixcellid,
					case when data_ticket.ticketid is not null then case when data_saleitem.Quantity &lt; 0 then -1 else 1 end
									else data_saleitem.Quantity
								end Quantity,
					0,
					0,
					data_sale.saleid,
					data_saleitem.saleitemid,
					case when data_saleitem.Quantity &lt; 0 then ISNULL((select top 1 1
																		from data_transaction
																		where data_transaction.transactiontype in (17, 18, 20, 40, 47)
																			and data_transaction.saleid = data_sale.saleid), 0)
							else 0
						end as UsageCheck

			from data_sale WITH(NOLOCK)
				LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
				INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
				LEFT  JOIN data_saleitem2ticket WITH(NOLOCK)				on data_saleitem2ticket.saleitemid = data_saleitem.saleitemid
				LEFT  JOIN data_saleitem2Performance WITH(NOLOCK)			on data_saleitem2performance.saleitemid = data_saleitem.saleitemid
				LEFT  JOIN cnf_performance WITH(NOLOCK)						on cnf_Performance.performanceid = data_saleitem2performance.performanceid
				LEFT  JOIN data_ticket WITH(NOLOCK)							on data_ticket.ticketid = data_saleitem2ticket.ticketid
				left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
				left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

				where data_sale.saleid = @INS_SaleID
		END

		if @DR_status = 1
		begin
			Insert into @Temp
			select  ISNULL(data_reservation.accountid, ODR.AccountID) as ReservationAccountID,
					data_ticket.accountid TicketAccountID,
					data_saleitem.Matrixcellid,
					case when data_ticket.ticketid is not null then case when data_saleitem.Quantity &lt; 0 then -1 else 1 end
									else data_saleitem.Quantity
								end Quantity,
					cnf_performance.PerformanceID,
					cnf_performance.Eventid,
					data_sale.saleid,
					data_saleitem.saleitemid,
					case when data_saleitem.Quantity &lt; 0 then ISNULL((select top 1 1
																		from data_transaction
																		where data_transaction.transactiontype in (17, 18, 20, 40, 47)
																			and data_transaction.saleid = data_sale.saleid), 0)
							else 0
						end as UsageCheck

			from data_sale WITH(NOLOCK)
				LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
				INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
				LEFT  JOIN data_saleitem2ticket WITH(NOLOCK)				on data_saleitem2ticket.saleitemid = data_saleitem.saleitemid
				LEFT  JOIN data_saleitem2Performance WITH(NOLOCK)			on data_saleitem2performance.saleitemid = data_saleitem.saleitemid
				LEFT  JOIN cnf_performance WITH(NOLOCK)						on cnf_Performance.performanceid = data_saleitem2performance.performanceid
				LEFT  JOIN data_ticket WITH(NOLOCK)							on data_ticket.ticketid = data_saleitem2ticket.ticketid
				left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
				left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

				where data_sale.saleid = @INS_SaleID
				and data_saleitem.quantity &lt; 0

			Insert into @Temp
			select  ISNULL(data_reservation.accountid, ODR.AccountID) as ReservationAccountID,
					data_ticket.accountid TicketAccountID,
					data_saleitem.Matrixcellid,
					case when data_ticket.ticketid is not null then case when data_saleitem.Quantity &lt; 0 then -1 else 1 end
									else data_saleitem.Quantity
								end Quantity,
					0,
					0,
					data_sale.saleid,
					data_saleitem.saleitemid,
					case when data_saleitem.Quantity &lt; 0 then ISNULL((select top 1 1
																		from data_transaction
																		where data_transaction.transactiontype in (17, 18, 20, 40, 47)
																			and data_transaction.saleid = data_sale.saleid), 0)
							else 0
						end as UsageCheck

			from data_sale WITH(NOLOCK)
				LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
				INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
				LEFT  JOIN data_saleitem2ticket WITH(NOLOCK)				on data_saleitem2ticket.saleitemid = data_saleitem.saleitemid
				LEFT  JOIN data_saleitem2Performance WITH(NOLOCK)			on data_saleitem2performance.saleitemid = data_saleitem.saleitemid
				LEFT  JOIN cnf_performance WITH(NOLOCK)						on cnf_Performance.performanceid = data_saleitem2performance.performanceid
				LEFT  JOIN data_ticket WITH(NOLOCK)							on data_ticket.ticketid = data_saleitem2ticket.ticketid
				left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
				left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

				where data_sale.saleid = @INS_SaleID
				and data_saleitem.quantity &lt; 0

		end

		Exec otn_sp_CheckAccountRestrictions @Temp, 'Temp'
	end
end</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>ALTER TABLE [dbo].[DATA_Sale] ENABLE TRIGGER [data_sale_SalesRestriction]</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>3189</SQLVERSION><RMTRACKLINK>IDBOS-2362</RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.objects WHERE [name] = N'data_sale_SalesRestriction' AND [type] = 'TR')
BEGIN
      DROP TRIGGER [dbo].[data_sale_SalesRestriction];
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>Create trigger [dbo].[data_sale_SalesRestriction] on [dbo].[DATA_Sale] FOR update
	 as
begin
	SET NOCOUNT ON;
    IF UPDATE(Approved) or Update(StatusCode)
    BEGIN

		Declare @Temp Restriction_Table

		DECLARE @INS_SaleID int
		DECLARE @status int = 0 
		DECLARE @DR_status int

		DECLARE	@ReservationAccountID int
		DECLARE	@B2BAccountID int  
		DECLARE	@TicketAccountID int
		DECLARE	@SaleID int
		DECLARE	@SaleItemID int
		DECLARE @UsageCheck int
		DECLARE	@PerformanceID int
		DECLARE	@Quantity int
		DECLARE @MatrixCellID int
		DECLARE @EventID int

		DECLARE @RestrictionType int	
			
		DECLARE @ReservationAccountOwner int = 1
		DECLARE @TicketAccountOwner int = 2
		DECLARE @CheckforRestraintOnly int = 0

		SELECT @status=i.Approved, @INS_SaleID = i.Saleid 
				FROM inserted i
				JOIN deleted d
					ON i.SaleID = d.SaleID
					AND i.Approved &lt;&gt; d.Approved

		if @status = 0 
		begin
			SELECT @DR_status = CASE WHEN i.StatusCode = 2 then  1
			            else 0
					end, 
			       @INS_SaleID = i.Saleid 
					FROM inserted i
					JOIN deleted d
						ON i.[SaleID] = d.[SaleID]
						AND i.[StatusCode] &lt;&gt; d.[StatusCode]
		end


		if @status = 1
		begin
			Insert into @Temp
			select  ISNULL(data_reservation.accountid, ODR.AccountID) as ReservationAccountID,
					data_ticket.accountid TicketAccountID,
					data_saleitem.Matrixcellid,
					case when data_ticket.ticketid is not null then case when data_saleitem.Quantity &lt; 0 then -1 else 1 end
									else data_saleitem.Quantity
								end Quantity,
					cnf_performance.PerformanceID,
					cnf_performance.Eventid,
					data_sale.saleid,
					data_saleitem.saleitemid,
					case when data_saleitem.Quantity &lt; 0 then ISNULL((select top 1 1
																		from data_transaction
																		where data_transaction.transactiontype in (17, 18, 20, 40, 47)
																			and data_transaction.saleid = data_sale.saleid), 0)
							else 0
						end as UsageCheck

			from data_sale WITH(NOLOCK)
				LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
				INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
				LEFT  JOIN data_saleitem2ticket WITH(NOLOCK)				on data_saleitem2ticket.saleitemid = data_saleitem.saleitemid
				LEFT  JOIN data_saleitem2Performance WITH(NOLOCK)			on data_saleitem2performance.saleitemid = data_saleitem.saleitemid
				LEFT  JOIN cnf_performance WITH(NOLOCK)						on cnf_Performance.performanceid = data_saleitem2performance.performanceid
				LEFT  JOIN data_ticket WITH(NOLOCK)							on data_ticket.ticketid = data_saleitem2ticket.ticketid
				left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
				left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

				where data_sale.saleid = @INS_SaleID
		END

		if @DR_status = 1
		begin
			Insert into @Temp
			select  ISNULL(data_reservation.accountid, ODR.AccountID) as ReservationAccountID,
					data_ticket.accountid TicketAccountID,
					data_saleitem.Matrixcellid,
					case when data_ticket.ticketid is not null then case when data_saleitem.Quantity &lt; 0 then -1 else 1 end
									else data_saleitem.Quantity
								end Quantity,
					cnf_performance.PerformanceID,
					cnf_performance.Eventid,
					data_sale.saleid,
					data_saleitem.saleitemid,
					case when data_saleitem.Quantity &lt; 0 then ISNULL((select top 1 1
																		from data_transaction
																		where data_transaction.transactiontype in (17, 18, 20, 40, 47)
																			and data_transaction.saleid = data_sale.saleid), 0)
							else 0
						end as UsageCheck

			from data_sale WITH(NOLOCK)
				LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
				INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
				LEFT  JOIN data_saleitem2ticket WITH(NOLOCK)				on data_saleitem2ticket.saleitemid = data_saleitem.saleitemid
				LEFT  JOIN data_saleitem2Performance WITH(NOLOCK)			on data_saleitem2performance.saleitemid = data_saleitem.saleitemid
				LEFT  JOIN cnf_performance WITH(NOLOCK)						on cnf_Performance.performanceid = data_saleitem2performance.performanceid
				LEFT  JOIN data_ticket WITH(NOLOCK)							on data_ticket.ticketid = data_saleitem2ticket.ticketid
				left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
				left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

				where data_sale.saleid = @INS_SaleID
				and data_saleitem.quantity &lt; 0
		end

		Exec otn_sp_CheckAccountRestrictions @Temp, 'Temp'
	end
end</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>ALTER TABLE [dbo].[DATA_Sale] ENABLE TRIGGER [data_sale_SalesRestriction]</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>3188</SQLVERSION><RMTRACKLINK>2297</RMTRACKLINK><REASON></REASON><TABLENAMES>CNF_AccountRestriction2DMGCategory=AccountRestriction2DMGCategoryId
CNF_AccountRestriction2Performance=AccountRestriction2PerformanceId
CNF_AccountRestriction2Event=AccountRestriction2EventId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND TABLE_NAME = 'CNF_AccountRestriction2DMGCatagory')
BEGIN
	Drop Table CNF_AccountRestriction2DMGCatagory
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND TABLE_NAME = 'CNF_AccountRestriction2DMGCategory')
BEGIN
Create table CNF_AccountRestriction2DMGCategory
(
	[AccountRestriction2DMGCategoryId] [int] IDENTITY(1,1) NOT NULL,
	[AccountRestrictionId] [int] NOT NULL,
	[DMGCategoryID] [int] NULL,	
	[Last_UserId_Log] [int] NULL,
	[Last_WorkstationId_Log] [int] NULL,
	[Last_DateTime_Log] [datetime] NULL
) ON [PRIMARY]
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND TABLE_NAME = 'CNF_AccountRestriction2Performance')
BEGIN
	Drop Table CNF_AccountRestriction2Performance
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND TABLE_NAME = 'CNF_AccountRestriction2Performance')
BEGIN
Create table CNF_AccountRestriction2Performance
(
	[AccountRestriction2PerformanceId] [int] IDENTITY(1,1) NOT NULL,
	[AccountRestrictionId] [int] NOT NULL,
	[PerformanceID] [int] NULL,	
	[Last_UserId_Log] [int] NULL,
	[Last_WorkstationId_Log] [int] NULL,
	[Last_DateTime_Log] [datetime] NULL
) ON [PRIMARY]
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND TABLE_NAME = 'CNF_AccountRestriction2Event')
BEGIN
	Drop Table CNF_AccountRestriction2Event
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND TABLE_NAME = 'CNF_AccountRestriction2Event')
BEGIN
Create table CNF_AccountRestriction2Event
(
	[AccountRestriction2EventId] [int] IDENTITY(1,1) NOT NULL,
	[AccountRestrictionId] [int] NOT NULL,
	[EventID] [int] NULL,	
	[Last_UserId_Log] [int] NULL,
	[Last_WorkstationId_Log] [int] NULL,
	[Last_DateTime_Log] [datetime] NULL
) ON [PRIMARY]
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>3187</SQLVERSION><RMTRACKLINK>2297</RMTRACKLINK><REASON></REASON><TABLENAMES>CNF_AccountRestriction2DMGCatagory=AccountRestriction2DMGCategoryId
CNF_AccountRestriction2Performance=AccountRestriction2PerformanceId
CNF_AccountRestriction2Event=AccountRestriction2EventId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND TABLE_NAME = 'CNF_AccountRestriction2DMGCatagory')
BEGIN
Create table CNF_AccountRestriction2DMGCatagory
(
	[AccountRestriction2DMGCategoryId] [int] IDENTITY(1,1) NOT NULL,
	[AccountRestrictionId] [int] NOT NULL,
	[DMGCategoryID] [int] NULL,	
	[UserId] [int] NULL,
	[WorkstationId] [int] NULL,
	[Last_DateTime_Log] [datetime] NULL
) ON [PRIMARY]
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND TABLE_NAME = 'CNF_AccountRestriction2Performance')
BEGIN
Create table CNF_AccountRestriction2Performance
(
	[AccountRestriction2PerformanceId] [int] IDENTITY(1,1) NOT NULL,
	[AccountRestrictionId] [int] NOT NULL,
	[PerformanceID] [int] NULL,	
	[UserId] [int] NULL,
	[WorkstationId] [int] NULL,
	[Last_DateTime_Log] [datetime] NULL
) ON [PRIMARY]
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND TABLE_NAME = 'CNF_AccountRestriction2Event')
BEGIN
Create table CNF_AccountRestriction2Event
(
	[AccountRestriction2EventId] [int] IDENTITY(1,1) NOT NULL,
	[AccountRestrictionId] [int] NOT NULL,
	[EventID] [int] NULL,	
	[UserId] [int] NULL,
	[WorkstationId] [int] NULL,
	[Last_DateTime_Log] [datetime] NULL
) ON [PRIMARY]
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>3186</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
FROM sys.indexes 
WHERE name='IDX_RR_DATA_Revenue_RevenueAmount' AND object_id = OBJECT_ID('RR_DATA_Revenue'))
begin
	CREATE NONCLUSTERED INDEX [IDX_RR_DATA_Revenue_RevenueAmount]
	ON [dbo].[RR_DATA_Revenue] ([RevenueAmount])
	INCLUDE ([COAAccountId],[RevenueRecognitionRuleId],[TransactionId],[SaleItemId],[TicketId],[AccountingType])
end</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
FROM sys.indexes 
WHERE name='IDX_RR_DATA_Revenue_TransactiONID' AND object_id = OBJECT_ID('RR_DATA_Revenue'))
begin
	CREATE NONCLUSTERED INDEX [IDX_RR_DATA_Revenue_TransactiONID]
	ON [dbo].[RR_DATA_Revenue] ([TransactionId])
	INCLUDE ([COAAccountId],[RevenueRecognitionRuleId],[SaleItemId],[TicketId],[RevenueAmount],[AccountingType])
End</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>scoluccia</ADDEDBY><SQLVERSION>3185</SQLVERSION><RMTRACKLINK>IDBOS-1606</RMTRACKLINK><REASON>Removed field  TckValidityId from DATA_Biometric2Ticket</REASON><TABLENAMES>DATA_Biometric2Ticket=Biometric2TicketId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_Biometric2Ticket_TckValidityId')
BEGIN
  ALTER TABLE DATA_Biometric2Ticket
  DROP CONSTRAINT FK_DATA_Biometric2Ticket_TckValidityId
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'TckValidityId' 
                      AND OBJECT_ID = OBJECT_ID(N'DATA_Biometric2Ticket'))
BEGIN
  ALTER TABLE DATA_Biometric2Ticket
  DROP COLUMN TckValidityId 
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>ecandido</ADDEDBY><SQLVERSION>3184</SQLVERSION><RMTRACKLINK>IDBOS-1606</RMTRACKLINK><REASON>Add Field "Imported" in table OFF_TicketUsage</REASON><TABLENAMES>OFF_TicketUsage=TicketUsageId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'Imported' 
                      AND OBJECT_ID = OBJECT_ID(N'OFF_TicketUsage'))
BEGIN
  ALTER TABLE OFF_TicketUsage
  ADD Imported Integer Not Null Default 0
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>3183</SQLVERSION><RMTRACKLINK>IDBOS-2219</RMTRACKLINK><REASON>Dropped FK constraint for CNF_SalesRestriction on CNF_Event</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Event_CNF_SaleRestriction')
BEGIN
  ALTER TABLE CNF_Event
  DROP CONSTRAINT FK_CNF_Event_CNF_SaleRestriction
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>3182</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>IDBOS-2235 - History Log Improvement</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_HIL_CreateHILTrigger]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_HIL_CreateHILTrigger</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>CReate Procedure [dbo].[otn_sp_HIL_CreateHILTrigger]
	@TABLE_NAME sysname
AS 
BEGIN
	DECLARE @Logged int
	set @Logged = 0

	IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME= 'DATA_HL_Master')
	BEGIN

		
		INSERT INTO dbo.cnf_dbtable
			   (TABLENAME,
				Active,
				Logged,
				Last_UserId_Log,
				Last_WorkstationId_Log,
				Last_DateTime_Log)
		SELECT @TABLE_NAME, 
				0,
				0,  
				1,
				1,
				GetDate()
		FROM sys.tables AS t WITH(NOLOCK)
		where t.name = @TABLE_NAME
		  and t.name not in (select tablename from cnf_dbtable WITH(NOLOCK))	
		  	 
		INSERT INTO dbo.cnf_dbcolumn
			   (DBTableId,
				ColumnName,
				Active,
				logged,
				Last_UserId_Log,
				Last_WorkstationId_Log,
				Last_DateTime_Log)
		SELECT distinct HT.dbtableid AS tablesID, 
				c.name,
				0,
				0,
				1,
				1,  
				GetDate()
		FROM sys.tables AS t WITH(NOLOCK)
			INNER JOIN sys.columns c WITH(NOLOCK)				ON t.OBJECT_ID = c.OBJECT_ID 
			INNER JOIN cnf_dbtable HT WITH(NOLOCK)              ON HT.TableName = t.name	

		WHERE SCHEMA_NAME(schema_id) = 'dbo'
			and t.name = @TABLE_NAME
			AND (cast(HT.dbTableID as Varchar(5000)) + c.Name) not in (select (cast(DBTableID as Varchar(5000)) + ColumnName) from cnf_dbcolumn WITH(NOLOCK))


	--ACtivate logged and active
		Update cnf_dbtable
		   set Logged = case when (select 1 from cnf_dbtable DT where DT.TableName = @TABLE_NAME and DT.Logged = 1) = 1 then 1
							 else 0
						end,
			   Active = case when (select 1 from cnf_dbtable DT where DT.TableName = @TABLE_NAME and DT.Active = 1) = 1 then 1
							 else 0
						end
		WHERE  TableName = @TABLE_NAME
			AND TableName in (
	  							SELECT distinct t.name AS table_name
									FROM sys.tables AS t WITH(NOLOCK)
										INNER JOIN sys.columns c WITH(NOLOCK)				ON t.OBJECT_ID = c.OBJECT_ID 	
									WHERE c.name LIKE '%LAST%LOG'
										and SCHEMA_NAME(schema_id) = 'dbo'
							)
			AND TableName in (
								SELECT distinct t.name AS table_name
									FROM sys.tables AS t WITH(NOLOCK)
										INNER JOIN sys.columns c WITH(NOLOCK)				ON t.OBJECT_ID = c.OBJECT_ID 	
									WHERE c.name LIKE '%LAST%LOG'
										and SCHEMA_NAME(schema_id) = 'dbo'
										and ((T.name like '%ADM_%') or (t.name like '%CNF_%') or
												(t.name in ('DATA_Account', 'DATA_AccountFinancial', 'DATA_AccountRelationship', 'DATA_DmgData',
															'DATA_DmgData_Translate', 'DATA_Right')))
								)
			AND TableName NOT IN (SELECT table_name
								FROM information_schema.columns WITH(NOLOCK)
								where data_type in ('NTEXT', 'TEXT')
									AND TABLE_NAME in (
	  													SELECT distinct t.name AS table_name
															FROM sys.tables AS t WITH(NOLOCK)
																INNER JOIN sys.columns c WITH(NOLOCK)				ON t.OBJECT_ID = c.OBJECT_ID 	
															WHERE c.name LIKE '%LAST%LOG'
																and SCHEMA_NAME(schema_id) = 'dbo'
													))

	Update cnf_dbtable
	   set Logged = 0,
	       Active = 0
	WHERE  TableName = @TABLE_NAME
	  and TableName not in (select name
							  from sys.tables)


	Update cnf_dbcolumn
	  set Active = 1,
	      Logged = 1
	where DBTableid in (select dbtableid from cnf_dbtable WITH(NOLOCK) where active = 1 and logged = 1 and tablename = @TABLE_NAME)
	  and ColumnName not in ('Last_UserID_log', 'Last_WorkstationID_LOG', 'Last_DateTime_Log', 'LastFire', 'UserLogID', 'LastLogin', 'LastUpdDate')
	  and columnName in (select c.name
							from sys.tables AS t WITH(NOLOCK)				
								INNER JOIN sys.columns c WITH(NOLOCK)				ON t.OBJECT_ID = c.OBJECT_ID 
							where t.name = @TABLE_NAME)  

	Update cnf_dbcolumn
	  set Active = 0,
	      Logged = 0
	where DBTableid in (select dbtableid from cnf_dbtable WITH(NOLOCK) where active = 1 and logged = 1 and tablename = @TABLE_NAME)
	  and columnName not in (select c.name
							from sys.tables AS t WITH(NOLOCK)				
								INNER JOIN sys.columns c WITH(NOLOCK)				ON t.OBJECT_ID = c.OBJECT_ID 
							where t.name = @TABLE_NAME)  


	select @Logged = Logged from cnf_dbtable WITH(NOLOCK) where tablename = @TABLE_NAME
	if @Logged = 1 
	BEGIN
		DECLARE @sql NVARCHAR(max),
				@SQL1 NVARCHAR(MAX)

		SET NOCOUNT ON  

		EXEC('IF OBJECT_ID (''' + @TABLE_NAME + '_CT'', ''TR'') IS NOT NULL DROP TRIGGER ' + @TABLE_NAME + '_CT')
		SELECT @sql = 
		'create trigger ' + @TABLE_NAME + '_CT on ' + @TABLE_NAME + ' FOR insert, update, delete
		as
		declare @TName varchar(128),
		        @TID nvarchar(max),
				@TLog int,  
				@PKC varchar(max),
				@PKV varchar(max),  
				@sql nvarchar(max), 
				@Type nvarchar(1),
				@MId nvarchar(max) = ''0'', 
				@ColumnID nvarchar(max) = ''0'',
				@CName varchar(128),
				@CValue1 nvarchar(max),
				@CValue2 nvarchar(max)

		if exists(select top 1 1 from cnf_system where ISNULL(BOSHistoryLogEnabled, 1) = 1 and offlinemode = 0)
		BEGIN
			select @TName = ''' + @TABLE_NAME + ''', @TID=dbtableid, @TLog = (case when Active = 1 and Logged = 1 then 1 else 0 end) from cnf_dbtable WITH(NOLOCK) where TableName=''' + @TABLE_NAME + '''

			if @TLog = 1
			begin
				if exists (select * from inserted)
				if exists (select * from deleted)
				select @Type = ''2''      --Update
				else
				select @Type = ''3''      --Insert
				else
				select @Type = ''1''      --Delete

				select * into #ins from inserted
				select * into #del from deleted

				select @PKC = coalesce(@PKC + '' and'', '' on'') + '' i.'' + c.COLUMN_NAME + '' = d.'' + c.COLUMN_NAME, @PKV = coalesce(@PKV+''+'','''') + ''convert(varchar(100), coalesce(i.'' + COLUMN_NAME + '',d.'' + COLUMN_NAME + ''))''
				  from INFORMATION_SCHEMA.TABLE_CONSTRAINTS p WITH(NOLOCK)
					   INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE c WITH(NOLOCK) on c.CONSTRAINT_NAME = p.CONSTRAINT_NAME and c.TABLE_NAME = p.TABLE_NAME
				 where p.TABLE_NAME=@TName and CONSTRAINT_TYPE=''PRIMARY KEY''

				DECLARE TCursor CURSOR LOCAL FOR
								select columnName,
									   dbcolumnid
								from(
								select CNF_DBColumn.ColumnName,
									CNF_DBColumn.DBColumnId,
									(case when cnf_dbcolumn.Active = 1 and cnf_dbcolumn.Logged = 1 then 1 else 0 end) Active
									from sys.tables AS t WITH(NOLOCK)				
										INNER JOIN sys.columns c WITH(NOLOCK)				ON t.OBJECT_ID = c.OBJECT_ID 
										INNER JOIN cnf_dbtable WITH(NOLOCK)					on cnf_dbtable.tablename = t.name
										INNER JOIN cnf_dbcolumn WITH(NOLOCK)				on cnf_dbcolumn.dbtableid = cnf_dbtable.dbtableid and cnf_dbcolumn.columnname = c.name
								where cnf_dbcolumn.dbtableid = @TID
								)p
								where Active = 1

				OPEN TCursor

				FETCH NEXT FROM TCursor INTO
					@CName, @ColumnID
					'
			SELECT @sql1 = '
				WHILE @@FETCH_STATUS = 0
				BEGIN

					set @sql =''Select @CValue1 = '' + @CName +'' from #ins ''
					EXEC sp_executesql @sql, N''@CValue1 nvarchar(max) OUTPUT'', @CValue1 OUTPUT

					set @sql =''Select @CValue2 = '' + @CName +'' from #del ''
					EXEC sp_executesql @sql, N''@CValue2 nvarchar(max) OUTPUT'', @CValue2 OUTPUT

					if ISNULL(@CValue1, ''&amp;*()_2'') &lt;&gt; ISNULL(@CValue2, ''&amp;*()_2'')
					begin
						if @MId = 0
						begin
							set @sql = ''insert DATA_HL_Master (OperationType, dbtableid, ReferenceId, UserId, WorkstationId, InsDateTime, DelDateTime)''
							set @sql = @sql + '' select '''''' + @Type + ''''''''												
							set @sql = @sql + '', '''''' + @TID + ''''''''		
							set @sql = @sql + '','' + @PKV		
							set @sql = @sql + '', i.Last_UserId_Log, i.Last_WorkstationId_Log, i.Last_DateTime_Log, getdate()''
							set @sql = @sql + '' from #ins i full outer join #del d ''
							set @sql = @sql + @PKC 
							set @sql = @sql + '' SELECT @MId = SCOPE_IDENTITY()''
							EXEC sp_executesql @sql, N''@MId nvarchar(max) OUTPUT'', @MId OUTPUT
						end
						if @Type &lt;&gt; ''3''
						BEGIN
							set @sql = ''insert data_HL_Detail (MasterId, OriginalValue, ModifiedValue, DBColumnID)''						
							set @sql = @sql + '' select convert(varchar(1000),'' + @MId + ''), convert(varchar(1000),d.'' + @CName + ''), convert(varchar(1000),i.'' + @CName + '')''				
							set @sql = @sql + '', convert(varchar(1000),'' + @ColumnID + '')  ''
							set @sql = @sql + '' from #ins i full outer join #del d '' + @PKC				
							EXEC sp_executesql @sql 																	
						END		
						
					END
					FETCH NEXT FROM TCursor INTO
					   @CName, @ColumnID
				END  --While loop
				CLOSE TCursor;
				DEALLOCATE TCursor; 
			END    --Table Check
		END	-- System Check
		'

	EXEC(@sql + @sql1)
	END	
  END
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
FROM sys.indexes 
WHERE name='IDX_CNF_DBTable_TableName' AND object_id = OBJECT_ID('CNF_DBTable'))
begin
	CREATE UNIQUE NONCLUSTERED INDEX [IDX_CNF_DBTable_TableName] ON [dbo].[CNF_DBTable]
	(
		[TableName] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]

END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>BEGIN
	DECLARE @TableName nvarchar(100)
	DECLARE @TriggerName nvarchar(100)
	DECLARE @SQL nvarchar(250)
	
	DECLARE CT_Cursor CURSOR LOCAL FOR
								select TableName
								from cnf_dbtable
								WHERE Active = 0
								  and Logged = 1

	OPEN CT_Cursor

	FETCH NEXT FROM CT_Cursor INTO @TableName

	WHILE @@FETCH_STATUS = 0
	BEGIN
		Set @TriggerName = @TableName + '_CT'
		
		IF EXISTS (SELECT 1 FROM sys.triggers 
				   WHERE Name = @TriggerName)
		BEGIN
			Set @SQL = 'DISABLE TRIGGER [dbo].[' +  @TriggerName + '] ON [' + @TableName + ']'

			EXEC(@SQL)
		END

		FETCH NEXT FROM CT_Cursor INTO @TableName
	END
	CLOSE CT_Cursor;
	DEALLOCATE CT_Cursor;

End</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dchen</ADDEDBY><SQLVERSION>3181</SQLVERSION><RMTRACKLINK>87552</RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>if not exists(select * from sys.triggers where name = 'InsertFirtsUsage' )
    EXEC dbo.sp_executesql @statement = N'CREATE TRIGGER InsertFirtsUsage ON  DATA_TicketUsage 
						AFTER INSERT 
						AS 
						BEGIN
						  -- SET NOCOUNT ON added to prevent extra result sets from
						  -- interfering with SELECT statements.
						  SET NOCOUNT ON;
						  DECLARE @UsageId integer
						  DECLARE @TicketId integer
						  DECLARE @ValidateResult integer
						  DECLARE @UsageType integer
                                                  -- Insert statements for trigger here
						  IF NOT EXISTS(SELECT * FROM DELETED)
						  BEGIN
						    SELECT @UsageId=UsageId, @TicketId=TicketId, @ValidateResult=ValidateResult, @UsageType=UsageType FROM Inserted
						    IF (@ValidateResult &lt;= 99) AND (@UsageType=1)
						    BEGIN 
						      UPDATE DATA_Ticket 
						        SET FirstUsageId = ISNULL(FirstUsageId, @UsageId)
						      WHERE TicketId = @TicketId
						    END
						  END
                                          END'
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>UPDATE DATA_Ticket 
SET FirstUsageId = FU.UsageId
FROM 
  DATA_Ticket AS TI
  INNER JOIN (SELECT
		TU.TicketId,
		MIN(TU.UsageId) UsageId
	      FROM
		DATA_TicketUsage TU With(NoLock)
	      WHERE
	        UsageType = 1
	        AND ValidateResult &lt;= 99							
	      GROUP BY
	        TU.TicketId
	     ) FU ON (FU.TicketId = TI.TicketId AND (TI.FirstUsageId is null))</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3180</SQLVERSION><RMTRACKLINK>IDBOS-1177</RMTRACKLINK><REASON>0) Added Column BattelliActStatus to SIAE_Event table</REASON><TABLENAMES>SIAE_Event=EventId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
              WHERE Name = N'BattelliActStatus' 
              AND OBJECT_ID = OBJECT_ID(N'SIAE_Event'))
BEGIN
  ALTER TABLE SIAE_Event
  ADD BattelliActStatus Smallint Default 1 NOT NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3179</SQLVERSION><RMTRACKLINK>IDBOS-1177</RMTRACKLINK><REASON>0) Changing Column definition for --&gt; SIAE_SiaeLog.PuntoVenditaId
1) Adding New Table SIAE_SiaeLogAdditionalInfo
2) Adding Foreign Key FK_SIAE_SiaeLogAdditionalInfo_SiaeLogId</REASON><TABLENAMES>SIAE_SiaeLogAdditionalInfo=SiaeLogAdditionalInfoId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT * FROM sys.columns
          WHERE Name = N'PuntoVenditaId' 
          AND OBJECT_ID = OBJECT_ID(N'SIAE_SiaeLog'))
BEGIN
  ALTER TABLE SIAE_SiaeLog
  ALTER COLUMN PuntoVenditaId NVarChar(32) NULL 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND TABLE_NAME = 'SIAE_SiaeLogAdditionalInfo')
BEGIN
Create table SIAE_SiaeLogAdditionalInfo
(
	[SiaeLogAdditionalInfoId]  Integer IDENTITY(1,1) NOT NULL,
	[SiaeLogId] Integer NOT NULL,
	[AcquirenteTipoAutenticazione] Smallint NOT NULL,
	[AcquirenteAK] varchar(32) NULL,
	[AcquirenteCellulare] varchar(32) NULL,
	[AcquirenteEMail] varchar(50) NULL,
	[AcquirenteMetodoSpedizione] varchar(50) NULL,
	[AcquirenteIndirizzoSpedizione] varchar(400) NULL,
	[AcquirenteIP] varchar(15) NULL,
	[AcquirenteDataOraRegistrazione] Datetime NULL,
	[TransazioneAK] varchar(32) NULL,
	[TransazioneIP] varchar(15) NULL,
	[TransazioneDataOraChekOut] DateTime NULL,
	[TransazioneDataOraPagamento] DateTime NULL,
	[TransazioneCRO] varchar(50) NULL,
	[NomePartecipante] varchar(50) NULL,
	[CognomePartecipante] varchar(50) NULL,
Primary Key ([SiaeLogAdditionalInfoId])
) 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_SIAE_SiaeLogAdditionalInfo_SiaeLogId')
BEGIN
  ALTER TABLE SIAE_SiaeLogAdditionalInfo
  ADD CONSTRAINT [FK_SIAE_SiaeLogAdditionalInfo_SiaeLogId] FOREIGN KEY([SiaeLogId]) 
  REFERENCES [SIAE_SiaeLog] ([SiaeLogId])
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>scoluccia</ADDEDBY><SQLVERSION>3178</SQLVERSION><RMTRACKLINK>IDBOS-1606</RMTRACKLINK><REASON>Added a field named TckValidityId in DATA_Biometric and  DATA_Biometric2Ticket and this is a foreign key to OFF_TckValidity</REASON><TABLENAMES>DATA_Biometric=BiometricId
DATA_Biometric2Ticket=Biometric2TicketId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'TckValidityId' 
                      AND OBJECT_ID = OBJECT_ID(N'DATA_Biometric'))
BEGIN
  ALTER TABLE DATA_Biometric
  ADD TckValidityId Integer NULL 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_Biometric_TckValidityId')
BEGIN
  ALTER TABLE DATA_Biometric
  ADD CONSTRAINT [FK_DATA_Biometric_TckValidityId] FOREIGN KEY([TckValidityId]) 
  REFERENCES [OFF_TckValidity] ([TckValidityId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'TckValidityId' 
                      AND OBJECT_ID = OBJECT_ID(N'DATA_Biometric2Ticket'))
BEGIN
  ALTER TABLE DATA_Biometric2Ticket
  ADD TckValidityId Integer NULL 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_Biometric2Ticket_TckValidityId')
BEGIN
  ALTER TABLE DATA_Biometric2Ticket
  ADD CONSTRAINT [FK_DATA_Biometric2Ticket_TckValidityId] FOREIGN KEY([TckValidityId]) 
  REFERENCES [OFF_TckValidity] ([TckValidityId])
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>ecandido</ADDEDBY><SQLVERSION>3177</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>Add field to identify the workstation number that is able to make synchronization between Online and Offline database</REASON><TABLENAMES>CNF_System=SystemId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>if not exists (select
                 column_name
               from
                 INFORMATION_SCHEMA.columns
               where
                 table_name = 'CNF_System' and
                 column_name = 'WorkstationOfflineSync')
  alter table CNF_System add WorkstationOfflineSync int
</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fesposito</ADDEDBY><SQLVERSION>3176</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>Recreating DATA_TicketExport, Deleting DATA_TicketExportDetail,DATA_TicketExport2Ticket</REASON><TABLENAMES>DATA_TicketExport=TicketExportId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>BEGIN
 
  DECLARE @stmt VARCHAR(300);
 
  -- Cursor to generate ALTER TABLE DROP CONSTRAINT statements  
  DECLARE cur CURSOR FOR
     SELECT 'ALTER TABLE ' + OBJECT_SCHEMA_NAME(parent_object_id) + '.' + OBJECT_NAME(parent_object_id) +
                    ' DROP CONSTRAINT ' + name
     FROM sys.foreign_keys 
     WHERE OBJECT_SCHEMA_NAME(referenced_object_id) = 'dbo' AND 
                OBJECT_NAME(referenced_object_id) = 'DATA_TicketExport';
 
   OPEN cur;
   FETCH cur INTO @stmt;
 
   -- Drop each found foreign key constraint 
   WHILE @@FETCH_STATUS = 0
     BEGIN
       EXEC (@stmt);
       FETCH cur INTO @stmt;
     END
 
  CLOSE cur;
  DEALLOCATE cur;
 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS ( SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND  TABLE_NAME = 'DATA_TicketExport2Ticket' )

BEGIN
   DROP TABLE DATA_TicketExport2Ticket
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS ( SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND  TABLE_NAME = 'DATA_TicketExportDetail' )

BEGIN
   DROP TABLE DATA_TicketExportDetail
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS ( SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND  TABLE_NAME = 'DATA_TicketExport' )

BEGIN
   DROP TABLE DATA_TicketExport
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                WHERE TABLE_SCHEMA = 'dbo' 
                  AND TABLE_NAME = 'DATA_TicketExport')
BEGIN
Create table [DATA_TicketExport]
(
	[TicketExportId] Integer Identity(1,1) NOT NULL,
	[UserId] Integer NOT NULL,
	[WorkstationId] Integer NOT NULL,
	[PerformanceId] Integer NOT NULL,
	[CreationDateTime] Datetime NOT NULL,
	[StartDateTime] Datetime NOT NULL,
Primary Key ([TicketExportId])
) 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_TicketExport_UserId')
BEGIN
  ALTER TABLE DATA_TicketExport
  ADD CONSTRAINT [FK_DATA_TicketExport_UserId] FOREIGN KEY([UserId]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_TicketExport_WorkstationId')
BEGIN
  ALTER TABLE DATA_TicketExport
  ADD CONSTRAINT [FK_DATA_TicketExport_WorkstationId] FOREIGN KEY([WorkstationId]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_TicketExport_PerformanceId')
BEGIN
  ALTER TABLE DATA_TicketExport
  ADD CONSTRAINT [FK_DATA_TicketExport_PerformanceId] FOREIGN KEY([PerformanceId]) 
  REFERENCES [CNF_Performance] ([PerformanceId])
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>3175</SQLVERSION><RMTRACKLINK>IDBOS-2144</RMTRACKLINK><REASON>Drop all tables related to the VRO system and Tessera del tifoso

[0] Drop column and FK from SIAE_Event
[1] Drop all indexes
[2] Drop VRO tables
[3] Drop LTA tables
[4] Drop GEO table
[5] Drop TDT tables</REASON><TABLENAMES>SIAE_Event=EventId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * 
           FROM sys.foreign_keys 
	   WHERE object_id = OBJECT_ID(N'dbo.fkSIAE_CNF_SoccerLtaTask_SIAE_Event_TaskId')
           AND parent_object_id = OBJECT_ID(N'dbo.SIAE_Event'))
BEGIN
  ALTER TABLE SIAE_Event DROP CONSTRAINT fkSIAE_CNF_SoccerLtaTask_SIAE_Event_TaskId
END

IF EXISTS(SELECT * FROM sys.columns
          WHERE Name = N'SoccerLtaTaskId' 
          AND OBJECT_ID = OBJECT_ID(N'SIAE_Event'))
BEGIN
  ALTER TABLE SIAE_Event
  DROP COLUMN SoccerLtaTaskId
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS ( SELECT * FROM sys.indexes 
            WHERE name='Idx_DATA_Account_VroAccount' AND object_id = OBJECT_ID('SIAE_VroAccounts'))
BEGIN
  DROP INDEX Idx_DATA_Account_VroAccount ON SIAE_VroAccounts
END

IF EXISTS ( SELECT * FROM sys.indexes 
            WHERE name='Idx_VroMex_Date' AND object_id = OBJECT_ID('SIAE_VroMessages'))
BEGIN
  DROP INDEX Idx_VroMex_Date ON SIAE_VroMessages
END

IF EXISTS ( SELECT * FROM sys.indexes 
            WHERE name='Idx_VroMex_RequestType' AND object_id = OBJECT_ID('SIAE_VroMessages'))
BEGIN
  DROP INDEX Idx_VroMex_RequestType ON SIAE_VroMessages
END

IF EXISTS ( SELECT * FROM sys.indexes 
            WHERE name='Idx_VroRel_VroAccountId' AND object_id = OBJECT_ID('SIAE_VroRelationships'))
BEGIN
  DROP INDEX Idx_VroRel_VroAccountId ON SIAE_VroRelationships
END

IF EXISTS ( SELECT * FROM sys.indexes 
            WHERE name='Idx_VroRel_SaleItem_Ticket' AND object_id = OBJECT_ID('SIAE_VroRelationships'))
BEGIN
  DROP INDEX Idx_VroRel_SaleItem_Ticket ON SIAE_VroRelationships
END

IF EXISTS ( SELECT * FROM sys.indexes 
            WHERE name='Idx_VroRel_Account_Perf_VroAccountId' AND object_id = OBJECT_ID('SIAE_VroRelationships'))
BEGIN
  DROP INDEX Idx_VroRel_Account_Perf_VroAccountId ON SIAE_VroRelationships
END

IF EXISTS ( SELECT * FROM sys.indexes 
            WHERE name='Idx_VroRel_Account_Perf_SaleItem' AND object_id = OBJECT_ID('SIAE_VroRelationships'))
BEGIN
  DROP INDEX Idx_VroRel_Account_Perf_SaleItem ON SIAE_VroRelationships
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * 
           FROM INFORMATION_SCHEMA.TABLES 
           WHERE TABLE_SCHEMA = 'dbo' 
           AND TABLE_NAME = 'SIAE_VroAccounts')
BEGIN
  DROP TABLE SIAE_VroAccounts
END

IF EXISTS (SELECT * 
           FROM INFORMATION_SCHEMA.TABLES 
           WHERE TABLE_SCHEMA = 'dbo' 
           AND TABLE_NAME = 'SIAE_VroControlPanel')
BEGIN
  DROP TABLE SIAE_VroControlPanel
END

IF EXISTS (SELECT * 
           FROM INFORMATION_SCHEMA.TABLES 
           WHERE TABLE_SCHEMA = 'dbo' 
           AND TABLE_NAME = 'SIAE_VroMessages')
BEGIN
  DROP TABLE SIAE_VroMessages
END

IF EXISTS (SELECT * 
           FROM INFORMATION_SCHEMA.TABLES 
           WHERE TABLE_SCHEMA = 'dbo' 
           AND TABLE_NAME = 'SIAE_VroRelationships')
BEGIN
  DROP TABLE SIAE_VroRelationships
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT * FROM sys.columns
          WHERE Name = N'SoccerLtaTaskId' 
          AND OBJECT_ID = OBJECT_ID(N'SIAE_Event'))
BEGIN
  ALTER TABLE SIAE_Event
  DROP COLUMN SoccerLtaTaskId
END

IF EXISTS (SELECT * 
           FROM INFORMATION_SCHEMA.TABLES 
           WHERE TABLE_SCHEMA = 'dbo' 
           AND TABLE_NAME = 'SIAE_DATA_SoccerLtaTaskItem')
BEGIN
  DROP TABLE SIAE_DATA_SoccerLtaTaskItem
END

IF EXISTS (SELECT * 
           FROM INFORMATION_SCHEMA.TABLES 
           WHERE TABLE_SCHEMA = 'dbo' 
           AND TABLE_NAME = 'SIAE_CNF_SoccerLtaTaskItemRule')
BEGIN
  DROP TABLE SIAE_CNF_SoccerLtaTaskItemRule
END

IF EXISTS (SELECT * 
           FROM INFORMATION_SCHEMA.TABLES 
           WHERE TABLE_SCHEMA = 'dbo' 
           AND TABLE_NAME = 'SIAE_CNF_SoccerLtaTaskItem')
BEGIN
  DROP TABLE SIAE_CNF_SoccerLtaTaskItem
END

IF EXISTS (SELECT * 
           FROM INFORMATION_SCHEMA.TABLES 
           WHERE TABLE_SCHEMA = 'dbo' 
           AND TABLE_NAME = 'SIAE_CNF_SoccerLtaTask')
BEGIN
  DROP TABLE SIAE_CNF_SoccerLtaTask
END

IF EXISTS (SELECT * 
           FROM INFORMATION_SCHEMA.TABLES 
           WHERE TABLE_SCHEMA = 'dbo' 
           AND TABLE_NAME = 'SIAE_SoccerLtaTask2PerfItemRule')
BEGIN
  DROP TABLE SIAE_SoccerLtaTask2PerfItemRule
END

IF EXISTS (SELECT * 
           FROM INFORMATION_SCHEMA.TABLES 
           WHERE TABLE_SCHEMA = 'dbo' 
           AND TABLE_NAME = 'SIAE_SoccerLtaTask2PerfItem')
BEGIN
  DROP TABLE SIAE_SoccerLtaTask2PerfItem
END

IF EXISTS (SELECT * 
           FROM INFORMATION_SCHEMA.TABLES 
           WHERE TABLE_SCHEMA = 'dbo' 
           AND TABLE_NAME = 'SIAE_SoccerLtaTask2Performance')
BEGIN
  DROP TABLE SIAE_SoccerLtaTask2Performance
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * 
           FROM INFORMATION_SCHEMA.TABLES 
           WHERE TABLE_SCHEMA = 'dbo' 
           AND TABLE_NAME = 'SIAE_GeoEntity')
BEGIN
  DROP TABLE SIAE_GeoEntity
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * 
           FROM INFORMATION_SCHEMA.TABLES 
           WHERE TABLE_SCHEMA = 'dbo' 
           AND TABLE_NAME = 'SIAE_TesseraTifosoRule2Entity')
BEGIN
  DROP TABLE SIAE_TesseraTifosoRule2Entity
END

IF EXISTS (SELECT * 
           FROM INFORMATION_SCHEMA.TABLES 
           WHERE TABLE_SCHEMA = 'dbo' 
           AND TABLE_NAME = 'SIAE_TesseraTifosoRule')
BEGIN
  DROP TABLE SIAE_TesseraTifosoRule
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>pdalben</ADDEDBY><SQLVERSION>3174</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>Added DATA_DeviceOperations.OperationCompleted</REASON><TABLENAMES>DATA_DeviceOperations=DevOpId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
WHERE Name = N'OperationCompleted' AND OBJECT_ID = OBJECT_ID(N'DATA_DeviceOperations'))
BEGIN
  ALTER TABLE DATA_DeviceOperations ADD OperationCompleted Smallint Default 0 NOT NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT * FROM sys.columns
WHERE Name = N'OperationCompleted' AND OBJECT_ID = OBJECT_ID(N'DATA_DeviceOperations'))
BEGIN
  UPDATE DATA_DeviceOperations SET OperationCompleted = 1
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>3173</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_HIL_CreateHILTrigger]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_HIL_CreateHILTrigger</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>CREATE Procedure dbo.otn_sp_HIL_CreateHILTrigger
	@TABLE_NAME sysname
AS 
BEGIN
	DECLARE @Logged int
	set @Logged = 0

	IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME= 'DATA_HL_Master')
	BEGIN

		
		INSERT INTO dbo.cnf_dbtable
			   (TABLENAME,
				Active,
				Logged,
				Last_UserId_Log,
				Last_WorkstationId_Log,
				Last_DateTime_Log)
		SELECT @TABLE_NAME, 
				0,
				0,  
				1,
				1,
				GetDate()
		FROM sys.tables AS t WITH(NOLOCK)
		where t.name = @TABLE_NAME
		  and t.name not in (select tablename from cnf_dbtable WITH(NOLOCK))	
		  	 
		INSERT INTO dbo.cnf_dbcolumn
			   (DBTableId,
				ColumnName,
				Active,
				logged,
				Last_UserId_Log,
				Last_WorkstationId_Log,
				Last_DateTime_Log)
		SELECT distinct HT.dbtableid AS tablesID, 
				c.name,
				0,
				0,
				1,
				1,  
				GetDate()
		FROM sys.tables AS t WITH(NOLOCK)
			INNER JOIN sys.columns c WITH(NOLOCK)				ON t.OBJECT_ID = c.OBJECT_ID 
			INNER JOIN cnf_dbtable HT WITH(NOLOCK)              ON HT.TableName = t.name	

		WHERE SCHEMA_NAME(schema_id) = 'dbo'
			and t.name = @TABLE_NAME
			AND (cast(HT.dbTableID as Varchar(5000)) + c.Name) not in (select (cast(DBTableID as Varchar(5000)) + ColumnName) from cnf_dbcolumn WITH(NOLOCK))


--ACtivate logged and active
	Update cnf_dbtable
	   set Logged = 1,
	       Active = 1
	WHERE  TableName = @TABLE_NAME
	    AND TableName in (
	  						SELECT distinct t.name AS table_name
								FROM sys.tables AS t WITH(NOLOCK)
									INNER JOIN sys.columns c WITH(NOLOCK)				ON t.OBJECT_ID = c.OBJECT_ID 	
								WHERE c.name LIKE '%LAST%LOG'
									and SCHEMA_NAME(schema_id) = 'dbo'
						)
		AND TableName in (
							SELECT distinct t.name AS table_name
								FROM sys.tables AS t WITH(NOLOCK)
									INNER JOIN sys.columns c WITH(NOLOCK)				ON t.OBJECT_ID = c.OBJECT_ID 	
								WHERE c.name LIKE '%LAST%LOG'
									and SCHEMA_NAME(schema_id) = 'dbo'
									and ((T.name like '%ADM_%') or (t.name like '%CNF_%') or
											(t.name in ('DATA_Account', 'DATA_AccountFinancial', 'DATA_AccountRelationship', 'DATA_DmgData',
														'DATA_DmgData_Translate', 'DATA_Right')))
							)
		AND TableName NOT IN (SELECT table_name
							FROM information_schema.columns WITH(NOLOCK)
							where data_type in ('NTEXT', 'TEXT')
								AND TABLE_NAME in (
	  												SELECT distinct t.name AS table_name
														FROM sys.tables AS t WITH(NOLOCK)
															INNER JOIN sys.columns c WITH(NOLOCK)				ON t.OBJECT_ID = c.OBJECT_ID 	
														WHERE c.name LIKE '%LAST%LOG'
															and SCHEMA_NAME(schema_id) = 'dbo'
												))

	Update cnf_dbtable
	   set Logged = 0,
	       Active = 0
	WHERE  TableName = @TABLE_NAME
	  and TableName not in (select name
							  from sys.tables)


	Update cnf_dbcolumn
	  set Active = 1,
	      Logged = 1
	where DBTableid in (select dbtableid from cnf_dbtable WITH(NOLOCK) where active = 1 and logged = 1 and tablename = @TABLE_NAME)
	  and ColumnName not in ('Last_UserID_log', 'Last_WorkstationID_LOG', 'Last_DateTime_Log', 'LastFire', 'UserLogID', 'LastLogin', 'LastUpdDate')
	  and columnName in (select c.name
							from sys.tables AS t WITH(NOLOCK)				
								INNER JOIN sys.columns c WITH(NOLOCK)				ON t.OBJECT_ID = c.OBJECT_ID 
							where t.name = @TABLE_NAME)  

	Update cnf_dbcolumn
	  set Active = 0,
	      Logged = 0
	where DBTableid in (select dbtableid from cnf_dbtable WITH(NOLOCK) where active = 1 and logged = 1 and tablename = @TABLE_NAME)
	  and columnName not in (select c.name
							from sys.tables AS t WITH(NOLOCK)				
								INNER JOIN sys.columns c WITH(NOLOCK)				ON t.OBJECT_ID = c.OBJECT_ID 
							where t.name = @TABLE_NAME)  


	select @Logged = Logged from cnf_dbtable WITH(NOLOCK) where tablename = @TABLE_NAME
	if @Logged = 1 
	BEGIN
		DECLARE @sql NVARCHAR(max),
				@SQL1 NVARCHAR(MAX)

		SET NOCOUNT ON  

		EXEC('IF OBJECT_ID (''' + @TABLE_NAME + '_CT'', ''TR'') IS NOT NULL DROP TRIGGER ' + @TABLE_NAME + '_CT')
		SELECT @sql = 
		'create trigger ' + @TABLE_NAME + '_CT on ' + @TABLE_NAME + ' FOR insert, update, delete
		as
		declare @TName varchar(128),
		        @TID nvarchar(max),
				@TLog int,  
				@PKC varchar(max),
				@PKV varchar(max),  
				@sql nvarchar(max), 
				@Type nvarchar(1),
				@MId nvarchar(max) = ''0'', 
				@ColumnID nvarchar(max) = ''0'',
				@CName varchar(128),
				@CValue1 nvarchar(max),
				@CValue2 nvarchar(max)

		if exists(select top 1 1 from cnf_system where ISNULL(BOSHistoryLogEnabled, 1) = 1 and offlinemode = 0)
		BEGIN
			select @TName = ''' + @TABLE_NAME + ''', @TID=dbtableid, @TLog = (case when Active = 1 and Logged = 1 then 1 else 0 end) from cnf_dbtable WITH(NOLOCK) where TableName=''' + @TABLE_NAME + '''

			if @TLog = 1
			begin
				if exists (select * from inserted)
				if exists (select * from deleted)
				select @Type = ''2''      --Update
				else
				select @Type = ''3''      --Insert
				else
				select @Type = ''1''      --Delete

				select * into #ins from inserted
				select * into #del from deleted

				select @PKC = coalesce(@PKC + '' and'', '' on'') + '' i.'' + c.COLUMN_NAME + '' = d.'' + c.COLUMN_NAME, @PKV = coalesce(@PKV+''+'','''') + ''convert(varchar(100), coalesce(i.'' + COLUMN_NAME + '',d.'' + COLUMN_NAME + ''))''
				  from INFORMATION_SCHEMA.TABLE_CONSTRAINTS p WITH(NOLOCK)
					   INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE c WITH(NOLOCK) on c.CONSTRAINT_NAME = p.CONSTRAINT_NAME and c.TABLE_NAME = p.TABLE_NAME
				 where p.TABLE_NAME=@TName and CONSTRAINT_TYPE=''PRIMARY KEY''

				DECLARE TCursor CURSOR LOCAL FOR
								select columnName,
									   dbcolumnid
								from(
								select CNF_DBColumn.ColumnName,
									CNF_DBColumn.DBColumnId,
									(case when cnf_dbcolumn.Active = 1 and cnf_dbcolumn.Logged = 1 then 1 else 0 end) Active
									from sys.tables AS t WITH(NOLOCK)				
										INNER JOIN sys.columns c WITH(NOLOCK)				ON t.OBJECT_ID = c.OBJECT_ID 
										INNER JOIN cnf_dbtable WITH(NOLOCK)					on cnf_dbtable.tablename = t.name
										INNER JOIN cnf_dbcolumn WITH(NOLOCK)				on cnf_dbcolumn.dbtableid = cnf_dbtable.dbtableid and cnf_dbcolumn.columnname = c.name
								where cnf_dbcolumn.dbtableid = @TID
								)p
								where Active = 1

				OPEN TCursor

				FETCH NEXT FROM TCursor INTO
					@CName, @ColumnID
					'
			SELECT @sql1 = '
				WHILE @@FETCH_STATUS = 0
				BEGIN

					set @sql =''Select @CValue1 = '' + @CName +'' from #ins ''
					EXEC sp_executesql @sql, N''@CValue1 nvarchar(max) OUTPUT'', @CValue1 OUTPUT

					set @sql =''Select @CValue2 = '' + @CName +'' from #del ''
					EXEC sp_executesql @sql, N''@CValue2 nvarchar(max) OUTPUT'', @CValue2 OUTPUT

					if ISNULL(@CValue1, ''&amp;*()_2'') &lt;&gt; ISNULL(@CValue2, ''&amp;*()_2'')
					begin
						if @MId = 0
						begin
							set @sql = ''insert DATA_HL_Master (OperationType, dbtableid, ReferenceId, UserId, WorkstationId, InsDateTime, DelDateTime)''
							set @sql = @sql + '' select '''''' + @Type + ''''''''												
							set @sql = @sql + '', '''''' + @TID + ''''''''		
							set @sql = @sql + '','' + @PKV		
							set @sql = @sql + '', i.Last_UserId_Log, i.Last_WorkstationId_Log, i.Last_DateTime_Log, getdate()''
							set @sql = @sql + '' from #ins i full outer join #del d ''
							set @sql = @sql + @PKC 
							set @sql = @sql + '' SELECT @MId = SCOPE_IDENTITY()''
							EXEC sp_executesql @sql, N''@MId nvarchar(max) OUTPUT'', @MId OUTPUT
						end
						if @Type &lt;&gt; ''3''
						BEGIN
							set @sql = ''insert data_HL_Detail (MasterId, OriginalValue, ModifiedValue, DBColumnID)''						
							set @sql = @sql + '' select convert(varchar(1000),'' + @MId + ''), convert(varchar(1000),d.'' + @CName + ''), convert(varchar(1000),i.'' + @CName + '')''				
							set @sql = @sql + '', convert(varchar(1000),'' + @ColumnID + '')  ''
							set @sql = @sql + '' from #ins i full outer join #del d '' + @PKC				
							EXEC sp_executesql @sql 																	
						END		
						
					END
					FETCH NEXT FROM TCursor INTO
					   @CName, @ColumnID
				END  --While loop
				CLOSE TCursor;
				DEALLOCATE TCursor; 
			END    --Table Check
		END	-- System Check
		'

	EXEC(@sql + @sql1)
	END	
  END
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>declare @TABLE_NAME sysname

SELECT @TABLE_NAME = MIN(Table_Name)
  FROM INFORMATION_SCHEMA.Tables 
 WHERE TABLE_TYPE = 'BASE TABLE' 
	AND TABLE_NAME != 'sysdiagrams'
	AND TABLE_SCHEMA = 'dbo'


WHILE @TABLE_NAME IS NOT NULL
BEGIN
	Exec otn_sp_HIL_CreateHILTrigger @TABLE_NAME

	SELECT @TABLE_NAME = MIN(Table_Name)
	  FROM INFORMATION_SCHEMA.Tables 
     WHERE TABLE_NAME &gt; @TABLE_NAME
	   AND TABLE_TYPE = 'BASE TABLE' 
	   AND TABLE_NAME != 'sysdiagrams'
	   AND TABLE_SCHEMA = 'dbo'

END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>pchen</ADDEDBY><SQLVERSION>3172</SQLVERSION><RMTRACKLINK>IDBOS-2027</RMTRACKLINK><REASON>Append a field named Purged in DATA_HL_Master</REASON><TABLENAMES>DATA_HL_Master=MasterId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'Purged' 
                      AND OBJECT_ID = OBJECT_ID(N'DATA_HL_Master'))
BEGIN
  ALTER TABLE DATA_HL_Master
  ADD Purged Smallint NULL 
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3171</SQLVERSION><RMTRACKLINK>IDBOS-2026</RMTRACKLINK><REASON>Removed DATA_HistoryLog Table
[0] Deleted Stored Procedures
[1] Deleted DATA_HistoryLog Table</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * 
           FROM INFORMATION_SCHEMA.ROUTINES 
           WHERE ROUTINE_NAME = 'otn_sp_ui_DATA_HistoryLog_insert')
BEGIN
     DROP PROCEDURE dbo.otn_sp_ui_DATA_HistoryLog_insert
END

IF EXISTS (SELECT * 
           FROM INFORMATION_SCHEMA.ROUTINES 
           WHERE ROUTINE_NAME = 'otn_sp_ui_DATA_HistoryLog_update')
BEGIN
     DROP PROCEDURE dbo.otn_sp_ui_DATA_HistoryLog_update
END

IF EXISTS (SELECT * 
           FROM INFORMATION_SCHEMA.ROUTINES 
           WHERE ROUTINE_NAME = 'otn_sp_ui_DATA_HistoryLog_delete')
BEGIN
     DROP PROCEDURE dbo.otn_sp_ui_DATA_HistoryLog_delete
END  </SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * 
           FROM INFORMATION_SCHEMA.TABLES 
           WHERE TABLE_SCHEMA = 'dbo' 
           AND TABLE_NAME = 'DATA_HistoryLog')
BEGIN
	DROP TABLE DATA_HistoryLog
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>lfornaroli</ADDEDBY><SQLVERSION>3170</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>CNF_MatrixCell
[0] add Field WalletId
[1] add FK on Doctemplate</REASON><TABLENAMES>CNF_MatrixCell=MatrixCellId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'WalletId' 
                      AND OBJECT_ID = OBJECT_ID(N'CNF_MatrixCell'))
BEGIN
  ALTER TABLE CNF_MatrixCell
  ADD WalletId Integer NULL 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (
               Select  f.name
               From sys.foreign_keys AS f
                 INNER JOIN sys.foreign_key_columns AS fc ON f.object_id = fc.constraint_object_id    
               Where f.parent_object_id     = object_id(N'[dbo].[CNF_MatrixCell]')          
                 AND f.referenced_object_id = object_id(N'[dbo].[CNF_DocTemplate]')           
                 AND COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'WalletId'
               )
BEGIN
  Alter table [CNF_MatrixCell] add foreign key([WalletId]) references [CNF_DocTemplate] ([DocTemplateId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>declare @foreign_key_name nvarchar(200)
declare  @dropstmt nvarchar(1000)
SELECT @foreign_key_name = f.name
  FROM sys.foreign_keys AS f
INNER JOIN sys.foreign_key_columns AS fc ON f.object_id = fc.constraint_object_id    
WHERE f.parent_object_id     = object_id(N'[dbo].[CNF_MatrixCell]')            
  AND f.referenced_object_id = object_id(N'[dbo].[CNF_DocTemplate]')            
  AND COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'WalletId';

IF (LEN(@foreign_key_name) = 0) 
begin
  SELECT @dropstmt = 'Alter table [CNF_MatrixCell] add  foreign key([WalletId]) references [CNF_DocTemplate] ([DocTemplateId])' 
  EXECUTE sp_executesql @dropstmt
end;
</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>3169</SQLVERSION><RMTRACKLINK>IDBOS-1792</RMTRACKLINK><REASON>Renamed 'ToAuthorize' to 'InvoiceStatus'</REASON><TABLENAMES>DATA_InvoiceData=InvoiceDataId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'ToAuthorize' 
                      AND OBJECT_ID = OBJECT_ID(N'DATA_InvoiceData'))
BEGIN
  ALTER TABLE DATA_InvoiceData
  DROP COLUMN ToAuthorize 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'InvoiceStatus' 
                      AND OBJECT_ID = OBJECT_ID(N'DATA_InvoiceData'))
BEGIN
  ALTER TABLE DATA_InvoiceData
  ADD InvoiceStatus Smallint NULL 
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>3168</SQLVERSION><RMTRACKLINK>IDBOS-1792</RMTRACKLINK><REASON>Added 2 new fields to DATA_InvoiceData:
1)ToAuthorize
2)InternalId</REASON><TABLENAMES>DATA_InvoiceData=InvoiceDataId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'ToAuthorize' 
                      AND OBJECT_ID = OBJECT_ID(N'DATA_InvoiceData'))
BEGIN
  ALTER TABLE DATA_InvoiceData
  ADD ToAuthorize Smallint NULL 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'InternalId' 
                      AND OBJECT_ID = OBJECT_ID(N'DATA_InvoiceData'))
BEGIN
  ALTER TABLE DATA_InvoiceData
  ADD InternalId Integer NULL 
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>3167</SQLVERSION><RMTRACKLINK>IDBOS-1885</RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>Update cnf_dbtable
   set Logged = 0,
       Active = 0
from cnf_dbtable
where tablename = 'CNF_EnvelopeCapacity'</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>update cnf_dbtable
   set Active = 0
where tablename in ('CNF_Seat', 
                    'CNF_SpaceStructure', 
					'SEAT_CNF_SpaceStructureSeat', 
					'CNF_SeatCategory'
				   )</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>update cnf_dbcolumn
   set Active = 0,
       Logged = 0
where dbtableid in (select dbtableid  
                      from cnf_dbtable
					 where TableName = 'CNF_Scheduler'
				    )
  and columnName = 'LastFire'</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>update cnf_dbcolumn
   set Active = 0,
       Logged = 0
where dbtableid in (select dbtableid  
                      from cnf_dbtable
					 where TableName = 'CNF_Workstation'
				    )
  and columnName = 'UserLogID'</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>update cnf_dbcolumn
   set Active = 0,
       Logged = 0
where dbtableid in (select dbtableid  
                      from cnf_dbtable
					 where TableName = 'CNF_User'
				    )
  and columnName = 'LastLogin'</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>update cnf_dbcolumn
   set Active = 0,
       Logged = 0
where dbtableid in (select dbtableid  
                      from cnf_dbtable
		     where TableName = 'CNF_Matrixcell'
		    )
  and columnName = 'LastUpdDate'</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3166</SQLVERSION><RMTRACKLINK>71332</RMTRACKLINK><REASON>Add FontStyleXML in order to store the label font style informations.</REASON><TABLENAMES>CNF_DataMask=DataMaskId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'FontStyleXML' AND
                Object_ID  = Object_ID(N'CNF_DataMask'))
BEGIN
  Alter Table CNF_DataMask
  Add FontStyleXML Nvarchar(500) NULL
END

</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fdipalma</ADDEDBY><SQLVERSION>3165</SQLVERSION><RMTRACKLINK>IDBOS-1792</RMTRACKLINK><REASON>Changing 2 fields in DATA_InvoiceData as Int:
1)CreditNoteTransactionId
2)CreditNoteAccountId</REASON><TABLENAMES>DATA_InvoiceData=InvoiceDataId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'CreditNoteTransactionId' 
                      AND OBJECT_ID = OBJECT_ID(N'DATA_InvoiceData'))
BEGIN
  ALTER TABLE DATA_InvoiceData
  ALTER COLUMN CreditNoteTransactionId int NULL 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'CreditNoteAccountId' 
                      AND OBJECT_ID = OBJECT_ID(N'DATA_InvoiceData'))
BEGIN
  ALTER TABLE DATA_InvoiceData
  ALTER COLUMN CreditNoteAccountId int NULL 
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>3164</SQLVERSION><RMTRACKLINK>IDBOS-1792</RMTRACKLINK><REASON>Added field 'External Type' to CNF_Invoice</REASON><TABLENAMES>CNF_Invoice=InvoiceId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'ExternalType' 
                      AND OBJECT_ID = OBJECT_ID(N'CNF_Invoice'))
BEGIN
  ALTER TABLE CNF_Invoice
  ADD ExternalType Smallint NULL 
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>3163</SQLVERSION><RMTRACKLINK>IDBOS1916</RMTRACKLINK><REASON>Data Mask Categories - Unable to open tile, attached SQL error displays</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>update cnf_doctemplate
   set dmgcategoryid = null
where dmgcategoryID in (select dmgcategoryid 
                          from cnf_dmgcategory 
						 where dmgtype = 11
						  and dmgparentid is null
						  and dmgcategorycode &lt;&gt; 'DUMMY'
						)</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>delete from CNF_DmgCategory
where dmgtype = 11
  and dmgparentid is null
  and dmgcategorycode &lt;&gt; 'DUMMY'</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>3162</SQLVERSION><RMTRACKLINK>IDBOS-1792</RMTRACKLINK><REASON>Added 4 fields to DATA_InvoiceData:
1)CreditNoteTransactionId
2)DocumentType
3)DocumentGeneralType
4)CreditNoteAccountId</REASON><TABLENAMES>DATA_InvoiceData=InvoiceDataId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'CreditNoteTransactionId' 
                      AND OBJECT_ID = OBJECT_ID(N'DATA_InvoiceData'))
BEGIN
  ALTER TABLE DATA_InvoiceData
  ADD CreditNoteTransactionId int NULL 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'DocumentType' 
                      AND OBJECT_ID = OBJECT_ID(N'DATA_InvoiceData'))
BEGIN
  ALTER TABLE DATA_InvoiceData
  ADD DocumentType Smallint NULL 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'DocumentGeneralType' 
                      AND OBJECT_ID = OBJECT_ID(N'DATA_InvoiceData'))
BEGIN
  ALTER TABLE DATA_InvoiceData
  ADD DocumentGeneralType Smallint NULL 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'CreditNoteAccountId' 
                      AND OBJECT_ID = OBJECT_ID(N'DATA_InvoiceData'))
BEGIN
  ALTER TABLE DATA_InvoiceData
  ADD CreditNoteAccountId int NULL 
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>3161</SQLVERSION><RMTRACKLINK>IDBOS-1792</RMTRACKLINK><REASON>Added new field to CNF_Invoice: ConfigurationType</REASON><TABLENAMES>CNF_Invoice=InvoiceId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'ConfigurationType' 
                      AND OBJECT_ID = OBJECT_ID(N'CNF_Invoice'))
BEGIN
  ALTER TABLE CNF_Invoice
  ADD ConfigurationType Smallint NULL 
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>3160</SQLVERSION><RMTRACKLINK>IDBOS-1889</RMTRACKLINK><REASON>Set XMLHistoryLogEnabled to 0 in CNF_System</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'XMLHistoryLogEnabled' 
                      AND OBJECT_ID = OBJECT_ID(N'CNF_System'))
BEGIN
  UPDATE CNF_System
  SET XMLHistoryLogEnabled = 0
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3159</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.29.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3158</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.29.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3157</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.29.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3156</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.29.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3155</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.29.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3154</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3153</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3152</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3151</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3150</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3149</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3148</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3147</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3146</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3145</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3144</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3143</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3142</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3141</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3140</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3139</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3138</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3137</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3136</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3135</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3134</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3133</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3132</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3131</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3130</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3129</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3128</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3127</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3126</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3125</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3124</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3123</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3122</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3121</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3120</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3119</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3118</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3117</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3116</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3115</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3114</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3113</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3112</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3111</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3110</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3109</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3108</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3107</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3106</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3105</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3104</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3103</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3102</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3101</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3100</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3099</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3098</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3097</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3096</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3095</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3094</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3093</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3092</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3091</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3090</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3089</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3088</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3087</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3086</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3085</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3084</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3083</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3082</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3081</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3080</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3079</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3078</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3077</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3076</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3075</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3074</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3073</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3072</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3071</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3070</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3069</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3068</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3067</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3066</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3065</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3064</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.29.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3063</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.29.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3062</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3061</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.29.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3060</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.29.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>3059</SQLVERSION><RMTRACKLINK>IDBOS-1792</RMTRACKLINK><REASON>Extended length of InvoiceURL field to 300 </REASON><TABLENAMES>DATA_InvoiceData=InvoiceDataId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'InvoiceURL' 
                      AND OBJECT_ID = OBJECT_ID(N'DATA_InvoiceData'))
BEGIN
  ALTER TABLE DATA_InvoiceData
  ALTER COLUMN InvoiceURL Nvarchar(300) NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>3058</SQLVERSION><RMTRACKLINK>IDBOS-1792</RMTRACKLINK><REASON>Added Extension and InvoiceURL fields to DATA_InvoiceData</REASON><TABLENAMES>DATA_InvoiceData=InvoiceDataId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'Extension' 
                      AND OBJECT_ID = OBJECT_ID(N'DATA_InvoiceData'))
BEGIN
  ALTER TABLE DATA_InvoiceData
  ADD Extension Nvarchar(30) NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'InvoiceURL' 
                      AND OBJECT_ID = OBJECT_ID(N'DATA_InvoiceData'))
BEGIN
  ALTER TABLE DATA_InvoiceData
  ADD InvoiceURL Nvarchar(50) NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>3057</SQLVERSION><RMTRACKLINK>IDBOS-1754</RMTRACKLINK><REASON>Added field to CNF_DmgCategory: DmgAccountFilter</REASON><TABLENAMES>CNF_DmgCategory=DmgCategoryId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
                      WHERE Name = N'DmgAccountFilter' 
                      AND OBJECT_ID = OBJECT_ID(N'CNF_DmgCategory'))
BEGIN
  ALTER TABLE CNF_DmgCategory
  ADD DmgAccountFilter Smallint NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>lfornaroli</ADDEDBY><SQLVERSION>3056</SQLVERSION><RMTRACKLINK>IDBOS-1305</RMTRACKLINK><REASON>Add index on CNF_SeatCategory for API CPU usages</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS ( SELECT * FROM sys.indexes 
                WHERE name='Idx_CNF_SeatCategory_API_Search' AND object_id = OBJECT_ID('CNF_SeatCategory')
              )
begin
  CREATE NONCLUSTERED INDEX Idx_CNF_SeatCategory_API_Search ON CNF_SeatCategory(AttributeId ASC)
    INCLUDE (  SeatCategoryId, Name, Code)
                                                 
end</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>scoluccia</ADDEDBY><SQLVERSION>3055</SQLVERSION><RMTRACKLINK>IDBOS-1742</RMTRACKLINK><REASON>Adding into CNF_PromotionItemRule fields
[MinAmountThreShold] Money NULL,
[MaxAmountThreShold] Money NULL
</REASON><TABLENAMES>CNF_PromotionItemRule=PromotionItemRuleId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
WHERE Name = N'MinAmountThreShold' AND OBJECT_ID = OBJECT_ID(N'CNF_PromotionItemRule'))
BEGIN
  ALTER TABLE CNF_PromotionItemRule ADD MinAmountThreShold Money NULL
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
WHERE Name = N'MaxAmountThreShold' AND OBJECT_ID = OBJECT_ID(N'CNF_PromotionItemRule'))
BEGIN
  ALTER TABLE CNF_PromotionItemRule ADD MaxAmountThreShold Money NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fdipalma</ADDEDBY><SQLVERSION>3054</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>DATA_Right ALTER COLUMN StrValue NVARCHAR (500) NULL</REASON><TABLENAMES>DATA_Right=DataRightId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT * FROM sys.columns
WHERE Name = N'StrValue' AND OBJECT_ID = OBJECT_ID(N'DATA_Right'))
BEGIN
  ALTER TABLE DATA_Right ALTER COLUMN StrValue NVARCHAR (500) NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>pchen</ADDEDBY><SQLVERSION>3053</SQLVERSION><RMTRACKLINK>85969</RMTRACKLINK><REASON>extend the RecordNo field to 300</REASON><TABLENAMES>DATA_PaymentCard=PaymentId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT * FROM sys.columns
WHERE Name = N'RecordNo' AND OBJECT_ID = OBJECT_ID(N'DATA_PaymentCard'))
BEGIN
  ALTER TABLE DATA_PaymentCard ALTER COLUMN RecordNo NVARCHAR (300) NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>3052</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>Create indexes on DATA_Account</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT object_id
               FROM sys.indexes
               WHERE Name = 'IDX_Data_Account_AccountDetails')
BEGIN
  CREATE NONCLUSTERED INDEX [IDX_Data_Account_AccountDetails]
  ON [DATA_Account] ([DmgCategoryId],[AccountType],[InsDateTime])
  INCLUDE ([AccountId],[AccountAK],[Enabled],[DisplayName],[CompanyName],[Address1],[ZipCode],[City],[State],[Country],[HomePhone],[BusinessPhone],[MobilePhone],[EmailAddress1],[UpdDateTime],[ExternalCode1])
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fesposito</ADDEDBY><SQLVERSION>3051</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>Fixing DBInfo Stored Procedures</REASON><TABLENAMES>CNF_DBInfo=DBInfoId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT *
             FROM   sys.objects
            WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_RR_RevenueData_OnFlexContractPayment]')
	      AND type IN ( N'P'))
BEGIN
  drop procedure otn_sp_RR_RevenueData_OnFlexContractPayment
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>pchen</ADDEDBY><SQLVERSION>3050</SQLVERSION><RMTRACKLINK>85969</RMTRACKLINK><REASON>extend the ProcessData field to 300</REASON><TABLENAMES>DATA_PaymentCard=PaymentId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT * FROM sys.columns
WHERE Name = N'ProcessData' AND OBJECT_ID = OBJECT_ID(N'DATA_PaymentCard'))
BEGIN
  ALTER TABLE DATA_PaymentCard ALTER COLUMN ProcessData NVARCHAR (300) NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dchen</ADDEDBY><SQLVERSION>3049</SQLVERSION><RMTRACKLINK>IDBOS-1574</RMTRACKLINK><REASON>Adding Chart Of Account</REASON><TABLENAMES>CNF_Donation=DonationId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
WHERE Name = N'COAAccountId' AND OBJECT_ID = OBJECT_ID(N'CNF_Donation'))
BEGIN
  ALTER TABLE CNF_Donation ADD COAAccountId int NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>3048</SQLVERSION><RMTRACKLINK>IDBOS-836</RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF TYPE_ID(N'Restriction_Table') IS NULL 
BEGIN
	Create TYPE dbo.Restriction_Table as TABLE(Reservation_Owner int,                                          
											   Ticket_Owner int,
											   MatrixCellID int,
											   Quantity int,
											   PerformanceID int,
											   EventID int,
											   SaleID int,
											   SaleitemID int,
											   CheckforRestrictionOnly int
											  )
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_CheckAccountRestrictions]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_CheckAccountRestrictions</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>CREATE PROCEDURE [otn_sp_CheckAccountRestrictions]  (
                                                      @Restriction_Check         Restriction_Table READONLY
                                                    ) 
AS    
BEGIN

	DECLARE @SalesDate datetime = getdate();
	DECLARE @AccountRestrictionID int
	DECLARE @OldAccountRestrictionID int = 99999
	DECLARE @RestrictionType int
	DECLARE @Reservation_Owner int
	DECLARE @Ticket_Owner int
	DECLARE @OLD_Ticket_Owner int
	DECLARE @OLD_Resevation_Owner int
	DECLARE @MatrixCellID int
	DECLARE @Quantity int
	DECLARE @FullQuantity int
	DECLARE @PerformanceID int
	DECLARE @EventID int
	DECLARE @SaleID int
	DECLARE @SaleitemID int
	DECLARE @CheckforRestrictionOnly int
	DECLARE @ReservationAccountLimit int
	DECLARE @TicketAccountLimit int
	DECLARE @ReservationorTicket int = 0
	DECLARE @CountofMatrixCells int = 0
	DECLARE @Prevent int = 0
	DECLARE @PreventSale int = 0
	DECLARE @RejectReason varchar(500) = ''
	DECLARE @RejectType int = 0
	DECLARE @GL_Prevent int = 0

--Reservation Owner Check
	SET @RestrictionType = 1
	set @CountofMatrixCells = 0
	SET @OLD_Resevation_Owner = 99999

	DECLARE Check_Cursor CURSOR LOCAL FOR
		select DISTINCT  Reservation_Owner,
		                 Ticket_Owner,
						 Res_Table.MatrixCellID,
						 Quantity,
						 SaleID,
						 SaleitemID,
						 CheckforRestrictionOnly,
						 cnf_AccountRestriction.AccountRestrictionID,
						 cnf_AccountRestriction.ReservationAccountLimit,
						 cnf_AccountRestriction.TicketAccountLimit

		  from @Restriction_Check Res_Table
				INNER JOIN cnf_AccountRestriction2MatrixCell WITH(NOLOCK)				ON cnf_AccountRestriction2MatrixCell.MatrixCellID = Res_Table.MatrixCellID
				INNER JOIN cnf_AccountRestriction2Account WITH(NOLOCK)					ON cnf_AccountRestriction2Account.AccountID = Res_Table.Reservation_Owner
					                                                                       and cnf_accountrestriction2Account.AccountRestrictionID = CNF_AccountRestriction2MatrixCell.AccountRestrictionId
				INNER JOIN cnf_AccountRestriction WITH(NOLOCK)							ON cnf_AccountRestriction.AccountRestrictionId = cnf_AccountRestriction2MatrixCell.AccountRestrictionId

	     where cnf_AccountRestriction.Enabled = 1
		   and Convert(date, GetDAte(), 120) between Convert(date, StartDateTime, 120) and Convert(date, EndDateTime, 120)
		   and CNF_AccountRestriction.RestrictionType = @RestrictionType
		   and Res_Table.Reservation_Owner is not null
		   and ReservationAccountLimit is not null
		   and Reservation_Owner &lt;&gt; 0
		 order by cnf_AccountRestriction.AccountRestrictionID

	OPEN Check_Cursor

	FETCH NEXT FROM Check_Cursor INTO
						@Reservation_Owner,
						@Ticket_Owner,
						@MatrixCellID,
						@Quantity,
						@SaleID,
						@SaleitemID,
						@CheckforRestrictionOnly,
	                    @AccountRestrictionID,
						@ReservationAccountLimit,
						@TicketAccountLimit


	WHILE @@FETCH_STATUS = 0
	BEGIN
		IF @OldAccountRestrictionID &lt;&gt; @AccountRestrictionID and @Reservation_Owner &lt;&gt; @OLD_Resevation_Owner
		BEGIN 
			If @ReservationAccountLimit &gt; 0 
				set @ReservationorTicket = 1

			SET @Prevent = 0;

			if @ReservationorTicket = 1 
			BEGIN
				select @FullQuantity = sum(Quantity),  @CountofMatrixCells = Count(*)
					from @Restriction_Check
					where MatrixCellID in (select MatrixcellId 
											from cnf_AccountRestriction2MatrixCell WITH(NOLOCK)									
											where cnf_AccountRestriction2MatrixCell.AccountRestrictionId = @AccountRestrictionID)
					and Reservation_Owner = @Reservation_Owner						 							

				if @FullQuantity &gt; 0
				Begin			  
					if @CountofMatrixCells = 1 						
						Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @ReservationorTicket, @RestrictionType, @Reservation_Owner, @Ticket_Owner, 
															null, null, @SaleID, @SaleitemID, @CheckforRestrictionOnly, @PreventSale OUTPUT, @RejectReason OUTPUT, @RejectType OUTPUT
					else
					begin
						Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @ReservationorTicket, @RestrictionType, @Reservation_Owner, @Ticket_Owner, 
															null, null, @SaleID, @SaleitemID, 1, @PreventSale OUTPUT, @RejectReason OUTPUT, @RejectType OUTPUT
						set @Prevent = @PreventSale
						SET @GL_Prevent = @GL_Prevent + @Prevent

						if @Prevent = 0 and @CheckforRestrictionOnly = 0 
						begin
							INSERT INTO [dbo].[DATA_AccountLimit]
											([AccountRestrictionId]
											,[AccountId]
											,[PerformanceId]
											,[SaleId]
											,[SaleItemId]
											,[SaleDate]
											,[ReservationAccountQuantity]
											,[TicketAccountQuantity])
										VALUES
											(@AccountRestrictionID
											,@Reservation_Owner
											,@PerformanceID
											,@SaleID
											,@SaleItemID
											,@SalesDate
											,@FullQuantity
											,0)						 
						end
					end
				end
				else
				begin
						INSERT INTO [dbo].[DATA_AccountLimit]
											([AccountRestrictionId]
											,[AccountId]
											,[PerformanceId]
											,[SaleId]
											,[SaleItemId]
											,[SaleDate]
											,[ReservationAccountQuantity]
											,[TicketAccountQuantity])
										VALUES
											(@AccountRestrictionID
											,@Reservation_Owner
											,@PerformanceID
											,@SaleID
											,@SaleItemID
											,@SalesDate
											,@Quantity
											,0)		
				end
			END	
		END
		ELSE
		BEGIN
			IF @OldAccountRestrictionID &lt;&gt; @AccountRestrictionID and @Reservation_Owner &lt;&gt; @OLD_Resevation_Owner
			begin
				if @Prevent = 0 and @CheckforRestrictionOnly = 0 
				begin
					INSERT INTO [dbo].[DATA_AccountLimit]
									([AccountRestrictionId]
									,[AccountId]
									,[PerformanceId]
									,[SaleId]
									,[SaleItemId]
									,[SaleDate]
									,[ReservationAccountQuantity]
									,[TicketAccountQuantity])
								VALUES
									(@AccountRestrictionID
									,@Reservation_Owner
									,@PerformanceID
									,@SaleID
									,@SaleItemID
									,@SalesDate
									,@Quantity
									,0)						 
				end
			end
		END

		Set @OldAccountRestrictionID = @AccountRestrictionID
		SET @OLD_Resevation_Owner = @Reservation_Owner

		FETCH NEXT FROM Check_Cursor INTO
						@Reservation_Owner,
						@Ticket_Owner,
						@MatrixCellID,
						@Quantity,
						@SaleID,
						@SaleitemID,
						@CheckforRestrictionOnly,
	                    @AccountRestrictionID,
						@ReservationAccountLimit,
						@TicketAccountLimit
	END

	CLOSE Check_Cursor;
	DEALLOCATE Check_Cursor;




--Ticket Owner Check
	SET @RestrictionType = 1
	Set @OldAccountRestrictionID = 99999
	SET @OLD_Ticket_Owner = 99999
	if @GL_Prevent = 0
	BEGIN
		DECLARE Check_Cursor CURSOR LOCAL FOR
			select DISTINCT  Reservation_Owner,
							 Ticket_Owner,
							 Res_Table.MatrixCellID,
							 Quantity,
							 SaleID,
							 SaleitemID,
							 CheckforRestrictionOnly,
							 cnf_AccountRestriction.AccountRestrictionID,
							 cnf_AccountRestriction.ReservationAccountLimit,
							 cnf_AccountRestriction.TicketAccountLimit

			  from @Restriction_Check Res_Table
					INNER JOIN cnf_AccountRestriction2MatrixCell WITH(NOLOCK)				ON cnf_AccountRestriction2MatrixCell.MatrixCellID = Res_Table.MatrixCellID
					INNER JOIN cnf_AccountRestriction2Account WITH(NOLOCK)					ON cnf_AccountRestriction2Account.AccountID = Res_Table.Ticket_Owner
												                                               and cnf_accountrestriction2Account.AccountRestrictionID = CNF_AccountRestriction2MatrixCell.AccountRestrictionId
					INNER JOIN cnf_AccountRestriction WITH(NOLOCK)							ON cnf_AccountRestriction.AccountRestrictionId = cnf_AccountRestriction2MatrixCell.AccountRestrictionId

			 where cnf_AccountRestriction.Enabled = 1
			   and Convert(date, GetDAte(), 120) between Convert(date, StartDateTime, 120) and Convert(date, EndDateTime, 120)
			   and CNF_AccountRestriction.RestrictionType = @RestrictionType
			   and Res_Table.Ticket_Owner is not null
			   and TicketAccountLimit is not null
			   and Res_Table.Ticket_Owner &lt;&gt; 0

			 order by Ticket_Owner, AccountRestrictionID

		OPEN Check_Cursor

		FETCH NEXT FROM Check_Cursor INTO
							@Reservation_Owner,
							@Ticket_Owner,
							@MatrixCellID,
							@Quantity,
							@SaleID,
							@SaleitemID,
							@CheckforRestrictionOnly,
							@AccountRestrictionID,
							@ReservationAccountLimit,
							@TicketAccountLimit


		WHILE @@FETCH_STATUS = 0
		BEGIN
			IF @OldAccountRestrictionID &lt;&gt; @AccountRestrictionID and @Ticket_Owner &lt;&gt; @OLD_Ticket_Owner
			BEGIN 
				If @TicketAccountLimit &gt; 0 
				  set @ReservationorTicket = 2

				SET @Prevent = 0;

				IF @ReservationorTicket = 2
				BEGIN
					select @FullQuantity = sum(Quantity),  @CountofMatrixCells = Count(*) 
						from @Restriction_Check
						where MatrixCellID in (select MatrixcellId 
												from cnf_AccountRestriction2MatrixCell WITH(NOLOCK)									
												where cnf_AccountRestriction2MatrixCell.AccountRestrictionId = @AccountRestrictionID)	
						  and Ticket_Owner = @Ticket_Owner

					if @FullQuantity &gt; 0
					Begin				
						if @CountofMatrixCells = 1 						 																
							Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @ReservationorTicket, @RestrictionType, @Reservation_Owner, @Ticket_Owner, 
																null, null, @SaleID, @SaleitemID, @CheckforRestrictionOnly, @PreventSale OUTPUT, @RejectReason OUTPUT, @RejectType OUTPUT
						ELSE
						begin
							Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @ReservationorTicket, @RestrictionType, @Reservation_Owner, @Ticket_Owner, 
																null, null, @SaleID, @SaleitemID, 1, @PreventSale OUTPUT, @RejectReason OUTPUT, @RejectType OUTPUT
							set @Prevent = @PreventSale
							SET @GL_Prevent = @GL_Prevent + @Prevent

							if @Prevent = 0 and @CheckforRestrictionOnly = 0 
							begin
								INSERT INTO [dbo].[DATA_AccountLimit]
												([AccountRestrictionId]
												,[AccountId]
												,[PerformanceId]
												,[SaleId]
												,[SaleItemId]
												,[SaleDate]
												,[ReservationAccountQuantity]
												,[TicketAccountQuantity])
											VALUES
												(@AccountRestrictionID
												,@Ticket_Owner
												,@PerformanceID
												,@SaleID
												,@SaleItemID
												,@SalesDate
												,0
												,@FullQuantity)							 
							end
						end
					end
					else
					begin
						INSERT INTO [dbo].[DATA_AccountLimit]
											([AccountRestrictionId]
											,[AccountId]
											,[PerformanceId]
											,[SaleId]
											,[SaleItemId]
											,[SaleDate]
											,[ReservationAccountQuantity]
											,[TicketAccountQuantity])
										VALUES
											(@AccountRestrictionID
											,@Ticket_Owner
											,@PerformanceID
											,@SaleID
											,@SaleItemID
											,@SalesDate
											,0
											,@Quantity)	
					end
				END
			END
			ELSE
			BEGIN
				if @Prevent = 0 and @CheckforRestrictionOnly = 0 
				begin
							INSERT INTO [dbo].[DATA_AccountLimit]
											([AccountRestrictionId]
											,[AccountId]
											,[PerformanceId]
											,[SaleId]
											,[SaleItemId]
											,[SaleDate]
											,[ReservationAccountQuantity]
											,[TicketAccountQuantity])
										VALUES
											(@AccountRestrictionID
											,@Ticket_Owner
											,@PerformanceID
											,@SaleID
											,@SaleItemID
											,@SalesDate
											,0
											,@Quantity)						 
				end
			END

			Set @OldAccountRestrictionID = @AccountRestrictionID
			SET @OLD_Ticket_Owner = @Ticket_Owner

			FETCH NEXT FROM Check_Cursor INTO
							@Reservation_Owner,
							@Ticket_Owner,
							@MatrixCellID,
							@Quantity,
							@SaleID,
							@SaleitemID,
							@CheckforRestrictionOnly,
							@AccountRestrictionID,
							@ReservationAccountLimit,
							@TicketAccountLimit
		END

		CLOSE Check_Cursor;
		DEALLOCATE Check_Cursor;
	END;


--Performance Reservation Owner Check
	SET @RestrictionType = 2
	Set @OldAccountRestrictionID = 99999
	if @GL_Prevent = 0
	BEGIN
		DECLARE Check_Cursor CURSOR LOCAL FOR
			select DISTINCT  Reservation_Owner,
								Ticket_Owner,
								Res_Table.MatrixCellID,
								Quantity,
								SaleID,
								SaleitemID,
								CheckforRestrictionOnly,
								cnf_AccountRestriction.AccountRestrictionID,
								cnf_AccountRestriction.ReservationAccountLimit,
								cnf_AccountRestriction.TicketAccountLimit,
								Res_Table.PerformanceID,
								RES_Table.Eventid

				from @Restriction_Check Res_Table
					INNER JOIN cnf_Performance WITH(NOLOCK)									ON cnf_Performance.PerformanceID = Res_Table.PerformanceId
					INNER JOIN cnf_AccountRestriction2Account WITH(NOLOCK)					ON cnf_AccountRestriction2Account.AccountID = Res_Table.Reservation_Owner
					INNER JOIN cnf_AccountRestriction WITH(NOLOCK)							ON cnf_AccountRestriction.AccountRestrictionId = cnf_AccountRestriction2Account.AccountRestrictionId

				where cnf_AccountRestriction.Enabled = 1
				and Convert(date, GetDAte(), 120) between Convert(date, StartDateTime, 120) and Convert(date, EndDateTime, 120)
				and CNF_AccountRestriction.RestrictionType = @RestrictionType
				and Res_Table.Reservation_Owner is not null
				and ReservationAccountLimit is not null
				and Reservation_Owner &lt;&gt; 0

		OPEN Check_Cursor

		FETCH NEXT FROM Check_Cursor INTO
							@Reservation_Owner,
							@Ticket_Owner,
							@MatrixCellID,
							@Quantity,
							@SaleID,
							@SaleitemID,
							@CheckforRestrictionOnly,
							@AccountRestrictionID,
							@ReservationAccountLimit,
							@TicketAccountLimit,
							@PerformanceID,
							@EventID


		WHILE @@FETCH_STATUS = 0
		BEGIN
			IF @OldAccountRestrictionID &lt;&gt; @AccountRestrictionID
			BEGIN 
				If @ReservationAccountLimit &gt; 0 
					set @ReservationorTicket = 1

				SET @Prevent = 0;

				IF @ReservationorTicket = 1
				BEGIN
					select @FullQuantity = sum(Quantity),  @CountofMatrixCells = Count(*)
						from @Restriction_Check
						where PerformanceID = @PerformanceID 	
							and Reservation_Owner = @Reservation_Owner

					if @FullQuantity &gt; 0
					Begin				
						if @CountofMatrixCells = 1 						 																
							Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @ReservationorTicket, @RestrictionType, @Reservation_Owner, @Ticket_Owner, 
																@PerformanceID, @EventID, @SaleID, @SaleitemID, @CheckforRestrictionOnly, @PreventSale OUTPUT, @RejectReason OUTPUT, @RejectType OUTPUT
						else
						begin
							Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @ReservationorTicket, @RestrictionType, @Reservation_Owner, @Ticket_Owner, 
																@PerformanceID, @EventID, @SaleID, @SaleitemID, 1, @PreventSale OUTPUT, @RejectReason OUTPUT, @RejectType OUTPUT
							set @Prevent = @PreventSale
							SET @GL_Prevent = @GL_Prevent + @Prevent

							if @Prevent = 0 and @CheckforRestrictionOnly = 0 
							begin
								INSERT INTO [dbo].[DATA_AccountLimit]
												([AccountRestrictionId]
												,[AccountId]
												,[PerformanceId]
												,[SaleId]
												,[SaleItemId]
												,[SaleDate]
												,[ReservationAccountQuantity]
												,[TicketAccountQuantity])
											VALUES
												(@AccountRestrictionID
												,@Reservation_Owner
												,@PerformanceID
												,@SaleID
												,@SaleItemID
												,@SalesDate
												,@FullQuantity
												,0)							 
							end
						end
					end
					else
					begin
							INSERT INTO [dbo].[DATA_AccountLimit]
											([AccountRestrictionId]
											,[AccountId]
											,[PerformanceId]
											,[SaleId]
											,[SaleItemId]
											,[SaleDate]
											,[ReservationAccountQuantity]
											,[TicketAccountQuantity])
										VALUES
											(@AccountRestrictionID
											,@Reservation_Owner
											,@PerformanceID
											,@SaleID
											,@SaleItemID
											,@SalesDate
											,@Quantity
											,0)	


					end
				END

			END
			ELSE
			BEGIN
				if @Prevent = 0 and @CheckforRestrictionOnly = 0 
				begin
							INSERT INTO [dbo].[DATA_AccountLimit]
											([AccountRestrictionId]
											,[AccountId]
											,[PerformanceId]
											,[SaleId]
											,[SaleItemId]
											,[SaleDate]
											,[ReservationAccountQuantity]
											,[TicketAccountQuantity])
										VALUES
											(@AccountRestrictionID
											,@Reservation_Owner
											,@PerformanceID
											,@SaleID
											,@SaleItemID
											,@SalesDate
											,@Quantity
											,0)							 
				end
			END

			Set @OldAccountRestrictionID = @AccountRestrictionID
			SET @OLD_Resevation_Owner = @Reservation_Owner

			FETCH NEXT FROM Check_Cursor INTO
							@Reservation_Owner,
							@Ticket_Owner,
							@MatrixCellID,
							@Quantity,
							@SaleID,
							@SaleitemID,
							@CheckforRestrictionOnly,
							@AccountRestrictionID,
							@ReservationAccountLimit,
							@TicketAccountLimit,
							@PerformanceID,
							@EventID
		END

		CLOSE Check_Cursor;
		DEALLOCATE Check_Cursor;
	END



--Performance Ticket Owner Check
	SET @RestrictionType = 2
	Set @OldAccountRestrictionID = 99999
	Set @OLD_Ticket_Owner = 99999
	
	if @GL_Prevent = 0
	BEGIN
		DECLARE Check_Cursor CURSOR LOCAL FOR
			select DISTINCT  Reservation_Owner,
							 Ticket_Owner,
							 Res_Table.MatrixCellID,
							 Quantity,
							 SaleID,
							 SaleitemID,
							 CheckforRestrictionOnly,
							 cnf_AccountRestriction.AccountRestrictionID,
							 cnf_AccountRestriction.ReservationAccountLimit,
							 cnf_AccountRestriction.TicketAccountLimit,
							 Res_Table.PerformanceID,
							 RES_Table.Eventid

			  from @Restriction_Check Res_Table
					INNER JOIN cnf_Performance WITH(NOLOCK)									ON cnf_Performance.PerformanceID = Res_Table.PerformanceId
					INNER JOIN cnf_AccountRestriction2Account WITH(NOLOCK)					ON cnf_AccountRestriction2Account.AccountID = Res_Table.Ticket_Owner
					INNER JOIN cnf_AccountRestriction WITH(NOLOCK)							ON cnf_AccountRestriction.AccountRestrictionId = cnf_AccountRestriction2Account.AccountRestrictionId

			 where cnf_AccountRestriction.Enabled = 1
			   and Convert(date, GetDAte(), 120) between Convert(date, StartDateTime, 120) and Convert(date, EndDateTime, 120)
			   and CNF_AccountRestriction.RestrictionType = @RestrictionType
			   and Res_Table.Ticket_Owner is not null
			   and TicketAccountLimit is not null
			   and Res_Table.Ticket_Owner &lt;&gt; 0

		OPEN Check_Cursor

		FETCH NEXT FROM Check_Cursor INTO
							@Reservation_Owner,
							@Ticket_Owner,
							@MatrixCellID,
							@Quantity,
							@SaleID,
							@SaleitemID,
							@CheckforRestrictionOnly,
							@AccountRestrictionID,
							@ReservationAccountLimit,
							@TicketAccountLimit,
							@PerformanceID,
							@EventID


		WHILE @@FETCH_STATUS = 0
		BEGIN
			IF @OldAccountRestrictionID &lt;&gt; @AccountRestrictionID and @Ticket_Owner &lt;&gt; @OLD_Ticket_Owner
			BEGIN 
				If @TicketAccountLimit &gt; 0 
				  set @ReservationorTicket = 2

				SET @Prevent = 0;

				IF @ReservationorTicket = 2
				BEGIN
					select @FullQuantity = sum(Quantity),  @CountofMatrixCells = Count(*) 
						from @Restriction_Check
						where PerformanceID = @PerformanceID 	
						  and Ticket_Owner = @Ticket_Owner
				
					if @FullQuantity &gt; 0
					Begin
						if @CountofMatrixCells = 1 						 																
							Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @ReservationorTicket, @RestrictionType, @Reservation_Owner, @Ticket_Owner, 
															   @PerformanceID, @EventID, @SaleID, @SaleitemID, @CheckforRestrictionOnly, @PreventSale OUTPUT, @RejectReason OUTPUT, @RejectType OUTPUT
						else
						begin
							Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @ReservationorTicket, @RestrictionType, @Reservation_Owner, @Ticket_Owner, 
																@PerformanceID, @EventID, @SaleID, @SaleitemID, 1, @PreventSale OUTPUT, @RejectReason OUTPUT, @RejectType OUTPUT
							set @Prevent = @PreventSale
							SET @GL_Prevent = @GL_Prevent + @Prevent

							if @Prevent = 0 and @CheckforRestrictionOnly = 0 
							begin
								INSERT INTO [dbo].[DATA_AccountLimit]
												([AccountRestrictionId]
												,[AccountId]
												,[PerformanceId]
												,[SaleId]
												,[SaleItemId]
												,[SaleDate]
												,[ReservationAccountQuantity]
												,[TicketAccountQuantity])
											VALUES
												(@AccountRestrictionID
												,@Ticket_Owner
												,@PerformanceID
												,@SaleID
												,@SaleItemID
												,@SalesDate
												,0
												,@FullQuantity)								 
							end
						end
					end
					begin
							INSERT INTO [dbo].[DATA_AccountLimit]
											([AccountRestrictionId]
											,[AccountId]
											,[PerformanceId]
											,[SaleId]
											,[SaleItemId]
											,[SaleDate]
											,[ReservationAccountQuantity]
											,[TicketAccountQuantity])
										VALUES
											(@AccountRestrictionID
											,@Ticket_Owner
											,@PerformanceID
											,@SaleID
											,@SaleItemID
											,@SalesDate
											,0
											,@Quantity)	
					end
				END
			END
			ELSE
			BEGIN
				if @Prevent = 0 and @CheckforRestrictionOnly = 0 
				begin
							INSERT INTO [dbo].[DATA_AccountLimit]
											([AccountRestrictionId]
											,[AccountId]
											,[PerformanceId]
											,[SaleId]
											,[SaleItemId]
											,[SaleDate]
											,[ReservationAccountQuantity]
											,[TicketAccountQuantity])
										VALUES
											(@AccountRestrictionID
											,@Ticket_Owner
											,@PerformanceID
											,@SaleID
											,@SaleItemID
											,@SalesDate
											,0
											,@Quantity)							 
				end
			END

			Set @OldAccountRestrictionID = @AccountRestrictionID
			Set @OLD_Ticket_Owner = @Ticket_Owner

		FETCH NEXT FROM Check_Cursor INTO
							@Reservation_Owner,
							@Ticket_Owner,
							@MatrixCellID,
							@Quantity,
							@SaleID,
							@SaleitemID,
							@CheckforRestrictionOnly,
							@AccountRestrictionID,
							@ReservationAccountLimit,
							@TicketAccountLimit,
							@PerformanceID,
							@EventID
		END

		CLOSE Check_Cursor;
		DEALLOCATE Check_Cursor;
	END

--Event Reservation Owner Check
	SET @RestrictionType = 2
	Set @OldAccountRestrictionID = 99999
	if @GL_Prevent = 0
	BEGIN
		DECLARE Check_Cursor CURSOR LOCAL FOR
			select DISTINCT  Reservation_Owner,
							 Ticket_Owner,
							 Res_Table.MatrixCellID,
							 Quantity,
							 SaleID,
							 SaleitemID,
							 CheckforRestrictionOnly,
							 cnf_AccountRestriction.AccountRestrictionID,
							 cnf_AccountRestriction.ReservationAccountLimit,
							 cnf_AccountRestriction.TicketAccountLimit,
							 Res_Table.PerformanceID,
							 RES_Table.Eventid

			  from @Restriction_Check Res_Table
					INNER JOIN cnf_Event WITH(NOLOCK)										ON cnf_Event.EventID = Res_Table.EventID
					INNER JOIN cnf_AccountRestriction2Account WITH(NOLOCK)					ON cnf_AccountRestriction2Account.AccountID = Res_Table.Reservation_Owner
					INNER JOIN cnf_AccountRestriction WITH(NOLOCK)							ON cnf_AccountRestriction.AccountRestrictionId = cnf_AccountRestriction2Account.AccountRestrictionId

			 where cnf_AccountRestriction.Enabled = 1
			   and Convert(date, GetDAte(), 120) between Convert(date, StartDateTime, 120) and Convert(date, EndDateTime, 120)
			   and CNF_AccountRestriction.RestrictionType = @RestrictionType
			   and Res_Table.Reservation_Owner is not null
			   and ReservationAccountLimit is not null
			   and Res_Table.Reservation_Owner &lt;&gt; 0

		OPEN Check_Cursor

		FETCH NEXT FROM Check_Cursor INTO
							@Reservation_Owner,
							@Ticket_Owner,
							@MatrixCellID,
							@Quantity,
							@SaleID,
							@SaleitemID,
							@CheckforRestrictionOnly,
							@AccountRestrictionID,
							@ReservationAccountLimit,
							@TicketAccountLimit,
							@PerformanceID,
							@EventID


		WHILE @@FETCH_STATUS = 0
		BEGIN
			IF @OldAccountRestrictionID &lt;&gt; @AccountRestrictionID 
			BEGIN 
				If @ReservationAccountLimit &gt; 0 
				  set @ReservationorTicket = 1

				SET @Prevent = 0;

				IF @ReservationorTicket = 1
				BEGIN
					select @FullQuantity = sum(Quantity),  @CountofMatrixCells = Count(*) 
						from @Restriction_Check
						where EventID = @EventID 	
						  and Reservation_Owner = @Reservation_Owner
				
					if @FullQuantity &gt; 0
					Begin
						if @CountofMatrixCells = 1 						 																
							Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @ReservationorTicket, @RestrictionType, @Reservation_Owner, @Ticket_Owner, 
															   @PerformanceID, @EventID, @SaleID, @SaleitemID, @CheckforRestrictionOnly, @PreventSale OUTPUT, @RejectReason OUTPUT, @RejectType OUTPUT
						else
						begin
							Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @ReservationorTicket, @RestrictionType, @Reservation_Owner, @Ticket_Owner, 
																@PerformanceID, @EventID, @SaleID, @SaleitemID, 1, @PreventSale OUTPUT, @RejectReason OUTPUT, @RejectType OUTPUT
							set @Prevent = @PreventSale
							SET @GL_Prevent = @GL_Prevent + @Prevent

							if @Prevent = 0 and @CheckforRestrictionOnly = 0 
							begin
								INSERT INTO [dbo].[DATA_AccountLimit]
												([AccountRestrictionId]
												,[AccountId]
												,[PerformanceId]
												,[SaleId]
												,[SaleItemId]
												,[SaleDate]
												,[ReservationAccountQuantity]
												,[TicketAccountQuantity])
											VALUES
												(@AccountRestrictionID
												,@Reservation_Owner
												,@PerformanceID
												,@SaleID
												,@SaleItemID
												,@SalesDate
												,@FullQuantity
												,0)							 
							end
						end
					end
					begin
							INSERT INTO [dbo].[DATA_AccountLimit]
											([AccountRestrictionId]
											,[AccountId]
											,[PerformanceId]
											,[SaleId]
											,[SaleItemId]
											,[SaleDate]
											,[ReservationAccountQuantity]
											,[TicketAccountQuantity])
										VALUES
											(@AccountRestrictionID
											,@Reservation_Owner
											,@PerformanceID
											,@SaleID
											,@SaleItemID
											,@SalesDate
											,@Quantity
											,0)	
					end
				END
			END
			ELSE
			BEGIN
				if @Prevent = 0 and @CheckforRestrictionOnly = 0 
				begin
							INSERT INTO [dbo].[DATA_AccountLimit]
											([AccountRestrictionId]
											,[AccountId]
											,[PerformanceId]
											,[SaleId]
											,[SaleItemId]
											,[SaleDate]
											,[ReservationAccountQuantity]
											,[TicketAccountQuantity])
										VALUES
											(@AccountRestrictionID
											,@Reservation_Owner
											,@PerformanceID
											,@SaleID
											,@SaleItemID
											,@SalesDate
											,@Quantity
											,0)							 
				end
			END

			Set @OldAccountRestrictionID = @AccountRestrictionID
			SET @OLD_Resevation_Owner = @Reservation_Owner

		FETCH NEXT FROM Check_Cursor INTO
							@Reservation_Owner,
							@Ticket_Owner,
							@MatrixCellID,
							@Quantity,
							@SaleID,
							@SaleitemID,
							@CheckforRestrictionOnly,
							@AccountRestrictionID,
							@ReservationAccountLimit,
							@TicketAccountLimit,
							@PerformanceID,
							@EventID
		END

		CLOSE Check_Cursor;
		DEALLOCATE Check_Cursor;
	END


--Event Ticket Owner Check
	SET @RestrictionType = 2
	Set @OldAccountRestrictionID = 99999
	Set @OLD_Ticket_Owner = 99999
	if @GL_Prevent = 0
	BEGIN
		DECLARE Check_Cursor CURSOR LOCAL FOR
			select DISTINCT  Reservation_Owner,
							 Ticket_Owner,
							 Res_Table.MatrixCellID,
							 Quantity,
							 SaleID,
							 SaleitemID,
							 CheckforRestrictionOnly,
							 cnf_AccountRestriction.AccountRestrictionID,
							 cnf_AccountRestriction.ReservationAccountLimit,
							 cnf_AccountRestriction.TicketAccountLimit,
							 Res_Table.PerformanceID,
							 RES_Table.Eventid

			  from @Restriction_Check Res_Table
					INNER JOIN cnf_Event WITH(NOLOCK)										ON cnf_Event.EventID = Res_Table.EventID
					INNER JOIN cnf_AccountRestriction2Account WITH(NOLOCK)					ON cnf_AccountRestriction2Account.AccountID = Res_Table.Ticket_Owner
					INNER JOIN cnf_AccountRestriction WITH(NOLOCK)							ON cnf_AccountRestriction.AccountRestrictionId = cnf_AccountRestriction2Account.AccountRestrictionId

			 where cnf_AccountRestriction.Enabled = 1
			   and Convert(date, GetDAte(), 120) between Convert(date, StartDateTime, 120) and Convert(date, EndDateTime, 120)
			   and CNF_AccountRestriction.RestrictionType = @RestrictionType
			   and Res_Table.Ticket_Owner is not null
			   and TicketAccountLimit is not null
			   and Res_Table.Ticket_Owner &lt;&gt; 0

		OPEN Check_Cursor

		FETCH NEXT FROM Check_Cursor INTO
							@Reservation_Owner,
							@Ticket_Owner,
							@MatrixCellID,
							@Quantity,
							@SaleID,
							@SaleitemID,
							@CheckforRestrictionOnly,
							@AccountRestrictionID,
							@ReservationAccountLimit,
							@TicketAccountLimit,
							@PerformanceID,
							@EventID


		WHILE @@FETCH_STATUS = 0
		BEGIN
			IF @OldAccountRestrictionID &lt;&gt; @AccountRestrictionID and @Ticket_Owner &lt;&gt; @OLD_Ticket_Owner
			BEGIN 
				If @TicketAccountLimit &gt; 0 
				  set @ReservationorTicket = 2

				SET @Prevent = 0;

				IF @ReservationorTicket = 2
				BEGIN
					select @FullQuantity = sum(Quantity),  @CountofMatrixCells = Count(*) 
						from @Restriction_Check
						where EventID = @EventID  	
						  and Ticket_Owner = @Ticket_Owner
				
					if @FullQuantity &gt; 0
					Begin
						if @CountofMatrixCells = 1 						 																
							Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @ReservationorTicket, @RestrictionType, @Reservation_Owner, @Ticket_Owner, 
															   @PerformanceID, @EventID, @SaleID, @SaleitemID, @CheckforRestrictionOnly, @PreventSale OUTPUT, @RejectReason OUTPUT, @RejectType OUTPUT
						else
						begin
							Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @ReservationorTicket, @RestrictionType, @Reservation_Owner, @Ticket_Owner, 
																@PerformanceID, @EventID, @SaleID, @SaleitemID, 1, @PreventSale OUTPUT, @RejectReason OUTPUT, @RejectType OUTPUT
							set @Prevent = @PreventSale
							SET @GL_Prevent = @GL_Prevent + @Prevent

							if @Prevent = 0 and @CheckforRestrictionOnly = 0 
							begin
								INSERT INTO [dbo].[DATA_AccountLimit]
												([AccountRestrictionId]
												,[AccountId]
												,[PerformanceId]
												,[SaleId]
												,[SaleItemId]
												,[SaleDate]
												,[ReservationAccountQuantity]
												,[TicketAccountQuantity])
											VALUES
												(@AccountRestrictionID
												,@Ticket_Owner
												,@PerformanceID
												,@SaleID
												,@SaleItemID
												,@SalesDate
												,0
												,@FullQuantity)							 
							end
						end
					end
					else
					begin
							INSERT INTO [dbo].[DATA_AccountLimit]
											([AccountRestrictionId]
											,[AccountId]
											,[PerformanceId]
											,[SaleId]
											,[SaleItemId]
											,[SaleDate]
											,[ReservationAccountQuantity]
											,[TicketAccountQuantity])
										VALUES
											(@AccountRestrictionID
											,@Ticket_Owner
											,@PerformanceID
											,@SaleID
											,@SaleItemID
											,@SalesDate
											,0
											,@Quantity)	
					end
				END

			END
			ELSE
			BEGIN
				if @Prevent = 0 and @CheckforRestrictionOnly = 0 
				begin
							INSERT INTO [dbo].[DATA_AccountLimit]
											([AccountRestrictionId]
											,[AccountId]
											,[PerformanceId]
											,[SaleId]
											,[SaleItemId]
											,[SaleDate]
											,[ReservationAccountQuantity]
											,[TicketAccountQuantity])
										VALUES
											(@AccountRestrictionID
											,@Ticket_Owner
											,@PerformanceID
											,@SaleID
											,@SaleItemID
											,@SalesDate
											,0
											,@Quantity)							 
				end
			END

			Set @OldAccountRestrictionID = @AccountRestrictionID
			Set @OLD_Ticket_Owner = @Ticket_Owner

		FETCH NEXT FROM Check_Cursor INTO
							@Reservation_Owner,
							@Ticket_Owner,
							@MatrixCellID,
							@Quantity,
							@SaleID,
							@SaleitemID,
							@CheckforRestrictionOnly,
							@AccountRestrictionID,
							@ReservationAccountLimit,
							@TicketAccountLimit,
							@PerformanceID,
							@EventID
		END

		CLOSE Check_Cursor;
		DEALLOCATE Check_Cursor;
	END


	select @PreventSale as PreventSale, @RejectReason as RejectReason, @RejectType as RejectType

END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.objects WHERE [name] = N'data_sale_SalesRestriction' AND [type] = 'TR')
BEGIN
      DROP TRIGGER [dbo].[data_sale_SalesRestriction];
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>Create trigger [dbo].[data_sale_SalesRestriction] on [dbo].[DATA_Sale] FOR update
	 as
begin
	SET NOCOUNT ON;
    IF UPDATE(Approved) or Update(StatusCode)
    BEGIN

		Declare @Temp Restriction_Table

		DECLARE @INS_SaleID int
		DECLARE @status int = 0 
		DECLARE @DR_status int

		DECLARE	@ReservationAccountID int
		DECLARE	@B2BAccountID int  
		DECLARE	@TicketAccountID int
		DECLARE	@SaleID int
		DECLARE	@SaleItemID int
		DECLARE @UsageCheck int
		DECLARE	@PerformanceID int
		DECLARE	@Quantity int
		DECLARE @MatrixCellID int
		DECLARE @EventID int

		DECLARE @RestrictionType int	
			
		DECLARE @ReservationAccountOwner int = 1
		DECLARE @TicketAccountOwner int = 2
		DECLARE @CheckforRestraintOnly int = 0

		SELECT @status=i.Approved, @INS_SaleID = i.Saleid 
				FROM inserted i
				JOIN deleted d
					ON i.SaleID = d.SaleID
					AND i.Approved &lt;&gt; d.Approved

		if @status = 0 
		begin
			SELECT @DR_status = CASE WHEN i.StatusCode = 2 then  1
			            else 0
					end, 
			       @INS_SaleID = i.Saleid 
					FROM inserted i
					JOIN deleted d
						ON i.[SaleID] = d.[SaleID]
						AND i.[StatusCode] &lt;&gt; d.[StatusCode]
		end


		if @status = 1
		begin
			Insert into @Temp
			select  ISNULL(data_reservation.accountid, ODR.AccountID) as ReservationAccountID,
					data_ticket.accountid TicketAccountID,
					data_saleitem.Matrixcellid,
					case when data_ticket.ticketid is not null then case when data_saleitem.Quantity &lt; 0 then -1 else 1 end
									else data_saleitem.Quantity
								end Quantity,
					cnf_performance.PerformanceID,
					cnf_performance.Eventid,
					data_sale.saleid,
					data_saleitem.saleitemid,
					case when data_saleitem.Quantity &lt; 0 then ISNULL((select top 1 1
																		from data_transaction
																		where data_transaction.transactiontype in (17, 18, 20, 40, 47)
																			and data_transaction.saleid = data_sale.saleid), 0)
							else 0
						end as UsageCheck

			from data_sale WITH(NOLOCK)
				LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
				INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
				LEFT  JOIN data_saleitem2ticket WITH(NOLOCK)				on data_saleitem2ticket.saleitemid = data_saleitem.saleitemid
				LEFT  JOIN data_saleitem2Performance WITH(NOLOCK)			on data_saleitem2performance.saleitemid = data_saleitem.saleitemid
				LEFT  JOIN cnf_performance WITH(NOLOCK)						on cnf_Performance.performanceid = data_saleitem2performance.performanceid
				LEFT  JOIN data_ticket WITH(NOLOCK)							on data_ticket.ticketid = data_saleitem2ticket.ticketid
				left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
				left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

				where data_sale.saleid = @INS_SaleID
		END

		if @DR_status = 1
		begin
			Insert into @Temp
			select  ISNULL(data_reservation.accountid, ODR.AccountID) as ReservationAccountID,
					data_ticket.accountid TicketAccountID,
					data_saleitem.Matrixcellid,
					case when data_ticket.ticketid is not null then case when data_saleitem.Quantity &lt; 0 then -1 else 1 end
									else data_saleitem.Quantity
								end Quantity,
					cnf_performance.PerformanceID,
					cnf_performance.Eventid,
					data_sale.saleid,
					data_saleitem.saleitemid,
					case when data_saleitem.Quantity &lt; 0 then ISNULL((select top 1 1
																		from data_transaction
																		where data_transaction.transactiontype in (17, 18, 20, 40, 47)
																			and data_transaction.saleid = data_sale.saleid), 0)
							else 0
						end as UsageCheck

			from data_sale WITH(NOLOCK)
				LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
				INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
				LEFT  JOIN data_saleitem2ticket WITH(NOLOCK)				on data_saleitem2ticket.saleitemid = data_saleitem.saleitemid
				LEFT  JOIN data_saleitem2Performance WITH(NOLOCK)			on data_saleitem2performance.saleitemid = data_saleitem.saleitemid
				LEFT  JOIN cnf_performance WITH(NOLOCK)						on cnf_Performance.performanceid = data_saleitem2performance.performanceid
				LEFT  JOIN data_ticket WITH(NOLOCK)							on data_ticket.ticketid = data_saleitem2ticket.ticketid
				left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
				left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

				where data_sale.saleid = @INS_SaleID
				and data_saleitem.quantity &lt; 0
		end

		Exec otn_sp_CheckAccountRestrictions @Temp
	end
end
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>ALTER TABLE [dbo].[DATA_Sale] ENABLE TRIGGER [data_sale_SalesRestriction]</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>pchen</ADDEDBY><SQLVERSION>3047</SQLVERSION><RMTRACKLINK>85969</RMTRACKLINK><REASON>extend the ProcessData field to 150</REASON><TABLENAMES>DATA_PaymentCard=PaymentId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT * FROM sys.columns
WHERE Name = N'ProcessData' AND OBJECT_ID = OBJECT_ID(N'DATA_PaymentCard'))
BEGIN
  ALTER TABLE DATA_PaymentCard ALTER COLUMN ProcessData NVARCHAR (150) NULL
END
</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fdipalma</ADDEDBY><SQLVERSION>3046</SQLVERSION><RMTRACKLINK>IDBOS-1536</RMTRACKLINK><REASON>Adding into Data_Ticket2Performance fields
[EnvelopeCapacityId] [int] NULL,
[Active] [smallint] NOT NULL,</REASON><TABLENAMES>DATA_Ticket2Performance=Ticket2PerformanceId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
WHERE Name = N'EnvelopeCapacityId' AND OBJECT_ID = OBJECT_ID(N'DATA_Ticket2Performance'))
BEGIN
  ALTER TABLE DATA_Ticket2Performance ADD EnvelopeCapacityId int NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
WHERE Name = N'Active' AND OBJECT_ID = OBJECT_ID(N'DATA_Ticket2Performance'))
BEGIN
  ALTER TABLE DATA_Ticket2Performance ADD Active int Default 1 NOT NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>ALTER TABLE DATA_Ticket2Performance  WITH CHECK ADD FOREIGN KEY([EnvelopeCapacityId])
REFERENCES CNF_EnvelopeCapacity ([EnvelopeCapacityId])</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>pchen</ADDEDBY><SQLVERSION>3045</SQLVERSION><RMTRACKLINK>85969</RMTRACKLINK><REASON>extend the RetrivialReference field from 15 to 30</REASON><TABLENAMES>DATA_PaymentCard=PaymentId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT * FROM sys.columns
WHERE Name = N'RetrivialReference' AND OBJECT_ID = OBJECT_ID(N'DATA_PaymentCard'))
BEGIN
  ALTER TABLE DATA_PaymentCard ALTER COLUMN RetrivialReference NVARCHAR (30) NULL
END
</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>3044</SQLVERSION><RMTRACKLINK>1621</RMTRACKLINK><REASON>Create System Default Report Categories</REASON><TABLENAMES>CNF_DmgCategory=DmgCategoryId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
WHERE Name = N'SystemCategory' AND OBJECT_ID = OBJECT_ID(N'CNF_DmgCategory'))
BEGIN
  alter table CNF_DmgCategory add SystemCategory smallint null
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>Update cnf_dmgcategory
  SET SystemCategory = case when dmgCategoryCode = 'DUMMY' and dmgParentID is null 
                       then 1
                       else 0
                       end
Where SystemCategory = NULL </SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>3043</SQLVERSION><RMTRACKLINK>1629</RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>delete
from cnf_dbinfo
where paramname like 'SQL_%'
  and ParamValue &gt;= '29000'</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dchen</ADDEDBY><SQLVERSION>3042</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
WHERE Name = N'DonationType' AND OBJECT_ID = OBJECT_ID(N'CNF_Donation'))
BEGIN
  alter table CNF_Donation add DonationType integer not null
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>3041</SQLVERSION><RMTRACKLINK>1592</RMTRACKLINK><REASON></REASON><TABLENAMES>DATA_DBUpdateLog=DBUpdateLogId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT * FROM sys.columns
WHERE Name = N'ClientVersion' AND OBJECT_ID = OBJECT_ID(N'DATA_DBUpdateLog'))
BEGIN
  alter table DATA_DBUpdateLog alter column ClientVersion nvarchar(50)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT * FROM sys.columns
WHERE Name = N'ClientName' AND OBJECT_ID = OBJECT_ID(N'DATA_DBUpdateLog'))
BEGIN
  alter table DATA_DBUpdateLog alter column ClientName nvarchar(50)
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3040</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES>CNF_MatrixSheet=MatrixSheetId
CNF_Event=EventId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
WHERE Name = N'IntegrationType' AND OBJECT_ID = OBJECT_ID(N'CNF_MatrixSheet'))
BEGIN
  ALTER TABLE CNF_MatrixSheet ADD IntegrationType smallint NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
WHERE Name = N'IntegrationType' AND OBJECT_ID = OBJECT_ID(N'CNF_Event'))
BEGIN
  ALTER TABLE CNF_Event ADD IntegrationType smallint NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                WHERE TABLE_SCHEMA = 'dbo' 
                  AND TABLE_NAME = 'CNF_AccessToken')
BEGIN
CREATE TABLE CNF_AccessToken(
	[AccessToken] varchar(200) NULL,
	[Expiration] datetime NULL,
	[IntegrationType] smallint NULL
        ) 
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dchen</ADDEDBY><SQLVERSION>3039</SQLVERSION><RMTRACKLINK>IDBOS-1574</RMTRACKLINK><REASON>IDBOS-1574 Need Donation Round-up Functionality

*  CNF_Donation
* CNF_DonationPermission
* CND_MatrixCell2Donation</REASON><TABLENAMES>CNF_Donation=DonationId
CNF_Donation_Permission=DonationPermissionId
CNF_MatrixCell2Donation=MatrixCell2DonationId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                WHERE TABLE_SCHEMA = 'dbo' 
                  AND TABLE_NAME = 'CNF_Donation')
BEGIN
CREATE TABLE CNF_Donation(
	[DonationId] integer IDENTITY(1,1) NOT NULL,
	[DonationAK] varchar(32) NOT NULL,
	[DonationType] integer NOT NULL,
	[Code] nvarchar(10) NULL,
	[Name] nvarchar(50) NOT NULL,
	[Description] nvarchar(50) NULL,
	[SortOrder] smallint NULL,
	[DmgCategoryId] integer NULL,
	[Enabled] integer NOT NULL,
	[MatrixCellId_RoundUp] integer ,
	[MatrixCellId_Variable] integer ,
	[MatrixCellId_PercentageVariable] integer ,
	[Last_UserId_Log] integer NULL,
	[Last_WorkstationId_Log] integer NULL,
	[Last_DateTime_Log] datetime NULL,
Primary Key ([DonationId])
) 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                WHERE TABLE_SCHEMA = 'dbo' 
                  AND TABLE_NAME = 'CNF_Donation_Permission')
BEGIN
CREATE TABLE CNF_Donation_Permission(
	[DonationPermissionId] integer IDENTITY(1,1) NOT NULL,
	[DonationId] integer NOT NULL,
	[UserGroupId] integer NULL,
	[UserId] integer NULL,
	[SiteId] integer NULL,
	[OperatingAreaId] integer NULL,
	[WorkstationId] integer NULL,
	[Allow] smallint NOT NULL,
	[Last_UserId_Log] integer NULL,
	[Last_WorkstationId_Log] integer NULL,
	[Last_DateTime_Log] datetime NULL,
Primary Key ([DonationPermissionId])
) 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                WHERE TABLE_SCHEMA = 'dbo' 
                  AND TABLE_NAME = 'CNF_MatrixCell2Donation')
BEGIN
CREATE TABLE [CNF_MatrixCell2Donation]
(
	[MatrixCell2DonationId] integer IDENTITY(1,1) NOT NULL,
	[MatrixCellId] integer NOT NULL,
	[DonationId] integer NOT NULL,
	[Last_UserId_Log] integer NULL,
	[Last_WorkstationId_Log] integer NULL,
	[Last_DateTime_Log] datetime NULL,
Primary Key ([MatrixCell2DonationId])
) 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_CNF_Donation_DmgCategoryId')
BEGIN
  ALTER TABLE CNF_Donation 
  ADD CONSTRAINT [FK_CNF_Donation_DmgCategoryId] FOREIGN KEY([DmgCategoryId])
  REFERENCES CNF_DmgCategory ([DmgCategoryId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_CNF_Donation_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_Donation 
  ADD CONSTRAINT [FK_CNF_Donation_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log])
  REFERENCES CNF_User ([UserId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_CNF_Donation_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_Donation  
  ADD CONSTRAINT [FK_CNF_Donation_Last_WorkstationId_Log] FOREIGN KEY(Last_WorkstationId_Log)
  REFERENCES CNF_Workstation ([WorkstationId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_CNF_MatrixCell2Donation_DonationId')
BEGIN
  ALTER TABLE CNF_MatrixCell2Donation
  ADD CONSTRAINT [FK_CNF_MatrixCell2Donation_DonationId] FOREIGN KEY(DonationId)
  REFERENCES CNF_Donation ([DonationId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_CNF_MatrixCell2Donation_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_MatrixCell2Donation
  ADD CONSTRAINT [FK_CNF_MatrixCell2Donation_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log])
  REFERENCES CNF_User ([UserId])
END

</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_CNF_MatrixCell2Donation_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_MatrixCell2Donation
  ADD CONSTRAINT [FK_CNF_MatrixCell2Donation_Last_WorkstationId_Log] FOREIGN KEY(Last_WorkstationId_Log)
  REFERENCES CNF_Workstation ([WorkstationId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_Donation_Permission_DonationId')
BEGIN
	ALTER TABLE [CNF_Donation_Permission]  
	ADD CONSTRAINT [FK_Donation_Permission_DonationId] FOREIGN KEY([DonationId])
	REFERENCES [CNF_Donation] ([DonationId])
END

</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_Donation_Permission_OperatingAreaId')
BEGIN
	ALTER TABLE [CNF_Donation_Permission]  
	ADD CONSTRAINT [FK_Donation_Permission_OperatingAreaId] FOREIGN KEY([OperatingAreaId])
	REFERENCES [CNF_OperatingArea] ([OperatingAreaId])
END

</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_Donation_Permission_SiteId')
BEGIN
	ALTER TABLE [CNF_Donation_Permission]  
	ADD CONSTRAINT [FK_Donation_Permission_SiteId] FOREIGN KEY([SiteId])
	REFERENCES [CNF_Site] ([SiteId])
END

</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_Donation_Permission_UserGroupId')
BEGIN
	ALTER TABLE [CNF_Donation_Permission]  
	ADD CONSTRAINT [FK_Donation_Permission_UserGroupId] FOREIGN KEY([UserGroupId])
	REFERENCES [CNF_UserGroup] ([UserGroupId])
END

</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_Donation_Permission_UserId')
BEGIN
	ALTER TABLE [CNF_Donation_Permission]  
	ADD CONSTRAINT [FK_Donation_Permission_UserId] FOREIGN KEY([UserId])
	REFERENCES [CNF_User] ([UserId])
END

</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_Donation_Permission_WorkstationId')
BEGIN
	ALTER TABLE [CNF_Donation_Permission]  
	ADD CONSTRAINT [FK_Donation_Permission_WorkstationId] FOREIGN KEY([WorkstationId])
	REFERENCES [CNF_Workstation] ([WorkstationId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_CNF_Donation_Permission_Last_UserId_Log')
BEGIN
	ALTER TABLE [CNF_Donation_Permission]  
	ADD CONSTRAINT [FK_CNF_Donation_Permission_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log])
	REFERENCES [CNF_User] ([UserId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_CNF_MatrixCell2Donation_Last_WorkstationId_Log')
BEGIN
	ALTER TABLE [CNF_Donation_Permission]  
	ADD CONSTRAINT [FK_CNF_Donation_Permission_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log])
	REFERENCES [CNF_Workstation] ([WorkstationId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_CNF_MatrixCell2Donation_MatrixCellId')
BEGIN
  ALTER TABLE CNF_MatrixCell2Donation
  ADD CONSTRAINT [FK_CNF_MatrixCell2Donation_MatrixCellId] FOREIGN KEY(MatrixCellId)
  REFERENCES CNF_MatrixCell ([MatrixCellId])
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>3038</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>Previous 3038 patch reverted</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fdipalma</ADDEDBY><SQLVERSION>3037</SQLVERSION><RMTRACKLINK>IDBOS-1100</RMTRACKLINK><REASON>Added field UsedPeopleCount in the DATA_Ticket</REASON><TABLENAMES>DATA_Ticket=TicketId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
WHERE Name = N'UsedPeopleCount' AND OBJECT_ID = OBJECT_ID(N'DATA_Ticket'))
BEGIN
  ALTER TABLE DATA_Ticket ADD UsedPeopleCount int Default 0 NOT NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>lfornaroli</ADDEDBY><SQLVERSION>3036</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>[0] Create Table CNF_DeliveryOption2MaskTableItem
[1] Create Table CNF_DeliveryOption
[2] Add FK on CNF_MaskTableItem
[3] add FK on CNF_DeliveryOption
[4] Add field DeliveryOptionID
[5] Add FK on CNF_DeliveryOptionId</REASON><TABLENAMES>CNF_Delivery=DeliveryId
CNF_DeliveryAdditionalFilter=DeliveryAdditionalFilterId
CNF_DeliveryAdditionalFilter2MaskTableItem=DeliveryAdditionalFilter2MaskTableItemId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                WHERE TABLE_SCHEMA = 'dbo' 
                  AND TABLE_NAME = 'CNF_DeliveryAdditionalFilter2MaskTableItem')
BEGIN
Create table [CNF_DeliveryAdditionalFilter2MaskTableItem]
(
	[DeliveryAdditionalFilter2MaskTableItemId] Integer Identity(1,1) NOT NULL,
	[DeliveryAdditionalFilterId] Integer NOT NULL,
	[MaskTableItemId] Integer NOT NULL,
Primary Key ([DeliveryAdditionalFilter2MaskTableItemId])
) 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                WHERE TABLE_SCHEMA = 'dbo' 
                  AND TABLE_NAME = 'CNF_DeliveryAdditionalFilter')
BEGIN
Create table [CNF_DeliveryAdditionalFilter]
(
	[DeliveryAdditionalFilterId] Integer Identity(1,1) NOT NULL,
	[Name] nvarchar(250) NOT NULL,
        [Code] nvarchar(200) NOT NULL,
        [Description] nvarchar(250) NOT NULL,
  	[ObjType] smallint NOT NULL,
        [MaskTableId] integer,
        [MaskValue] nvarchar(500)
Primary Key ([DeliveryAdditionalFilterId])
) 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DeliveryAdditionalFilter2MaskTableItem_MasktableItemId')
BEGIN
  ALTER TABLE CNF_DeliveryAdditionalFilter2MaskTableItem
  ADD CONSTRAINT [FK_CNF_DeliveryAdditionalFilter2MaskTableItem_MasktableItemId] FOREIGN KEY([MaskTableItemId]) 
  REFERENCES [CNF_MaskTableItem] ([MaskTableItemId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DeliveryAdditionalFilter2MaskTableItem_DeliveryAdditionalFilterId')
BEGIN
  ALTER TABLE CNF_DeliveryAdditionalFilter2MaskTableItem
  ADD CONSTRAINT [FK_CNF_DeliveryAdditionalFilter2MaskTableItem_DeliveryAdditionalFilterId] FOREIGN KEY([DeliveryAdditionalFilterId]) 
  REFERENCES [CNF_DeliveryAdditionalFilter] ([DeliveryAdditionalFilterId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
           WHERE Name = N'DeliveryAdditionalFilterId' AND
           Object_ID  = Object_ID(N'CNF_Delivery'))
BEGIN
  ALTER TABLE CNF_Delivery 
  ADD DeliveryAdditionalFilterId integer NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Delivery_DeliveryAdditionalFilterId')
BEGIN
  ALTER TABLE CNF_Delivery
  ADD CONSTRAINT [FK_CNF_Delivery_DeliveryAdditionalFilterId] FOREIGN KEY([DeliveryAdditionalFilterId]) 
  REFERENCES [CNF_DeliveryAdditionalFilter] ([DeliveryAdditionalFilterId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DeliveryAdditionalFIlter_MaskTableId')
BEGIN
  ALTER TABLE CNF_DeliveryAdditionalFilter
  ADD CONSTRAINT [FK_CNF_DeliveryAdditionalFIlter_MaskTableId] FOREIGN KEY([MaskTableId]) 
  REFERENCES [CNF_MaskTable] ([MaskTableId])
END




</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>3035</SQLVERSION><RMTRACKLINK>86165</RMTRACKLINK><REASON>Dropped PriorValidityXML field from DATA_TicketHistory
Added 2 fields to DATA_TicketStatus: 
1)PriorActveToDate
2)PriorValidityXML</REASON><TABLENAMES>DATA_TicketHistory=TicketHistoryId
DATA_TicketStatus=TicketStatusID</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'PriorValidityXML' AND
                Object_ID  = Object_ID(N'DATA_TicketHistory'))
BEGIN
  Alter Table DATA_TicketHistory
  DROP COLUMN PriorValidityXML 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
           WHERE Name = N'PriorActiveToDate' AND
           Object_ID  = Object_ID(N'DATA_TicketStatus'))
BEGIN
  ALTER TABLE DATA_TicketStatus 
  ADD PriorActiveToDate Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
           WHERE Name = N'PriorValidityXML' AND
           Object_ID  = Object_ID(N'DATA_TicketStatus'))
BEGIN
  ALTER TABLE DATA_TicketStatus 
  ADD PriorValidityXML Varchar(max) NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>3034</SQLVERSION><RMTRACKLINK>86165</RMTRACKLINK><REASON>Added new field to Data_TicketHistory: PriorValidityXML</REASON><TABLENAMES>DATA_TicketHistory=TicketHistoryId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
           WHERE Name = N'PriorValidityXML' AND
           Object_ID  = Object_ID(N'DATA_TicketHistory'))
BEGIN
  ALTER TABLE DATA_TicketHistory 
  ADD PriorValidityXML Varchar(max) NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>pchen</ADDEDBY><SQLVERSION>3033</SQLVERSION><RMTRACKLINK>86607</RMTRACKLINK><REASON>Adding SortOrder to CNF_PriceList</REASON><TABLENAMES>CNF_PriceList=PriceListId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
           WHERE Name = N'SortOrder' AND
           Object_ID  = Object_ID(N'CNF_PriceList'))
BEGIN
  ALTER TABLE CNF_PriceList 
  ADD SortOrder Integer NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>pdalben</ADDEDBY><SQLVERSION>3032</SQLVERSION><RMTRACKLINK>86507</RMTRACKLINK><REASON>Added LocationRouteId to DATA_TicketUsage</REASON><TABLENAMES>DATA_TicketUsage=UsageId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
WHERE Name = N'LocationRouteId' AND OBJECT_ID = OBJECT_ID(N'DATA_TicketUsage'))
BEGIN
  ALTER TABLE DATA_TicketUsage ADD LocationRouteId Integer NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>3031</SQLVERSION><RMTRACKLINK>IDBOS-1523</RMTRACKLINK><REASON>Adding indexes on SaleItem2CostCenter</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT object_id
        FROM sys.indexes
        WHERE Name = 'Idx_SaleItem2Cost_CC_SI_TR')
BEGIN
  CREATE NONCLUSTERED INDEX [Idx_SaleItem2Cost_CC_SI_TR]
  ON [dbo].[DATA_SaleItem2CostCenter] ([CostCenterId] Desc,[SaleItemId] Desc,[TransactionId] Desc)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT object_id
        FROM sys.indexes
        WHERE Name = 'Idx_SaleItem2Cost_CC_SL')
BEGIN
  CREATE NONCLUSTERED INDEX [Idx_SaleItem2Cost_CC_SL]
  ON [dbo].[DATA_SaleItem2CostCenter] ([CostCenterId] Desc,[SaleItemId] Desc)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT object_id
        FROM sys.indexes
        WHERE Name = 'Idx_SaleItem2Cost_TR')
BEGIN
  CREATE NONCLUSTERED INDEX [Idx_SaleItem2Cost_TR]
  ON [dbo].[DATA_SaleItem2CostCenter] ([TransactionId] Desc)
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>3030</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES>CNF_Product=ProductId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>DISABLE TRIGGER CNF_DBColumn_CT ON CNF_DBColumn; 

ALTER TABLE DATA_HL_Detail  
NOCHECK CONSTRAINT FK_DATA_HL_Detail_DBColumnId;  

ALTER TABLE DATA_HL_Master
NOCHECK CONSTRAINT FK_DATA_HL_Master_DBTableId;  

delete 
from CNF_DBColumn
where dbtableid in (
		select dbtableid
		from CNF_DBTable
		where tablename in ('CNF_Family', 'CNF_Shell', 'CNF_UpSale', 'CNF_Card', 'CNF_CardBonus', 'CNF_CC2OperatingArea', 'CNF_Entity', 'CNF_Entity2Attribute',
		'CNF_MapView', 'CNF_delivery2entity', 'CNF_AccountRestriction2Performance')
)</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>delete
from CNF_DBTable
where tablename in ('CNF_Family', 'CNF_Shell', 'CNF_UpSale', 'CNF_Card', 'CNF_CardBonus', 'CNF_CC2OperatingArea', 'CNF_Entity', 'CNF_Entity2Attribute',
'CNF_MapView', 'CNF_delivery2entity',  'CNF_AccountRestriction2Performance')</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF (EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                 WHERE TABLE_SCHEMA = 'dbo' 
                 AND  TABLE_NAME = 'CNF_Family'))
BEGIN
  drop table CNF_Family
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF (EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                 WHERE TABLE_SCHEMA = 'dbo' 
                 AND  TABLE_NAME = 'CNF_UpSale'))
BEGIN
  drop table CNF_UpSale
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF (EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                 WHERE TABLE_SCHEMA = 'dbo' 
                 AND  TABLE_NAME = 'CNF_CardBonus'))
BEGIN
  drop table CNF_CardBonus
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF (EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                 WHERE TABLE_SCHEMA = 'dbo' 
                 AND  TABLE_NAME = 'CNF_CC2OperatingArea'))
BEGIN
  drop table CNF_CC2OperatingArea
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF (EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                 WHERE TABLE_SCHEMA = 'dbo' 
                 AND  TABLE_NAME = 'CNF_Entity'))
BEGIN
  drop table CNF_Entity
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF (EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                 WHERE TABLE_SCHEMA = 'dbo' 
                 AND  TABLE_NAME = 'CNF_Entity2Attribute'))
BEGIN
  drop table CNF_Entity2Attribute
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF (EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                 WHERE TABLE_SCHEMA = 'dbo' 
                 AND  TABLE_NAME = 'CNF_delivery2entity'))
BEGIN
  drop table CNF_delivery2entity
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF (EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                 WHERE TABLE_SCHEMA = 'dbo' 
                 AND  TABLE_NAME = 'CNF_AccountRestriction2Performance'))
BEGIN
  drop table CNF_AccountRestriction2Performance
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>exec Otn_Remove_ForeingKey 'cnf_product', 'cnf_shell', 'ShellID', 0</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT 1 FROM sys.columns 
			WHERE Name = N'ShellID'
			AND Object_ID = Object_ID(N'DBO.cnf_product'))
BEGIN
   ALTER TABLE cnf_product DROP COLUMN ShellID;
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF (EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                 WHERE TABLE_SCHEMA = 'dbo' 
                 AND  TABLE_NAME = 'CNF_Shell'))
BEGIN
  drop table CNF_Shell
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>exec Otn_Remove_ForeingKey 'dbo.CNF_SeatLayoutItem', 'dbo.CNF_MapView', 'MapID', 0</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF (EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                 WHERE TABLE_SCHEMA = 'dbo' 
                 AND  TABLE_NAME = 'CNF_MapView'))
BEGIN
  drop table CNF_MapView
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>exec Otn_Remove_ForeingKey 'dbo.cnf_Upgrade', 'dbo.cnf_card', 'PRODUCTID', 0</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF (EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                 WHERE TABLE_SCHEMA = 'dbo' 
                 AND  TABLE_NAME = 'CNF_Card'))
BEGIN
  drop table CNF_Card
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>ALTER TABLE DATA_HL_Master
CHECK CONSTRAINT FK_DATA_HL_Master_DBTableId;  

ALTER TABLE DATA_HL_Detail  
CHECK CONSTRAINT FK_DATA_HL_Detail_DBColumnId;  

ENABLE TRIGGER CNF_DBColumn_CT ON CNF_DBColumn; 
</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dstornaiuolo</ADDEDBY><SQLVERSION>3029</SQLVERSION><RMTRACKLINK>IDBOS-858</RMTRACKLINK><REASON>Script 0 : Adding AlertStatus to MSG_CNF_Message
Script 1 : Adding AlertType to MSG_CNF_Message</REASON><TABLENAMES>MSG_CNF_Message=MessageId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
           WHERE Name = N'AlertStatus' AND
           Object_ID  = Object_ID(N'MSG_CNF_Message'))
BEGIN
  ALTER TABLE MSG_CNF_Message 
  ADD AlertStatus SMALLINT NOT NULL DEFAULT 0
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
           WHERE Name = N'AlertType' AND
           Object_ID  = Object_ID(N'MSG_CNF_Message'))
BEGIN
  ALTER TABLE MSG_CNF_Message 
  ADD AlertType SMALLINT NOT NULL DEFAULT 0
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>3028</SQLVERSION><RMTRACKLINK>IDBOS-1391</RMTRACKLINK><REASON>0 : Adding NDaysBefore to CNF_SuggestiveSell
1 : Adding NDaysAfter to CNF_SuggestiveSell</REASON><TABLENAMES>CNF_SuggestiveSell=SuggestiveSellId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
           WHERE Name = N'NDaysBefore' AND
           Object_ID  = Object_ID(N'CNF_SuggestiveSell'))
BEGIN
  ALTER TABLE CNF_SuggestiveSell
  ADD NDaysBefore Integer NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
           WHERE Name = N'NDaysAfter' AND
           Object_ID  = Object_ID(N'CNF_SuggestiveSell'))
BEGIN
  ALTER TABLE CNF_SuggestiveSell
  ADD NDaysAfter Integer NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fesposito</ADDEDBY><SQLVERSION>3027</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>Adding WorkstationId to DATA_TicketExport</REASON><TABLENAMES>DATA_TicketExport=TicketExportId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS ( SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND  TABLE_NAME = 'DATA_TicketExport2Ticket' )

BEGIN
   DELETE FROM DATA_TicketExport2Ticket
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS ( SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND  TABLE_NAME = 'DATA_TicketExportDetail' )

BEGIN
   DELETE FROM DATA_TicketExportDetail
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS ( SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND  TABLE_NAME = 'DATA_TicketExport' )

BEGIN
   DELETE FROM DATA_TicketExport
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
           WHERE Name = N'WorkstationId' AND
           Object_ID  = Object_ID(N'DATA_TicketExport'))
BEGIN
  ALTER TABLE DATA_TicketExport
  ADD WorkstationId Integer NOT NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_TicketExport_WorkstationId')
BEGIN
  ALTER TABLE DATA_TicketExport
  ADD CONSTRAINT [FK_DATA_TicketExport_WorkstationId] FOREIGN KEY([WorkstationId]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>3026</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.objects WHERE [name] = N'data_sale_SalesRestriction' AND [type] = 'TR')
BEGIN
      DROP TRIGGER [dbo].[data_sale_SalesRestriction];
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>Create trigger [dbo].[data_sale_SalesRestriction] on [dbo].[DATA_Sale] FOR update
	 as
begin
	SET NOCOUNT ON;
    IF UPDATE(Approved) or Update(StatusCode)
    BEGIN

		Declare @Temp table (	AccountID int, 
								SaleID int,
								SaleItemID int,
								PerformanceID int,
								Quantity int,
								SalesDate DateTime,
								MatrixCellID int,
								RestrictionType int
							)

		DECLARE @INS_SaleID int
		DECLARE @status int = 0 
		DECLARE @DR_status int

		DECLARE	@ReservationAccountID int
		DECLARE	@B2BAccountID int  
		DECLARE	@TicketAccountID int
		DECLARE	@SaleID int
		DECLARE	@SaleItemID int
		DECLARE @UsageCheck int
		DECLARE	@PerformanceID int
		DECLARE	@Quantity int
		DECLARE @MatrixCellID int
		DECLARE @EventID int

		DECLARE @RestrictionType int	
			
		DECLARE @ReservationAccountOwner int = 1
		DECLARE @TicketAccountOwner int = 2
		DECLARE @CheckforRestraintOnly int = 0

		SELECT @status=i.Approved, @INS_SaleID = i.Saleid 
				FROM inserted i
				JOIN deleted d
					ON i.SaleID = d.SaleID
					AND i.Approved &lt;&gt; d.Approved

		if @status = 0 
		begin
			SELECT @DR_status = CASE WHEN i.StatusCode = 2 then  1
			            else 0
					end, 
			       @INS_SaleID = i.Saleid 
					FROM inserted i
					JOIN deleted d
						ON i.[SaleID] = d.[SaleID]
						AND i.[StatusCode] &lt;&gt; d.[StatusCode]
		end


		if @status = 1
		begin
			DECLARE SaleItem_Cursor CURSOR LOCAL FOR
					select  ISNULL(data_reservation.accountid, ODR.AccountID) as AccountID,
						    ISNULL(data_reservation.B2bAccountID, ODR.B2bAccountID) as B2bAccountID,
							data_saleitem.Matrixcellid,
							case when data_saleitem2account.Accountid is not null then case when data_saleitem.Quantity &lt; 0 then -1 else 1 end
									else data_saleitem.Quantity
								end Quantity,
							data_saleitem2account.Accountid,
							data_sale.saleid,
							data_saleitem.saleitemid,
							case when data_saleitem.Quantity &lt; 0 then ISNULL((select top 1 1
																				from data_transaction
																				where data_transaction.transactiontype in (17, 18, 20, 40, 47)
																				  and data_transaction.saleid = data_sale.saleid), 0)
							     else 0
							 end as UsageCheck

					from data_sale WITH(NOLOCK)
						LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
						INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
						LEFT  JOIN data_saleitem2account WITH(NOLOCK)				on data_saleitem2account.SaleitemID = data_saleitem.saleitemid
						left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
						left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

					Where data_sale.saleid = @INS_SaleID
										
			OPEN SaleItem_Cursor

				FETCH NEXT FROM SaleItem_Cursor INTO
									@ReservationAccountID, 
									@B2BAccountID,
									@MatrixCellID,
									@Quantity,
									@TicketAccountID,
									@SaleID,
									@SaleItemID,
									@UsageCheck

				WHILE @@FETCH_STATUS = 0
				BEGIN
					if @UsageCheck = 0 
					BEGIN
						--   Ticket Test   with Ticket Owner				@TicketAccountOwner              --@RestrictionType = 1	
						exec otn_sp_GetAccountRestrictions @TicketAccountID,								--AccountID
														   @MatrixCellID,									--MatrixCellID
														   null,											--PerformanceID
														   null,											--EventID
														   @Quantity,										--Quantity
														   1,												--RestrictionType
														   @SaleID,											--SaleID
														   @SaleItemID,										--SaleItemID
														   0,												--CheckforRestrictionOnly
														   @TicketAccountOwner								--ReservationorTicketAccount		

				
						--   Ticket Test   with Reservation Owner			@ReservationAccountOwner         --@RestrictionType = 1
						exec otn_sp_GetAccountRestrictions @B2BAccountID,							--AccountID
														   @MatrixCellID,									--MatrixCellID
														   null,											--PerformanceID
														   null,											--EventID
														   @Quantity,										--Quantity
														   1,												--RestrictionType
														   @SaleID,											--SaleID
														   @SaleItemID,										--SaleItemID
														   0,												--CheckforRestrictionOnly
														   @ReservationAccountOwner							--ReservationorTicketAccount	

						--   Ticket Test   with Reservation Owner			@ReservationAccountOwner         --@RestrictionType = 1
						exec otn_sp_GetAccountRestrictions @ReservationAccountID,							--AccountID
														   @MatrixCellID,									--MatrixCellID
														   null,											--PerformanceID
														   null,											--EventID
														   @Quantity,										--Quantity
														   1,												--RestrictionType
														   @SaleID,											--SaleID
														   @SaleItemID,										--SaleItemID
														   0,												--CheckforRestrictionOnly
														   @ReservationAccountOwner							--ReservationorTicketAccount	

						DECLARE Performance_Cursor CURSOR LOCAL FOR
							  select data_saleitem2Performance.PerformanceID,
									 cnf_Performance.eventid

								from data_saleitem2Performance WITH(NOLOCK)																					   
									LEFT  JOIN cnf_Performance WITH(NOLOCK)						on cnf_Performance.PerformanceID = data_saleitem2Performance.PerformanceID
						
								Where Active = 1
								  and data_saleitem2Performance.Saleitemid = @SaleItemID

						OPEN Performance_Cursor

							FETCH NEXT FROM Performance_Cursor INTO
												@PerformanceID,
												@EventID

							WHILE @@FETCH_STATUS = 0
							BEGIN
									--	Perforamnce Test     with Ticket Owner			@TicketAccountOwner              --@RestrictionType = 2
									exec otn_sp_GetAccountRestrictions @TicketAccountID,								--AccountID
																	   @MatrixCellID,									--MatrixCellID
																	   @PerformanceID,									--PerformanceID
																	   @EventID,										--EventID
																	   @Quantity,										--Quantity
																	   2,												--RestrictionType
																	   @SaleID,											--SaleID
																	   @SaleItemID,										--SaleItemID
																	   0,												--CheckforRestrictionOnly
																	   @TicketAccountOwner								--ReservationorTicketAccount	

									--   Performance Test     with Reservation Owner    @TicketAccountOwner              --@RestrictionType = 2
									exec otn_sp_GetAccountRestrictions @ReservationAccountID,							--AccountID
																	   @MatrixCellID,									--MatrixCellID
																	   @PerformanceID,									--PerformanceID
																	   @EventID,										--EventID
																	   @Quantity,										--Quantity
																	   2,												--RestrictionType
																	   @SaleID,											--SaleID
																	   @SaleItemID,										--SaleItemID
																	   0,												--CheckforRestrictionOnly
																	   @ReservationAccountOwner								--ReservationorTicketAccount	


									FETCH NEXT FROM Performance_Cursor INTO
														@PerformanceID,
														@EventID
							END
							CLOSE Performance_Cursor;
							DEALLOCATE Performance_Cursor;
					end
					FETCH NEXT FROM SaleItem_Cursor INTO
										@ReservationAccountID, 
										@B2BAccountID,
										@MatrixCellID,
										@Quantity,
										@TicketAccountID,
										@SaleID,
										@SaleItemID,
										@UsageCheck
				end

			CLOSE SaleItem_Cursor;
			DEALLOCATE SaleItem_Cursor;
		END

		if @DR_status = 1
		begin
			DECLARE SaleItem_Cursor CURSOR LOCAL FOR
					select data_reservation.accountid, 
						   data_reservation.B2bAccountID,
						   data_saleitem.Matrixcellid,
							case when data_saleitem2account.Accountid is not null then -1
								 else data_saleitem.Quantity
							 end Quantity,
						   data_saleitem2account.Accountid,
						   data_sale.saleid,
						   data_saleitem.saleitemid

					from data_sale WITH(NOLOCK)
						LEFT JOIN data_reservation WITH(NOLOCK)					    on data_reservation.saleid = data_sale.saleid
						INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
						LEFT  JOIN data_saleitem2account WITH(NOLOCK)				on data_saleitem2account.SaleitemID = data_saleitem.saleitemid

					Where data_sale.saleid = @INS_SaleID
					  and data_saleitem.quantity &lt; 0 
					
			OPEN SaleItem_Cursor

			FETCH NEXT FROM SaleItem_Cursor INTO
								@ReservationAccountID, 
								@B2BAccountID,
								@MatrixCellID,
								@Quantity,
								@TicketAccountID,
								@SaleID,
								@SaleItemID

			WHILE @@FETCH_STATUS = 0
			BEGIN

				--   Ticket Test   with Ticket Owner				@TicketAccountOwner              --@RestrictionType = 1	
				exec otn_sp_GetAccountRestrictions @TicketAccountID,								--AccountID
				                                   @MatrixCellID,									--MatrixCellID
												   null,											--PerformanceID
												   null,											--EventID
												   @Quantity,										--Quantity
												   1,												--RestrictionType
												   @SaleID,											--SaleID
												   @SaleItemID,										--SaleItemID
												   0,												--CheckforRestrictionOnly
												   @TicketAccountOwner								--ReservationorTicketAccount		

				
				--   Ticket Test   with Reservation Owner			@ReservationAccountOwner         --@RestrictionType = 1
				exec otn_sp_GetAccountRestrictions @B2BAccountID,							        --AccountID
				                                   @MatrixCellID,									--MatrixCellID
												   null,											--PerformanceID
												   null,											--EventID
												   @Quantity,										--Quantity
												   1,												--RestrictionType
												   @SaleID,											--SaleID
												   @SaleItemID,										--SaleItemID
												   0,												--CheckforRestrictionOnly
												   @ReservationAccountOwner							--ReservationorTicketAccount
												   
				--   Ticket Test   with Reservation Owner			@ReservationAccountOwner         --@RestrictionType = 1
				exec otn_sp_GetAccountRestrictions @ReservationAccountID,							--AccountID
				                                   @MatrixCellID,									--MatrixCellID
												   null,											--PerformanceID
												   null,											--EventID
												   @Quantity,										--Quantity
												   1,												--RestrictionType
												   @SaleID,											--SaleID
												   @SaleItemID,										--SaleItemID
												   0,												--CheckforRestrictionOnly
												   @ReservationAccountOwner							--ReservationorTicketAccount													   	

			DECLARE Performance_Cursor CURSOR LOCAL FOR
						  select data_saleitem2Performance.PerformanceID,
						         cnf_Performance.eventid

							from data_saleitem2Performance WITH(NOLOCK)																					   
								LEFT  JOIN cnf_Performance WITH(NOLOCK)						on cnf_Performance.PerformanceID = data_saleitem2Performance.PerformanceID
						
							Where Active = 1
							  and data_saleitem2Performance.Saleitemid = @SaleItemID

					OPEN Performance_Cursor

						FETCH NEXT FROM Performance_Cursor INTO
											@PerformanceID,
											@EventID

						WHILE @@FETCH_STATUS = 0
						BEGIN
								--	Perforamnce Test     with Ticket Owner			@TicketAccountOwner              --@RestrictionType = 2
								exec otn_sp_GetAccountRestrictions @TicketAccountID,								--AccountID
																   @MatrixCellID,									--MatrixCellID
																   @PerformanceID,									--PerformanceID
																   @EventID,										--EventID
																   @Quantity,										--Quantity
																   2,												--RestrictionType
																   @SaleID,											--SaleID
																   @SaleItemID,										--SaleItemID
																   0,												--CheckforRestrictionOnly
																   @TicketAccountOwner								--ReservationorTicketAccount	

								--   Performance Test     with Reservation Owner    @TicketAccountOwner              --@RestrictionType = 2
								exec otn_sp_GetAccountRestrictions @ReservationAccountID,							--AccountID
																   @MatrixCellID,									--MatrixCellID
																   @PerformanceID,									--PerformanceID
																   @EventID,										--EventID
																   @Quantity,										--Quantity
																   2,												--RestrictionType
																   @SaleID,											--SaleID
																   @SaleItemID,										--SaleItemID
																   0,												--CheckforRestrictionOnly
																   @ReservationAccountOwner								--ReservationorTicketAccount	
						FETCH NEXT FROM Performance_Cursor INTO
											@PerformanceID,
											@EventID
				END
				CLOSE Performance_Cursor;
				DEALLOCATE Performance_Cursor;

				FETCH NEXT FROM SaleItem_Cursor INTO
								@ReservationAccountID, 
								@B2BAccountID,
								@MatrixCellID,
								@Quantity,
								@TicketAccountID,
								@SaleID,
								@SaleItemID

			end
			CLOSE SaleItem_Cursor;
			DEALLOCATE SaleItem_Cursor;
		end
	end
end</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>ALTER TABLE [dbo].[DATA_Sale] ENABLE TRIGGER [data_sale_SalesRestriction]</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fesposito</ADDEDBY><SQLVERSION>3025</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>Adding the field Voided</REASON><TABLENAMES>DATA_TicketExport2Ticket=TicketExport2TicketId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS ( SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND  TABLE_NAME = 'DATA_TicketExport2Ticket' )

BEGIN
   DELETE FROM DATA_TicketExport2Ticket
END

</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS ( SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND  TABLE_NAME = 'DATA_TicketExportDetail' )

BEGIN
   DELETE FROM DATA_TicketExportDetail
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS ( SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND  TABLE_NAME = 'DATA_TicketExport' )

BEGIN
   DELETE FROM DATA_TicketExport
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
           WHERE Name = N'Voided' AND
           Object_ID  = Object_ID(N'DATA_TicketExport2Ticket'))
BEGIN
  ALTER TABLE DATA_TicketExport2Ticket 
  ADD Voided SMALLINT NOT NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>3024</SQLVERSION><RMTRACKLINK>86522</RMTRACKLINK><REASON>86522 - Refund of used ticket is being returned to account restriction current quantity</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.objects WHERE [name] = N'data_sale_SalesRestriction' AND [type] = 'TR')
BEGIN
      DROP TRIGGER [dbo].[data_sale_SalesRestriction];
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>Create trigger [dbo].[data_sale_SalesRestriction] on [dbo].[DATA_Sale] FOR update
	 as
begin
	SET NOCOUNT ON;
    IF UPDATE(Approved) or Update(StatusCode)
    BEGIN

		Declare @Temp table (	AccountID int, 
								SaleID int,
								SaleItemID int,
								PerformanceID int,
								Quantity int,
								SalesDate DateTime,
								MatrixCellID int,
								RestrictionType int
							)

		DECLARE @INS_SaleID int
		DECLARE @status int = 0 
		DECLARE @DR_status int

		DECLARE	@ReservationAccountID int
		DECLARE	@B2BAccountID int  
		DECLARE	@TicketAccountID int
		DECLARE	@SaleID int
		DECLARE	@SaleItemID int
		DECLARE @UsageCheck int
		DECLARE	@PerformanceID int
		DECLARE	@Quantity int
		DECLARE @MatrixCellID int
		DECLARE @EventID int

		DECLARE @RestrictionType int	
			
		DECLARE @ReservationAccountOwner int = 1
		DECLARE @TicketAccountOwner int = 2
		DECLARE @CheckforRestraintOnly int = 0

		SELECT @status=i.Approved, @INS_SaleID = i.Saleid 
				FROM inserted i
				JOIN deleted d
					ON i.SaleID = d.SaleID
					AND i.Approved &lt;&gt; d.Approved

		if @status = 0 
		begin
			SELECT @DR_status = CASE WHEN i.StatusCode = 2 then  1
			            else 0
					end, 
			       @INS_SaleID = i.Saleid 
					FROM inserted i
					JOIN deleted d
						ON i.[SaleID] = d.[SaleID]
						AND i.[StatusCode] &lt;&gt; d.[StatusCode]
		end


		if @status = 1
		begin
			DECLARE SaleItem_Cursor CURSOR LOCAL FOR
					select  ISNULL(data_reservation.accountid, ODR.AccountID) as AccountID,
						    ISNULL(data_reservation.B2bAccountID, ODR.B2bAccountID) as B2bAccountID,
							data_saleitem.Matrixcellid,
							case when data_saleitem2account.Accountid is not null then case when data_saleitem.Quantity &lt; 0 then -1 else 1 end
									else data_saleitem.Quantity
								end Quantity,
							data_saleitem2account.Accountid,
							data_sale.saleid,
							data_saleitem.saleitemid,
							case when data_saleitem.Quantity &lt; 0 then ISNULL((select top 1 1
																				from data_saleitem2ticket
																					INNER JOIN data_ticketusage						ON data_ticketusage.ticketid = data_saleitem2ticket.ticketid
																				where data_ticketusage.validateresult &lt;= 99
																				  and data_saleitem2ticket.saleitemid = data_saleitem.saleitemid), 0)
							     else 0
							 end as UsageCheck

					from data_sale WITH(NOLOCK)
						LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
						INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
						LEFT  JOIN data_saleitem2account WITH(NOLOCK)				on data_saleitem2account.SaleitemID = data_saleitem.saleitemid
						left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
						left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

					Where data_sale.saleid = @INS_SaleID
										
			OPEN SaleItem_Cursor

				FETCH NEXT FROM SaleItem_Cursor INTO
									@ReservationAccountID, 
									@B2BAccountID,
									@MatrixCellID,
									@Quantity,
									@TicketAccountID,
									@SaleID,
									@SaleItemID,
									@UsageCheck

				WHILE @@FETCH_STATUS = 0
				BEGIN
					if @UsageCheck = 0 
					BEGIN
						--   Ticket Test   with Ticket Owner				@TicketAccountOwner              --@RestrictionType = 1	
						exec otn_sp_GetAccountRestrictions @TicketAccountID,								--AccountID
														   @MatrixCellID,									--MatrixCellID
														   null,											--PerformanceID
														   null,											--EventID
														   @Quantity,										--Quantity
														   1,												--RestrictionType
														   @SaleID,											--SaleID
														   @SaleItemID,										--SaleItemID
														   0,												--CheckforRestrictionOnly
														   @TicketAccountOwner								--ReservationorTicketAccount		

				
						--   Ticket Test   with Reservation Owner			@ReservationAccountOwner         --@RestrictionType = 1
						exec otn_sp_GetAccountRestrictions @B2BAccountID,							--AccountID
														   @MatrixCellID,									--MatrixCellID
														   null,											--PerformanceID
														   null,											--EventID
														   @Quantity,										--Quantity
														   1,												--RestrictionType
														   @SaleID,											--SaleID
														   @SaleItemID,										--SaleItemID
														   0,												--CheckforRestrictionOnly
														   @ReservationAccountOwner							--ReservationorTicketAccount	

						--   Ticket Test   with Reservation Owner			@ReservationAccountOwner         --@RestrictionType = 1
						exec otn_sp_GetAccountRestrictions @ReservationAccountID,							--AccountID
														   @MatrixCellID,									--MatrixCellID
														   null,											--PerformanceID
														   null,											--EventID
														   @Quantity,										--Quantity
														   1,												--RestrictionType
														   @SaleID,											--SaleID
														   @SaleItemID,										--SaleItemID
														   0,												--CheckforRestrictionOnly
														   @ReservationAccountOwner							--ReservationorTicketAccount	

						DECLARE Performance_Cursor CURSOR LOCAL FOR
							  select data_saleitem2Performance.PerformanceID,
									 cnf_Performance.eventid

								from data_saleitem2Performance WITH(NOLOCK)																					   
									LEFT  JOIN cnf_Performance WITH(NOLOCK)						on cnf_Performance.PerformanceID = data_saleitem2Performance.PerformanceID
						
								Where Active = 1
								  and data_saleitem2Performance.Saleitemid = @SaleItemID

						OPEN Performance_Cursor

							FETCH NEXT FROM Performance_Cursor INTO
												@PerformanceID,
												@EventID

							WHILE @@FETCH_STATUS = 0
							BEGIN
									--	Perforamnce Test     with Ticket Owner			@TicketAccountOwner              --@RestrictionType = 2
									exec otn_sp_GetAccountRestrictions @TicketAccountID,								--AccountID
																	   @MatrixCellID,									--MatrixCellID
																	   @PerformanceID,									--PerformanceID
																	   @EventID,										--EventID
																	   @Quantity,										--Quantity
																	   2,												--RestrictionType
																	   @SaleID,											--SaleID
																	   @SaleItemID,										--SaleItemID
																	   0,												--CheckforRestrictionOnly
																	   @TicketAccountOwner								--ReservationorTicketAccount	

									--   Performance Test     with Reservation Owner    @TicketAccountOwner              --@RestrictionType = 2
									exec otn_sp_GetAccountRestrictions @ReservationAccountID,							--AccountID
																	   @MatrixCellID,									--MatrixCellID
																	   @PerformanceID,									--PerformanceID
																	   @EventID,										--EventID
																	   @Quantity,										--Quantity
																	   2,												--RestrictionType
																	   @SaleID,											--SaleID
																	   @SaleItemID,										--SaleItemID
																	   0,												--CheckforRestrictionOnly
																	   @ReservationAccountOwner								--ReservationorTicketAccount	


									FETCH NEXT FROM Performance_Cursor INTO
														@PerformanceID,
														@EventID
							END
							CLOSE Performance_Cursor;
							DEALLOCATE Performance_Cursor;
					end
					FETCH NEXT FROM SaleItem_Cursor INTO
										@ReservationAccountID, 
										@B2BAccountID,
										@MatrixCellID,
										@Quantity,
										@TicketAccountID,
										@SaleID,
										@SaleItemID,
										@UsageCheck
				end

			CLOSE SaleItem_Cursor;
			DEALLOCATE SaleItem_Cursor;
		END

		if @DR_status = 1
		begin
			DECLARE SaleItem_Cursor CURSOR LOCAL FOR
					select data_reservation.accountid, 
						   data_reservation.B2bAccountID,
						   data_saleitem.Matrixcellid,
							case when data_saleitem2account.Accountid is not null then -1
								 else data_saleitem.Quantity
							 end Quantity,
						   data_saleitem2account.Accountid,
						   data_sale.saleid,
						   data_saleitem.saleitemid

					from data_sale WITH(NOLOCK)
						LEFT JOIN data_reservation WITH(NOLOCK)					    on data_reservation.saleid = data_sale.saleid
						INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
						LEFT  JOIN data_saleitem2account WITH(NOLOCK)				on data_saleitem2account.SaleitemID = data_saleitem.saleitemid

					Where data_sale.saleid = @INS_SaleID
					  and data_saleitem.quantity &lt; 0 
					
			OPEN SaleItem_Cursor

			FETCH NEXT FROM SaleItem_Cursor INTO
								@ReservationAccountID, 
								@B2BAccountID,
								@MatrixCellID,
								@Quantity,
								@TicketAccountID,
								@SaleID,
								@SaleItemID

			WHILE @@FETCH_STATUS = 0
			BEGIN

				--   Ticket Test   with Ticket Owner				@TicketAccountOwner              --@RestrictionType = 1	
				exec otn_sp_GetAccountRestrictions @TicketAccountID,								--AccountID
				                                   @MatrixCellID,									--MatrixCellID
												   null,											--PerformanceID
												   null,											--EventID
												   @Quantity,										--Quantity
												   1,												--RestrictionType
												   @SaleID,											--SaleID
												   @SaleItemID,										--SaleItemID
												   0,												--CheckforRestrictionOnly
												   @TicketAccountOwner								--ReservationorTicketAccount		

				
				--   Ticket Test   with Reservation Owner			@ReservationAccountOwner         --@RestrictionType = 1
				exec otn_sp_GetAccountRestrictions @B2BAccountID,							        --AccountID
				                                   @MatrixCellID,									--MatrixCellID
												   null,											--PerformanceID
												   null,											--EventID
												   @Quantity,										--Quantity
												   1,												--RestrictionType
												   @SaleID,											--SaleID
												   @SaleItemID,										--SaleItemID
												   0,												--CheckforRestrictionOnly
												   @ReservationAccountOwner							--ReservationorTicketAccount
												   
				--   Ticket Test   with Reservation Owner			@ReservationAccountOwner         --@RestrictionType = 1
				exec otn_sp_GetAccountRestrictions @ReservationAccountID,							--AccountID
				                                   @MatrixCellID,									--MatrixCellID
												   null,											--PerformanceID
												   null,											--EventID
												   @Quantity,										--Quantity
												   1,												--RestrictionType
												   @SaleID,											--SaleID
												   @SaleItemID,										--SaleItemID
												   0,												--CheckforRestrictionOnly
												   @ReservationAccountOwner							--ReservationorTicketAccount													   	

			DECLARE Performance_Cursor CURSOR LOCAL FOR
						  select data_saleitem2Performance.PerformanceID,
						         cnf_Performance.eventid

							from data_saleitem2Performance WITH(NOLOCK)																					   
								LEFT  JOIN cnf_Performance WITH(NOLOCK)						on cnf_Performance.PerformanceID = data_saleitem2Performance.PerformanceID
						
							Where Active = 1
							  and data_saleitem2Performance.Saleitemid = @SaleItemID

					OPEN Performance_Cursor

						FETCH NEXT FROM Performance_Cursor INTO
											@PerformanceID,
											@EventID

						WHILE @@FETCH_STATUS = 0
						BEGIN
								--	Perforamnce Test     with Ticket Owner			@TicketAccountOwner              --@RestrictionType = 2
								exec otn_sp_GetAccountRestrictions @TicketAccountID,								--AccountID
																   @MatrixCellID,									--MatrixCellID
																   @PerformanceID,									--PerformanceID
																   @EventID,										--EventID
																   @Quantity,										--Quantity
																   2,												--RestrictionType
																   @SaleID,											--SaleID
																   @SaleItemID,										--SaleItemID
																   0,												--CheckforRestrictionOnly
																   @TicketAccountOwner								--ReservationorTicketAccount	

								--   Performance Test     with Reservation Owner    @TicketAccountOwner              --@RestrictionType = 2
								exec otn_sp_GetAccountRestrictions @ReservationAccountID,							--AccountID
																   @MatrixCellID,									--MatrixCellID
																   @PerformanceID,									--PerformanceID
																   @EventID,										--EventID
																   @Quantity,										--Quantity
																   2,												--RestrictionType
																   @SaleID,											--SaleID
																   @SaleItemID,										--SaleItemID
																   0,												--CheckforRestrictionOnly
																   @ReservationAccountOwner								--ReservationorTicketAccount	
						FETCH NEXT FROM Performance_Cursor INTO
											@PerformanceID,
											@EventID
				END
				CLOSE Performance_Cursor;
				DEALLOCATE Performance_Cursor;

				FETCH NEXT FROM SaleItem_Cursor INTO
								@ReservationAccountID, 
								@B2BAccountID,
								@MatrixCellID,
								@Quantity,
								@TicketAccountID,
								@SaleID,
								@SaleItemID

			end
			CLOSE SaleItem_Cursor;
			DEALLOCATE SaleItem_Cursor;
		end
	end
end</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fesposito</ADDEDBY><SQLVERSION>3023</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>Recreating DATA_TicketExport, DATA_TicketExportDetail,DATA_TicketExport2Ticket</REASON><TABLENAMES>DATA_TicketExport=TicketExportId
DATA_TicketExportDetail=TicketExportDetailId
DATA_TicketExport2Ticket=TicketExport2TicketId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS ( SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND  TABLE_NAME = 'DATA_TicketExport2Ticket' )

BEGIN
   DROP TABLE DATA_TicketExport2Ticket
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS ( SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND  TABLE_NAME = 'DATA_TicketExportDetail' )

BEGIN
   DROP TABLE DATA_TicketExportDetail
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS ( SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND  TABLE_NAME = 'DATA_TicketExport' )

BEGIN
   DROP TABLE DATA_TicketExport
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                WHERE TABLE_SCHEMA = 'dbo' 
                  AND TABLE_NAME = 'DATA_TicketExport')
BEGIN
Create table [DATA_TicketExport]
(
	[TicketExportId] Integer Identity(1,1) NOT NULL,
	[UserId] Integer NOT NULL,
	[CreationDate] Datetime NOT NULL,
	[ProcessCode] Nvarchar(50) NOT NULL,
	[PerformanceId] Integer NULL,
Primary Key ([TicketExportId])
) 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                WHERE TABLE_SCHEMA = 'dbo' 
                  AND TABLE_NAME = 'DATA_TicketExportDetail')
BEGIN
Create table [DATA_TicketExportDetail]
(
	[TicketExportDetailId] Integer Identity(1,1) NOT NULL,
	[TicketExportId] Integer NOT NULL,
	[ProcessToken] Nvarchar(50) NOT NULL,
	[ExportDate] Datetime NOT NULL,
	[TicketQuantity] Integer NOT NULL,
	[CompletionDate] Datetime NULL,
Primary Key ([TicketExportDetailId])
) 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                WHERE TABLE_SCHEMA = 'dbo' 
                  AND TABLE_NAME = 'DATA_TicketExport2Ticket')
BEGIN
Create table [DATA_TicketExport2Ticket]
(
	[TicketExport2TicketId] Integer Identity(1,1) NOT NULL,
	[TicketExportId] Integer NOT NULL,
	[TicketExportDetailId] Integer NOT NULL,
	[TicketId] Integer NOT NULL,
	[VoidType] SmallInt NOT NULL,
	[IdentifierCode] Nvarchar(50) NOT NULL,
	[SeatId] Integer NULL,
	[Price] Float NULL,
	[Description] NVarchar(100) NULL,
	[Description2] NVarchar(100) NULL, 
Primary Key ([TicketExport2TicketId])
) 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_TicketExport_UserId')
BEGIN
  ALTER TABLE DATA_TicketExport
  ADD CONSTRAINT [FK_DATA_TicketExport_UserId] FOREIGN KEY([UserId]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_TicketExport_PerformanceId')
BEGIN
  ALTER TABLE DATA_TicketExport
  ADD CONSTRAINT [FK_DATA_TicketExport_PerformanceId] FOREIGN KEY([PerformanceId]) 
  REFERENCES [CNF_Performance] ([PerformanceId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_TicketExportDetail_TicketExportId')
BEGIN
  ALTER TABLE DATA_TicketExportDetail
  ADD CONSTRAINT [FK_DATA_TicketExportDetail_TicketExportId] FOREIGN KEY([TicketExportId]) 
  REFERENCES [DATA_TicketExport] ([TicketExportId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_TicketExport2Ticket_TicketExportId')
BEGIN
  ALTER TABLE DATA_TicketExport2Ticket
  ADD CONSTRAINT [FK_DATA_TicketExport2Ticket_TicketExportId] FOREIGN KEY([TicketExportId]) 
  REFERENCES [DATA_TicketExport] ([TicketExportId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_TicketExport2Ticket_TicketExportDetailId')
BEGIN
  ALTER TABLE DATA_TicketExport2Ticket
  ADD CONSTRAINT [FK_DATA_TicketExport2Ticket_TicketExportDetailId] FOREIGN KEY([TicketExportDetailId]) 
  REFERENCES [DATA_TicketExportDetail] ([TicketExportDetailId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_TicketExport2Ticket_TicketId')
BEGIN
  ALTER TABLE DATA_TicketExport2Ticket
  ADD CONSTRAINT [FK_DATA_TicketExport2Ticket_TicketId] FOREIGN KEY([TicketId]) 
  REFERENCES [DATA_Ticket] ([TicketId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_TicketExport2Ticket_SeatId')
BEGIN
  ALTER TABLE DATA_TicketExport2Ticket
  ADD CONSTRAINT [FK_DATA_TicketExport2Ticket_SeatId] FOREIGN KEY([SeatId]) 
  REFERENCES [CNF_Seat] ([SeatId])
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fesposito</ADDEDBY><SQLVERSION>3022</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>Adding Price, Sector and Rate</REASON><TABLENAMES>DATA_TicketExport2Ticket=TicketExport2TicketId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
           WHERE Name = N'Price' AND
           Object_ID  = Object_ID(N'DATA_TicketExport2Ticket'))
BEGIN
  ALTER TABLE DATA_TicketExport2Ticket 
  ADD Price Float NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
           WHERE Name = N'Sector' AND
           Object_ID  = Object_ID(N'DATA_TicketExport2Ticket'))
BEGIN
  ALTER TABLE DATA_TicketExport2Ticket 
  ADD Sector NVarchar(100) NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
           WHERE Name = N'Rate' AND
           Object_ID  = Object_ID(N'DATA_TicketExport2Ticket'))
BEGIN
  ALTER TABLE DATA_TicketExport2Ticket 
  ADD Rate NVarchar(100) NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fesposito</ADDEDBY><SQLVERSION>3021</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>Recreating DATA_TicketExport and DATA_TicketExport2Ticket
Creating DATA_TicketExportDetail</REASON><TABLENAMES>DATA_TicketExport=TicketExportId
DATA_TicketExportDetail=TicketExportDetailId
DATA_TicketExport2Ticket=TicketExport2TicketId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>BEGIN
 
  DECLARE @stmt VARCHAR(300);
 
  -- Cursor to generate ALTER TABLE DROP CONSTRAINT statements  
  DECLARE cur CURSOR FOR
     SELECT 'ALTER TABLE ' + OBJECT_SCHEMA_NAME(parent_object_id) + '.' + OBJECT_NAME(parent_object_id) +
                    ' DROP CONSTRAINT ' + name
     FROM sys.foreign_keys 
     WHERE OBJECT_SCHEMA_NAME(referenced_object_id) = 'dbo' AND 
                OBJECT_NAME(referenced_object_id) = 'DATA_TicketExport';
 
   OPEN cur;
   FETCH cur INTO @stmt;
 
   -- Drop each found foreign key constraint 
   WHILE @@FETCH_STATUS = 0
     BEGIN
       EXEC (@stmt);
       FETCH cur INTO @stmt;
     END
 
  CLOSE cur;
  DEALLOCATE cur;
 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS ( SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND  TABLE_NAME = 'DATA_TicketExport2Ticket' )

BEGIN
   DROP TABLE DATA_TicketExport2Ticket
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS ( SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND  TABLE_NAME = 'DATA_TicketExport' )

BEGIN
   DROP TABLE DATA_TicketExport
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                WHERE TABLE_SCHEMA = 'dbo' 
                  AND TABLE_NAME = 'DATA_TicketExport')
BEGIN
Create table [DATA_TicketExport]
(
	[TicketExportId] Integer Identity(1,1) NOT NULL,
	[CreationDate] Datetime NOT NULL,
	[PartnerCode] Nvarchar(30) NOT NULL,
	[ProcessCode] Nvarchar(50) NOT NULL,
	[PerformanceId] Integer NULL,
	[AccountId] Integer NULL,
	[Completed] Smallint NULL,
Primary Key ([TicketExportId])
) 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                WHERE TABLE_SCHEMA = 'dbo' 
                  AND TABLE_NAME = 'DATA_TicketExportDetail')
BEGIN
Create table [DATA_TicketExportDetail]
(
	[TicketExportDetailId] Integer Identity(1,1) NOT NULL,
	[TicketExportId] Integer NOT NULL,
	[Token] Nvarchar(50) NOT NULL,
	[ExportDate] Datetime NOT NULL,
	[TicketQuantity] Integer NOT NULL,
	[CompletionDate] Datetime NULL,
	[Completed] Smallint NULL,
	[Message] Nvarchar(100) NULL,
Primary Key ([TicketExportDetailId])
) 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                WHERE TABLE_SCHEMA = 'dbo' 
                  AND TABLE_NAME = 'DATA_TicketExport2Ticket')
BEGIN
Create table [DATA_TicketExport2Ticket]
(
	[TicketExport2TicketId] Integer Identity(1,1) NOT NULL,
	[TicketExportId] Integer NOT NULL,
	[TicketExportDetailId] Integer NOT NULL,
	[TicketId] Integer NOT NULL,
	[VoidType] SmallInt NOT NULL,
	[IdentifierCode] Nvarchar(50) NOT NULL,
	[SeatId] Integer NULL,
Primary Key ([TicketExport2TicketId])
) 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_TicketExport_PerformanceId')
BEGIN
  ALTER TABLE DATA_TicketExport
  ADD CONSTRAINT [FK_DATA_TicketExport_PerformanceId] FOREIGN KEY([PerformanceId]) 
  REFERENCES [CNF_Performance] ([PerformanceId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_TicketExport_AccountId')
BEGIN
  ALTER TABLE DATA_TicketExport
  ADD CONSTRAINT [FK_DATA_TicketExport_AccountId] FOREIGN KEY([AccountId]) 
  REFERENCES [DATA_Account] ([AccountId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_TicketExportDetail_TicketExportId')
BEGIN
  ALTER TABLE DATA_TicketExportDetail
  ADD CONSTRAINT [FK_DATA_TicketExportDetail_TicketExportId] FOREIGN KEY([TicketExportId]) 
  REFERENCES [DATA_TicketExport] ([TicketExportId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_TicketExport2Ticket_TicketExportId')
BEGIN
  ALTER TABLE DATA_TicketExport2Ticket
  ADD CONSTRAINT [FK_DATA_TicketExport2Ticket_TicketExportId] FOREIGN KEY([TicketExportId]) 
  REFERENCES [DATA_TicketExport] ([TicketExportId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_TicketExport2Ticket_TicketExportDetailId')
BEGIN
  ALTER TABLE DATA_TicketExport2Ticket
  ADD CONSTRAINT [FK_DATA_TicketExport2Ticket_TicketExportDetailId] FOREIGN KEY([TicketExportDetailId]) 
  REFERENCES [DATA_TicketExportDetail] ([TicketExportDetailId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_TicketExport2Ticket_TicketId')
BEGIN
  ALTER TABLE DATA_TicketExport2Ticket
  ADD CONSTRAINT [FK_DATA_TicketExport2Ticket_TicketId] FOREIGN KEY([TicketId]) 
  REFERENCES [DATA_Ticket] ([TicketId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_TicketExport2Ticket_SeatId')
BEGIN
  ALTER TABLE DATA_TicketExport2Ticket
  ADD CONSTRAINT [FK_DATA_TicketExport2Ticket_SeatId] FOREIGN KEY([SeatId]) 
  REFERENCES [CNF_Seat] ([SeatId])
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fesposito</ADDEDBY><SQLVERSION>3020</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>New fields in DATA_TicketExport </REASON><TABLENAMES>DATA_TicketExport=TicketExportId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
           WHERE Name = N'AccountId' AND
           Object_ID  = Object_ID(N'DATA_TicketExport'))
BEGIN
  ALTER TABLE DATA_TicketExport 
  ADD AccountId Integer NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
           WHERE Name = N'ExportDate' AND
           Object_ID  = Object_ID(N'DATA_TicketExport'))
BEGIN
  ALTER TABLE DATA_TicketExport 
  ADD ExportDate DateTime NOT NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_TicketExport_AccountId')
BEGIN
  ALTER TABLE DATA_TicketExport
  ADD CONSTRAINT [FK_DATA_TicketExport_AccountId] FOREIGN KEY([AccountId]) 
  REFERENCES [DATA_Account] ([AccountId])
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>3019</SQLVERSION><RMTRACKLINK>83300</RMTRACKLINK><REASON>Changed primary key on CNF_DBTable2DBGroup to include only DBTable2DBGroupId.

Added field 'GroupNames' to CNF_DBTable</REASON><TABLENAMES>CNF_DBTable2DBGroup=DBTable2DBGroupId
CNF_DBTable=DBTableId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DBTable2DBGroup_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_DBTable2DBGroup
  DROP CONSTRAINT FK_CNF_DBTable2DBGroup_Last_UserId_Log
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DBTable2DBGroup_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_DBTable2DBGroup
  DROP CONSTRAINT FK_CNF_DBTable2DBGroup_Last_WorkstationId_Log
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DBTable2DBGroup_DBTableId')
BEGIN
  ALTER TABLE CNF_DBTable2DBGroup
  DROP CONSTRAINT FK_CNF_DBTable2DBGroup_DBTableId
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DBTable2DBGroup_GroupId')
BEGIN
  ALTER TABLE CNF_DBTable2DBGroup
  DROP CONSTRAINT FK_CNF_DBTable2DBGroup_GroupId
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS ( SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND  TABLE_NAME = 'CNF_DBTable2DBGroup' )

BEGIN
   DROP TABLE CNF_DBTable2DBGroup
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                WHERE TABLE_SCHEMA = 'dbo' 
                  AND TABLE_NAME = 'CNF_DBTable2DBGroup')
BEGIN
Create table [CNF_DBTable2DBGroup]
(
	[DBTable2DBGroupId] Integer Identity(1,1) NOT NULL,
	[DBTableId] Integer NOT NULL,
	[DBGroupId] Integer NOT NULL,
	[SystemDefined] Smallint NULL,
	[Enabled] Smallint NULL,
	[Active] Smallint NULL,
	[Last_UserId_Log] Integer NULL,
	[Last_WorkstationId_Log] Integer NULL,
	[Last_DateTime_Log] Datetime NULL,
Primary Key ([DBTable2DBGroupId])
) 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DBTable2DBGroup_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_DBTable2DBGroup
  ADD CONSTRAINT [FK_CNF_DBTable2DBGroup_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DBTable2DBGroup_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_DBTable2DBGroup
  ADD CONSTRAINT [FK_CNF_DBTable2DBGroup_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DBTable2DBGroup_DBTableId')
BEGIN
  ALTER TABLE CNF_DBTable2DBGroup 
  ADD CONSTRAINT [FK_CNF_DBTable2DBGroup_DBTableId] FOREIGN KEY([DBTableId]) 
  REFERENCES [CNF_DBTable] ([DBTableId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DBTable2DBGroup_DBGroupId')
BEGIN
  ALTER TABLE CNF_DBTable2DBGroup 
  ADD CONSTRAINT [FK_CNF_DBTable2DBGroup_DBGroupId] FOREIGN KEY([DBGroupId]) 
  REFERENCES [CNF_DBGroup] ([DBGroupId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
           WHERE Name = N'GroupNames' AND
           Object_ID  = Object_ID(N'CNF_DBTable'))
BEGIN
  ALTER TABLE CNF_DBTable 
  ADD GroupNames Nvarchar(1000) NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fesposito</ADDEDBY><SQLVERSION>3018</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>New table DATA_TicketExport and DATA_TicketExport2Ticket</REASON><TABLENAMES>DATA_TicketExport=TicketExportId
DATA_TicketExport2Ticket=TicketExport2TicketId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                WHERE TABLE_SCHEMA = 'dbo' 
                  AND TABLE_NAME = 'DATA_TicketExport')
BEGIN
Create table [DATA_TicketExport]
(
	[TicketExportId] Integer Identity(1,1) NOT NULL,
	[PartnerCode] Nvarchar(30) NOT NULL,
	[ProcessCode] Nvarchar(50) NOT NULL,
	[Token] Nvarchar(100) NOT NULL,
	[PerformanceId] Integer NULL,
	[TicketQuantity] Integer NULL,
	[HasMore] Smallint NULL,
	[Completed] Smallint NULL,
	[Message] Nvarchar(100) NULL,
Primary Key ([TicketExportId])
) 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                WHERE TABLE_SCHEMA = 'dbo' 
                  AND TABLE_NAME = 'DATA_TicketExport2Ticket')
BEGIN
Create table [DATA_TicketExport2Ticket]
(
	[TicketExport2TicketId] Integer Identity(1,1) NOT NULL,
	[TicketExportId] Integer NOT NULL,
	[TicketId] Integer NOT NULL,
	[VoidType] SmallInt NOT NULL,
Primary Key ([TicketExport2TicketId])
) 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_TicketExport2Ticket_TicketExportId')
BEGIN
  ALTER TABLE DATA_TicketExport2Ticket
  ADD CONSTRAINT [FK_DATA_TicketExport2Ticket_TicketExportId] FOREIGN KEY([TicketExportId]) 
  REFERENCES [DATA_TicketExport] ([TicketExportId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_TicketExport2Ticket_TicketId')
BEGIN
  ALTER TABLE DATA_TicketExport2Ticket
  ADD CONSTRAINT [FK_DATA_TicketExport2Ticket_TicketId] FOREIGN KEY([TicketId]) 
  REFERENCES [DATA_Ticket] ([TicketId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_TicketExport_CNF_PerformanceId')
BEGIN
  ALTER TABLE DATA_TicketExport
  ADD CONSTRAINT [FK_DATA_TicketExport_CNF_PerformanceId] FOREIGN KEY([PerformanceId]) 
  REFERENCES [CNF_Performance] ([PerformanceId])
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>3017</SQLVERSION><RMTRACKLINK>83300</RMTRACKLINK><REASON>Changed field Code to Nvarchar(50)</REASON><TABLENAMES>CNF_DBTable=DBTableId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
           WHERE Name = N'Code' AND
           Object_ID  = Object_ID(N'CNF_DBGroup'))
BEGIN
  ALTER TABLE CNF_DBGroup 
  ALTER COLUMN Code Nvarchar(50) Null;
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>3016</SQLVERSION><RMTRACKLINK>83300</RMTRACKLINK><REASON>Need this patch to remove 'TableObjectId' parameter from insert/update procedures of CNF_DBTable</REASON><TABLENAMES>CNF_DBTable=DBTableId</TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>3015</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>Added indexes on several tables
[0..15] Indexes creation</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (    SELECT object_id
        FROM sys.indexes
        WHERE Name = 'Idx_RES_DATA_Transaction_PerformanceId')
BEGIN
  CREATE NONCLUSTERED INDEX [Idx_RES_DATA_Transaction_PerformanceId]
  ON [dbo].[RES_DATA_Transaction] ([PerformanceId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (    SELECT object_id
        FROM sys.indexes
        WHERE Name = 'Idx_DATA_Sale_PerformanceId')
BEGIN
  CREATE NONCLUSTERED INDEX [Idx_DATA_Sale_PerformanceId]
  ON [dbo].[DATA_Sale] ([PerformanceId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (    SELECT object_id
        FROM sys.indexes
        WHERE Name = 'Idx_DATA_TicketStatus_PerformanceId')
BEGIN
  CREATE NONCLUSTERED INDEX [Idx_DATA_TicketStatus_PerformanceId]
  ON [dbo].[DATA_TicketStatus] ([PerformanceId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (    SELECT object_id
        FROM sys.indexes
        WHERE Name = 'Idx_DM_PerformanceId')
BEGIN
  CREATE NONCLUSTERED INDEX [Idx_DM_PerformanceId]
  ON [dbo].[DATA_Media] ([PerformanceId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (    SELECT object_id
        FROM sys.indexes
        WHERE Name = 'Idx_DATA_M2P_PerformanceId')
BEGIN
  CREATE NONCLUSTERED INDEX [Idx_DATA_M2P_PerformanceId]
  ON [dbo].[DATA_Media2Performances] ([PerformanceId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (    SELECT object_id
        FROM sys.indexes
        WHERE Name = 'Idx_CNF_Sub2Perf_PerformanceId')
BEGIN
  CREATE NONCLUSTERED INDEX [Idx_CNF_Sub2Perf_PerformanceId]
  ON [dbo].[CNF_Subscription2Performance] ([PerformanceId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (    SELECT object_id
        FROM sys.indexes
        WHERE Name = 'Idx_CNF_PerformancePermission_PerfId')
BEGIN
  CREATE NONCLUSTERED INDEX [Idx_CNF_PerformancePermission_PerfId]
  ON [dbo].[CNF_Performance_Permission] ([PerformanceId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (    SELECT object_id
        FROM sys.indexes
        WHERE Name = 'Idx_CNF_PerfSaleVal_PerfId')
BEGIN
  CREATE NONCLUSTERED INDEX [Idx_CNF_PerfSaleVal_PerfId]
  ON [dbo].[CNF_Performance_SaleValidity] ([PerformanceId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (    SELECT object_id
        FROM sys.indexes
        WHERE Name = 'Idx_CNF_PerformanceCatVal_PerfId')
BEGIN
  CREATE NONCLUSTERED INDEX [Idx_CNF_PerformanceCatVal_PerfId]
  ON [dbo].[CNF_PerformanceCategoryValidity] ([PerformanceId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (    SELECT object_id
        FROM sys.indexes
        WHERE Name = 'Idx_CNF_PerformanceCatVal_Category')
BEGIN
  CREATE NONCLUSTERED INDEX [Idx_CNF_PerformanceCatVal_Category]
  ON [dbo].[CNF_PerformanceCategoryValidity] ([PerformanceCategoryId] ,[EventId] ,[PerformanceId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (    SELECT object_id
        FROM sys.indexes
        WHERE Name = 'Idx_CNF_PerformanceFilter_PerfId')
BEGIN
  CREATE NONCLUSTERED INDEX [Idx_CNF_PerformanceFilter_PerfId]
  ON [dbo].[CNF_PerformanceFilter] ([PerformanceId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (    SELECT object_id
        FROM sys.indexes
        WHERE Name = 'Idx_CNF_AlternativeCodes_PerformanceId')
BEGIN
  CREATE NONCLUSTERED INDEX [Idx_CNF_AlternativeCodes_PerformanceId]
  ON [dbo].[CNF_AlternativeCodes] ([PerformanceId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (    SELECT object_id
        FROM sys.indexes
        WHERE Name = 'Idx_CNF_AlternativeCodes_MatrixCellId')
BEGIN
  CREATE NONCLUSTERED INDEX [Idx_CNF_AlternativeCodes_MatrixCellId]
  ON [dbo].[CNF_AlternativeCodes] ([MatrixCellId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (    SELECT object_id
        FROM sys.indexes
        WHERE Name = 'Idx_CNF_AlternativeCodes_EventId')
BEGIN
  CREATE NONCLUSTERED INDEX [Idx_CNF_AlternativeCodes_EventId]
  ON [dbo].[CNF_AlternativeCodes] ([EventId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (    SELECT object_id
        FROM sys.indexes
        WHERE Name = 'Idx_CNF_AlternativeCodes_AccountId')
BEGIN
  CREATE NONCLUSTERED INDEX [Idx_CNF_AlternativeCodes_AccountId]
  ON [dbo].[CNF_AlternativeCodes] ([AccountId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (    SELECT object_id
        FROM sys.indexes
        WHERE Name = 'Idx_CNF_AlternativeCodes_Code')
BEGIN
  CREATE NONCLUSTERED INDEX [Idx_CNF_AlternativeCodes_Code]
  ON [dbo].[CNF_AlternativeCodes] ([MatrixCellId] ,[EventId] ,[AccountId] ,[PerformanceId] ,[Code])
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fdipalma</ADDEDBY><SQLVERSION>3014</SQLVERSION><RMTRACKLINK>IDBOS-1118</RMTRACKLINK><REASON>Added field PointsEmailSent in the DATA_Account</REASON><TABLENAMES>DATA_Account=AccountId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
WHERE Name = N'PointsEmailSent' AND OBJECT_ID = OBJECT_ID(N'DATA_Account'))
BEGIN
  ALTER TABLE DATA_Account ADD PointsEmailSent int Default 0 NOT NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>3013</SQLVERSION><RMTRACKLINK>83300</RMTRACKLINK><REASON>Added new column to CNF_DBGroup: Code</REASON><TABLENAMES>CNF_DBGroup=DBGroupId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
           WHERE Name = N'Code' AND
           Object_ID  = Object_ID(N'CNF_DBGroup'))
BEGIN
  ALTER TABLE CNF_DBGroup 
  ADD Code Nvarchar(10) NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>3012</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>Adding indexes to the DATA_SaleLimit</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (	SELECT object_id 
		FROM sys.indexes
		WHERE Name = 'Idx_DATA_SaleLimit_PerformanceId')
BEGIN
  CREATE NONCLUSTERED INDEX [Idx_DATA_SaleLimit_PerformanceId]
  ON [dbo].[DATA_SaleLimit] ([PerformanceId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (	SELECT object_id 
		FROM sys.indexes
		WHERE Name = 'Idx_DATA_SaleLimit_AccountId')
BEGIN
  CREATE NONCLUSTERED INDEX [Idx_DATA_SaleLimit_AccountId]
  ON [dbo].[DATA_SaleLimit] ([AccountId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (	SELECT object_id 
		FROM sys.indexes
		WHERE Name = 'Idx_DATA_SaleLimit_SaleRestrictionId')
BEGIN
  CREATE NONCLUSTERED INDEX [Idx_DATA_SaleLimit_SaleRestrictionId]
  ON [dbo].[DATA_SaleLimit] ([SaleRestrictionId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (	SELECT object_id 
		FROM sys.indexes
		WHERE Name = 'Idx_DATA_SaleLimit_SaleId')
BEGIN
  CREATE NONCLUSTERED INDEX [Idx_DATA_SaleLimit_SaleId]
  ON [dbo].[DATA_SaleLimit] ([SaleId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (	SELECT object_id 
		FROM sys.indexes
		WHERE Name = 'Idx_DATA_SaleLimit_AccPerfSaleId')
BEGIN
  CREATE NONCLUSTERED INDEX [Idx_DATA_SaleLimit_AccPerfSaleId]
  ON [dbo].[DATA_SaleLimit] ([AccountId] ,[PerformanceId] ,[SaleRestrictionId] ,[SaleId])
END
</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>3011</SQLVERSION><RMTRACKLINK>86177</RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.objects WHERE [name] = N'data_sale_SalesRestriction' AND [type] = 'TR')
BEGIN
      DROP TRIGGER [dbo].[data_sale_SalesRestriction];
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>Create trigger [dbo].[data_sale_SalesRestriction] on [dbo].[DATA_Sale] FOR update
	 as
begin
	SET NOCOUNT ON;
    IF UPDATE(Approved) or Update(StatusCode)
    BEGIN

		Declare @Temp table (	AccountID int, 
								SaleID int,
								SaleItemID int,
								PerformanceID int,
								Quantity int,
								SalesDate DateTime,
								MatrixCellID int,
								RestrictionType int
							)

		DECLARE @INS_SaleID int
		DECLARE @status int = 0 
		DECLARE @DR_status int

		DECLARE	@ReservationAccountID int
		DECLARE	@B2BAccountID int  
		DECLARE	@TicketAccountID int
		DECLARE	@SaleID int
		DECLARE	@SaleItemID int
		DECLARE	@PerformanceID int
		DECLARE	@Quantity int
		DECLARE @MatrixCellID int
		DECLARE @EventID int

		DECLARE @RestrictionType int	
			
		DECLARE @ReservationAccountOwner int = 1
		DECLARE @TicketAccountOwner int = 2
		DECLARE @CheckforRestraintOnly int = 0

		SELECT @status=i.Approved, @INS_SaleID = i.Saleid 
				FROM inserted i
				JOIN deleted d
					ON i.SaleID = d.SaleID
					AND i.Approved &lt;&gt; d.Approved

		if @status = 0 
		begin
			SELECT @DR_status = CASE WHEN i.StatusCode = 2 then  1
			            else 0
					end, 
			       @INS_SaleID = i.Saleid 
					FROM inserted i
					JOIN deleted d
						ON i.[SaleID] = d.[SaleID]
						AND i.[StatusCode] &lt;&gt; d.[StatusCode]
		end


		if @status = 1
		begin
			DECLARE SaleItem_Cursor CURSOR LOCAL FOR
					select  ISNULL(data_reservation.accountid, ODR.AccountID) as AccountID,
						    ISNULL(data_reservation.B2bAccountID, ODR.B2bAccountID) as B2bAccountID,
							data_saleitem.Matrixcellid,
							case when data_saleitem2account.Accountid is not null then case when data_saleitem.Quantity &lt; 0 then -1 else 1 end
									else data_saleitem.Quantity
								end Quantity,
							data_saleitem2account.Accountid,
							data_sale.saleid,
							data_saleitem.saleitemid

					from data_sale WITH(NOLOCK)
						LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
						INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
						LEFT  JOIN data_saleitem2account WITH(NOLOCK)				on data_saleitem2account.SaleitemID = data_saleitem.saleitemid
						left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
						left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

					Where data_sale.saleid = @INS_SaleID
										
			OPEN SaleItem_Cursor

				FETCH NEXT FROM SaleItem_Cursor INTO
									@ReservationAccountID, 
									@B2BAccountID,
									@MatrixCellID,
									@Quantity,
									@TicketAccountID,
									@SaleID,
									@SaleItemID

				WHILE @@FETCH_STATUS = 0
				BEGIN

					--   Ticket Test   with Ticket Owner				@TicketAccountOwner              --@RestrictionType = 1	
					exec otn_sp_GetAccountRestrictions @TicketAccountID,								--AccountID
													   @MatrixCellID,									--MatrixCellID
													   null,											--PerformanceID
													   null,											--EventID
													   @Quantity,										--Quantity
													   1,												--RestrictionType
													   @SaleID,											--SaleID
													   @SaleItemID,										--SaleItemID
													   0,												--CheckforRestrictionOnly
													   @TicketAccountOwner								--ReservationorTicketAccount		

				
					--   Ticket Test   with Reservation Owner			@ReservationAccountOwner         --@RestrictionType = 1
					exec otn_sp_GetAccountRestrictions @B2BAccountID,							--AccountID
													   @MatrixCellID,									--MatrixCellID
													   null,											--PerformanceID
													   null,											--EventID
													   @Quantity,										--Quantity
													   1,												--RestrictionType
													   @SaleID,											--SaleID
													   @SaleItemID,										--SaleItemID
													   0,												--CheckforRestrictionOnly
													   @ReservationAccountOwner							--ReservationorTicketAccount	

                    --   Ticket Test   with Reservation Owner			@ReservationAccountOwner         --@RestrictionType = 1
					exec otn_sp_GetAccountRestrictions @ReservationAccountID,							--AccountID
													   @MatrixCellID,									--MatrixCellID
													   null,											--PerformanceID
													   null,											--EventID
													   @Quantity,										--Quantity
													   1,												--RestrictionType
													   @SaleID,											--SaleID
													   @SaleItemID,										--SaleItemID
													   0,												--CheckforRestrictionOnly
													   @ReservationAccountOwner							--ReservationorTicketAccount	

					DECLARE Performance_Cursor CURSOR LOCAL FOR
						  select data_saleitem2Performance.PerformanceID,
						         cnf_Performance.eventid

							from data_saleitem2Performance WITH(NOLOCK)																					   
								LEFT  JOIN cnf_Performance WITH(NOLOCK)						on cnf_Performance.PerformanceID = data_saleitem2Performance.PerformanceID
						
							Where Active = 1
							  and data_saleitem2Performance.Saleitemid = @SaleItemID

					OPEN Performance_Cursor

						FETCH NEXT FROM Performance_Cursor INTO
											@PerformanceID,
											@EventID

						WHILE @@FETCH_STATUS = 0
						BEGIN
								--	Perforamnce Test     with Ticket Owner			@TicketAccountOwner              --@RestrictionType = 2
								exec otn_sp_GetAccountRestrictions @TicketAccountID,								--AccountID
																   @MatrixCellID,									--MatrixCellID
																   @PerformanceID,									--PerformanceID
																   @EventID,										--EventID
																   @Quantity,										--Quantity
																   2,												--RestrictionType
																   @SaleID,											--SaleID
																   @SaleItemID,										--SaleItemID
																   0,												--CheckforRestrictionOnly
																   @TicketAccountOwner								--ReservationorTicketAccount	

								--   Performance Test     with Reservation Owner    @TicketAccountOwner              --@RestrictionType = 2
								exec otn_sp_GetAccountRestrictions @ReservationAccountID,							--AccountID
																   @MatrixCellID,									--MatrixCellID
																   @PerformanceID,									--PerformanceID
																   @EventID,										--EventID
																   @Quantity,										--Quantity
																   2,												--RestrictionType
																   @SaleID,											--SaleID
																   @SaleItemID,										--SaleItemID
																   0,												--CheckforRestrictionOnly
																   @ReservationAccountOwner								--ReservationorTicketAccount	


						FETCH NEXT FROM Performance_Cursor INTO
											@PerformanceID,
											@EventID
				END
				CLOSE Performance_Cursor;
				DEALLOCATE Performance_Cursor;
				FETCH NEXT FROM SaleItem_Cursor INTO
									@ReservationAccountID, 
									@B2BAccountID,
									@MatrixCellID,
									@Quantity,
									@TicketAccountID,
									@SaleID,
									@SaleItemID
			end
			CLOSE SaleItem_Cursor;
			DEALLOCATE SaleItem_Cursor;
		END

		if @DR_status = 1
		begin
			DECLARE SaleItem_Cursor CURSOR LOCAL FOR
					select data_reservation.accountid, 
						   data_reservation.B2bAccountID,
						   data_saleitem.Matrixcellid,
							case when data_saleitem2account.Accountid is not null then -1
								 else data_saleitem.Quantity
							 end Quantity,
						   data_saleitem2account.Accountid,
						   data_sale.saleid,
						   data_saleitem.saleitemid

					from data_sale WITH(NOLOCK)
						LEFT JOIN data_reservation WITH(NOLOCK)					on data_reservation.saleid = data_sale.saleid
						INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
						LEFT  JOIN data_saleitem2account WITH(NOLOCK)				on data_saleitem2account.SaleitemID = data_saleitem.saleitemid

					Where data_sale.saleid = @INS_SaleID
					  and data_saleitem.quantity &lt; 0 
					
			OPEN SaleItem_Cursor

			FETCH NEXT FROM SaleItem_Cursor INTO
								@ReservationAccountID, 
								@B2BAccountID,
								@MatrixCellID,
								@Quantity,
								@TicketAccountID,
								@SaleID,
								@SaleItemID

			WHILE @@FETCH_STATUS = 0
			BEGIN

				--   Ticket Test   with Ticket Owner				@TicketAccountOwner              --@RestrictionType = 1	
				exec otn_sp_GetAccountRestrictions @TicketAccountID,								--AccountID
				                                   @MatrixCellID,									--MatrixCellID
												   null,											--PerformanceID
												   null,											--EventID
												   @Quantity,										--Quantity
												   1,												--RestrictionType
												   @SaleID,											--SaleID
												   @SaleItemID,										--SaleItemID
												   0,												--CheckforRestrictionOnly
												   @TicketAccountOwner								--ReservationorTicketAccount		

				
				--   Ticket Test   with Reservation Owner			@ReservationAccountOwner         --@RestrictionType = 1
				exec otn_sp_GetAccountRestrictions @B2BAccountID,							        --AccountID
				                                   @MatrixCellID,									--MatrixCellID
												   null,											--PerformanceID
												   null,											--EventID
												   @Quantity,										--Quantity
												   1,												--RestrictionType
												   @SaleID,											--SaleID
												   @SaleItemID,										--SaleItemID
												   0,												--CheckforRestrictionOnly
												   @ReservationAccountOwner							--ReservationorTicketAccount
												   
				--   Ticket Test   with Reservation Owner			@ReservationAccountOwner         --@RestrictionType = 1
				exec otn_sp_GetAccountRestrictions @ReservationAccountID,							--AccountID
				                                   @MatrixCellID,									--MatrixCellID
												   null,											--PerformanceID
												   null,											--EventID
												   @Quantity,										--Quantity
												   1,												--RestrictionType
												   @SaleID,											--SaleID
												   @SaleItemID,										--SaleItemID
												   0,												--CheckforRestrictionOnly
												   @ReservationAccountOwner							--ReservationorTicketAccount													   	

			DECLARE Performance_Cursor CURSOR LOCAL FOR
						  select data_saleitem2Performance.PerformanceID,
						         cnf_Performance.eventid

							from data_saleitem2Performance WITH(NOLOCK)																					   
								LEFT  JOIN cnf_Performance WITH(NOLOCK)						on cnf_Performance.PerformanceID = data_saleitem2Performance.PerformanceID
						
							Where Active = 1
							  and data_saleitem2Performance.Saleitemid = @SaleItemID

					OPEN Performance_Cursor

						FETCH NEXT FROM Performance_Cursor INTO
											@PerformanceID,
											@EventID

						WHILE @@FETCH_STATUS = 0
						BEGIN
								--	Perforamnce Test     with Ticket Owner			@TicketAccountOwner              --@RestrictionType = 2
								exec otn_sp_GetAccountRestrictions @TicketAccountID,								--AccountID
																   @MatrixCellID,									--MatrixCellID
																   @PerformanceID,									--PerformanceID
																   @EventID,										--EventID
																   @Quantity,										--Quantity
																   2,												--RestrictionType
																   @SaleID,											--SaleID
																   @SaleItemID,										--SaleItemID
																   0,												--CheckforRestrictionOnly
																   @TicketAccountOwner								--ReservationorTicketAccount	

								--   Performance Test     with Reservation Owner    @TicketAccountOwner              --@RestrictionType = 2
								exec otn_sp_GetAccountRestrictions @ReservationAccountID,							--AccountID
																   @MatrixCellID,									--MatrixCellID
																   @PerformanceID,									--PerformanceID
																   @EventID,										--EventID
																   @Quantity,										--Quantity
																   2,												--RestrictionType
																   @SaleID,											--SaleID
																   @SaleItemID,										--SaleItemID
																   0,												--CheckforRestrictionOnly
																   @ReservationAccountOwner								--ReservationorTicketAccount	
						FETCH NEXT FROM Performance_Cursor INTO
											@PerformanceID,
											@EventID
				END
				CLOSE Performance_Cursor;
				DEALLOCATE Performance_Cursor;

				FETCH NEXT FROM SaleItem_Cursor INTO
								@ReservationAccountID, 
								@B2BAccountID,
								@MatrixCellID,
								@Quantity,
								@TicketAccountID,
								@SaleID,
								@SaleItemID

			end
			CLOSE SaleItem_Cursor;
			DEALLOCATE SaleItem_Cursor;
		end
	end
end</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>3010</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.objects WHERE [name] = N'data_sale_SalesRestriction' AND [type] = 'TR')
BEGIN
      DROP TRIGGER [dbo].[data_sale_SalesRestriction];
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>
Create trigger [dbo].[data_sale_SalesRestriction] on [dbo].[DATA_Sale] FOR update
	 as
begin
	SET NOCOUNT ON;
    IF UPDATE(Paid) or Update(StatusCode)
    BEGIN

		Declare @Temp table (	AccountID int, 
								SaleID int,
								SaleItemID int,
								PerformanceID int,
								Quantity int,
								SalesDate DateTime,
								MatrixCellID int,
								RestrictionType int
							)

		DECLARE @INS_SaleID int
		DECLARE @status int = 0 
		DECLARE @DR_status int

		DECLARE	@ReservationAccountID int
		DECLARE	@B2BAccountID int  
		DECLARE	@TicketAccountID int
		DECLARE	@SaleID int
		DECLARE	@SaleItemID int
		DECLARE	@PerformanceID int
		DECLARE	@Quantity int
		DECLARE @MatrixCellID int
		DECLARE @EventID int

		DECLARE @RestrictionType int	
			
		DECLARE @ReservationAccountOwner int = 1
		DECLARE @TicketAccountOwner int = 2
		DECLARE @CheckforRestraintOnly int = 0

		SELECT @status=i.Paid, @INS_SaleID = i.Saleid 
				FROM inserted i
				JOIN deleted d
					ON i.[SaleID] = d.[SaleID]
					AND i.[Paid] &lt;&gt; d.[Paid]

		if @status = 0 
		begin
			SELECT @DR_status = CASE WHEN i.StatusCode = 2 then  1
			            else 0
					end, 
			       @INS_SaleID = i.Saleid 
					FROM inserted i
					JOIN deleted d
						ON i.[SaleID] = d.[SaleID]
						AND i.[StatusCode] &lt;&gt; d.[StatusCode]
		end


		if @status = 1
		begin
			DECLARE SaleItem_Cursor CURSOR LOCAL FOR
					select ISNULL(data_reservation.accountid, ODR.AccountID) as AccountID,
						   ISNULL(data_reservation.B2bAccountID, ODR.B2bAccountID) as B2bAccountID,
							data_saleitem.Matrixcellid,
							data_saleitem.Quantity,
							data_saleitem2account.Accountid,
							data_sale.saleid,
							data_saleitem.saleitemid

					from data_sale WITH(NOLOCK)
						LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
						INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
						LEFT  JOIN data_saleitem2account WITH(NOLOCK)				on data_saleitem2account.SaleitemID = data_saleitem.saleitemid
						left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
						left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

					Where data_sale.saleid = @INS_SaleID
										
			OPEN SaleItem_Cursor

				FETCH NEXT FROM SaleItem_Cursor INTO
									@ReservationAccountID, 
									@B2BAccountID,
									@MatrixCellID,
									@Quantity,
									@TicketAccountID,
									@SaleID,
									@SaleItemID

				WHILE @@FETCH_STATUS = 0
				BEGIN

					--   Ticket Test   with Ticket Owner				@TicketAccountOwner              --@RestrictionType = 1	
					exec otn_sp_GetAccountRestrictions @TicketAccountID,								--AccountID
													   @MatrixCellID,									--MatrixCellID
													   null,											--PerformanceID
													   null,											--EventID
													   @Quantity,										--Quantity
													   1,												--RestrictionType
													   @SaleID,											--SaleID
													   @SaleItemID,										--SaleItemID
													   0,												--CheckforRestrictionOnly
													   @TicketAccountOwner								--ReservationorTicketAccount		

				
					--   Ticket Test   with Reservation Owner			@ReservationAccountOwner         --@RestrictionType = 1
					exec otn_sp_GetAccountRestrictions @B2BAccountID,							--AccountID
													   @MatrixCellID,									--MatrixCellID
													   null,											--PerformanceID
													   null,											--EventID
													   @Quantity,										--Quantity
													   1,												--RestrictionType
													   @SaleID,											--SaleID
													   @SaleItemID,										--SaleItemID
													   0,												--CheckforRestrictionOnly
													   @ReservationAccountOwner							--ReservationorTicketAccount	

                    --   Ticket Test   with Reservation Owner			@ReservationAccountOwner         --@RestrictionType = 1
					exec otn_sp_GetAccountRestrictions @ReservationAccountID,							--AccountID
													   @MatrixCellID,									--MatrixCellID
													   null,											--PerformanceID
													   null,											--EventID
													   @Quantity,										--Quantity
													   1,												--RestrictionType
													   @SaleID,											--SaleID
													   @SaleItemID,										--SaleItemID
													   0,												--CheckforRestrictionOnly
													   @ReservationAccountOwner							--ReservationorTicketAccount	

					DECLARE Performance_Cursor CURSOR LOCAL FOR
						  select data_saleitem2Performance.PerformanceID,
						         cnf_Performance.eventid

							from data_saleitem2Performance WITH(NOLOCK)																					   
								LEFT  JOIN cnf_Performance WITH(NOLOCK)						on cnf_Performance.PerformanceID = data_saleitem2Performance.PerformanceID
						
							Where Active = 1
							  and data_saleitem2Performance.Saleitemid = @SaleItemID

					OPEN Performance_Cursor

						FETCH NEXT FROM Performance_Cursor INTO
											@PerformanceID,
											@EventID

						WHILE @@FETCH_STATUS = 0
						BEGIN
								--	Perforamnce Test     with Ticket Owner			@TicketAccountOwner              --@RestrictionType = 2
								exec otn_sp_GetAccountRestrictions @TicketAccountID,								--AccountID
																   @MatrixCellID,									--MatrixCellID
																   @PerformanceID,									--PerformanceID
																   @EventID,										--EventID
																   @Quantity,										--Quantity
																   2,												--RestrictionType
																   @SaleID,											--SaleID
																   @SaleItemID,										--SaleItemID
																   0,												--CheckforRestrictionOnly
																   @TicketAccountOwner								--ReservationorTicketAccount	

								--   Performance Test     with Reservation Owner    @TicketAccountOwner              --@RestrictionType = 2
								exec otn_sp_GetAccountRestrictions @ReservationAccountID,							--AccountID
																   @MatrixCellID,									--MatrixCellID
																   @PerformanceID,									--PerformanceID
																   @EventID,										--EventID
																   @Quantity,										--Quantity
																   2,												--RestrictionType
																   @SaleID,											--SaleID
																   @SaleItemID,										--SaleItemID
																   0,												--CheckforRestrictionOnly
																   @ReservationAccountOwner								--ReservationorTicketAccount	


						FETCH NEXT FROM Performance_Cursor INTO
											@PerformanceID,
											@EventID
				END
				CLOSE Performance_Cursor;
				DEALLOCATE Performance_Cursor;
				FETCH NEXT FROM SaleItem_Cursor INTO
									@ReservationAccountID, 
									@B2BAccountID,
									@MatrixCellID,
									@Quantity,
									@TicketAccountID,
									@SaleID,
									@SaleItemID
			end
			CLOSE SaleItem_Cursor;
			DEALLOCATE SaleItem_Cursor;
		END

		if @DR_status = 1
		begin
			DECLARE SaleItem_Cursor CURSOR LOCAL FOR
					select data_reservation.accountid, 
						   data_reservation.B2bAccountID,
						   data_saleitem.Matrixcellid,
						   data_saleitem.Quantity,
						   data_saleitem2account.Accountid,
						   data_sale.saleid,
						   data_saleitem.saleitemid

					from data_sale WITH(NOLOCK)
						LEFT JOIN data_reservation WITH(NOLOCK)					on data_reservation.saleid = data_sale.saleid
						INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
						LEFT  JOIN data_saleitem2account WITH(NOLOCK)				on data_saleitem2account.SaleitemID = data_saleitem.saleitemid

					Where data_sale.saleid = @INS_SaleID
					  and data_saleitem.quantity &lt; 0 
					
			OPEN SaleItem_Cursor

			FETCH NEXT FROM SaleItem_Cursor INTO
								@ReservationAccountID, 
								@B2BAccountID,
								@MatrixCellID,
								@Quantity,
								@TicketAccountID,
								@SaleID,
								@SaleItemID

			WHILE @@FETCH_STATUS = 0
			BEGIN

				--   Ticket Test   with Ticket Owner				@TicketAccountOwner              --@RestrictionType = 1	
				exec otn_sp_GetAccountRestrictions @TicketAccountID,								--AccountID
				                                   @MatrixCellID,									--MatrixCellID
												   null,											--PerformanceID
												   null,											--EventID
												   @Quantity,										--Quantity
												   1,												--RestrictionType
												   @SaleID,											--SaleID
												   @SaleItemID,										--SaleItemID
												   0,												--CheckforRestrictionOnly
												   @TicketAccountOwner								--ReservationorTicketAccount		

				
				--   Ticket Test   with Reservation Owner			@ReservationAccountOwner         --@RestrictionType = 1
				exec otn_sp_GetAccountRestrictions @B2BAccountID,							        --AccountID
				                                   @MatrixCellID,									--MatrixCellID
												   null,											--PerformanceID
												   null,											--EventID
												   @Quantity,										--Quantity
												   1,												--RestrictionType
												   @SaleID,											--SaleID
												   @SaleItemID,										--SaleItemID
												   0,												--CheckforRestrictionOnly
												   @ReservationAccountOwner							--ReservationorTicketAccount
												   
				--   Ticket Test   with Reservation Owner			@ReservationAccountOwner         --@RestrictionType = 1
				exec otn_sp_GetAccountRestrictions @ReservationAccountID,							--AccountID
				                                   @MatrixCellID,									--MatrixCellID
												   null,											--PerformanceID
												   null,											--EventID
												   @Quantity,										--Quantity
												   1,												--RestrictionType
												   @SaleID,											--SaleID
												   @SaleItemID,										--SaleItemID
												   0,												--CheckforRestrictionOnly
												   @ReservationAccountOwner							--ReservationorTicketAccount													   	

			DECLARE Performance_Cursor CURSOR LOCAL FOR
						  select data_saleitem2Performance.PerformanceID,
						         cnf_Performance.eventid

							from data_saleitem2Performance WITH(NOLOCK)																					   
								LEFT  JOIN cnf_Performance WITH(NOLOCK)						on cnf_Performance.PerformanceID = data_saleitem2Performance.PerformanceID
						
							Where Active = 1
							  and data_saleitem2Performance.Saleitemid = @SaleItemID

					OPEN Performance_Cursor

						FETCH NEXT FROM Performance_Cursor INTO
											@PerformanceID,
											@EventID

						WHILE @@FETCH_STATUS = 0
						BEGIN
								--	Perforamnce Test     with Ticket Owner			@TicketAccountOwner              --@RestrictionType = 2
								exec otn_sp_GetAccountRestrictions @TicketAccountID,								--AccountID
																   @MatrixCellID,									--MatrixCellID
																   @PerformanceID,									--PerformanceID
																   @EventID,										--EventID
																   @Quantity,										--Quantity
																   2,												--RestrictionType
																   @SaleID,											--SaleID
																   @SaleItemID,										--SaleItemID
																   0,												--CheckforRestrictionOnly
																   @TicketAccountOwner								--ReservationorTicketAccount	

								--   Performance Test     with Reservation Owner    @TicketAccountOwner              --@RestrictionType = 2
								exec otn_sp_GetAccountRestrictions @ReservationAccountID,							--AccountID
																   @MatrixCellID,									--MatrixCellID
																   @PerformanceID,									--PerformanceID
																   @EventID,										--EventID
																   @Quantity,										--Quantity
																   2,												--RestrictionType
																   @SaleID,											--SaleID
																   @SaleItemID,										--SaleItemID
																   0,												--CheckforRestrictionOnly
																   @ReservationAccountOwner								--ReservationorTicketAccount	
						FETCH NEXT FROM Performance_Cursor INTO
											@PerformanceID,
											@EventID
				END
				CLOSE Performance_Cursor;
				DEALLOCATE Performance_Cursor;

				FETCH NEXT FROM SaleItem_Cursor INTO
								@ReservationAccountID, 
								@B2BAccountID,
								@MatrixCellID,
								@Quantity,
								@TicketAccountID,
								@SaleID,
								@SaleItemID

			end
			CLOSE SaleItem_Cursor;
			DEALLOCATE SaleItem_Cursor;
		end
	end
end</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>3009</SQLVERSION><RMTRACKLINK>83300</RMTRACKLINK><REASON>Reverted patch #3007
Added 2 new tables: CNF_DBGroup and CNF_DBTable2DBGroup</REASON><TABLENAMES>CNF_DBGroup=DBGroupId
CNF_DBTable2DBGroup=DBTable2DBGroupId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_HL_Group_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_HL_Group
  DROP CONSTRAINT FK_CNF_HL_Group_Last_UserId_Log
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_HL_Group_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_HL_Group
  DROP CONSTRAINT FK_CNF_HL_Group_Last_WorkstationId_Log
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DBTable2Group_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_DBTable2Group
  DROP CONSTRAINT FK_CNF_DBTable2Group_Last_UserId_Log
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DBTable2Group_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_DBTable2Group
  DROP CONSTRAINT FK_CNF_DBTable2Group_Last_WorkstationId_Log
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DBTable2Group_DBTableId')
BEGIN
  ALTER TABLE CNF_DBTable2Group
  DROP CONSTRAINT FK_CNF_DBTable2Group_DBTableId
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DBTable2Group_GroupId')
BEGIN
  ALTER TABLE CNF_DBTable2Group
  DROP CONSTRAINT FK_CNF_DBTable2Group_GroupId
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS ( SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND  TABLE_NAME = 'CNF_HL_Group' )

BEGIN
   DROP TABLE CNF_HL_Group
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS ( SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND  TABLE_NAME = 'CNF_DBTable2Group' )

BEGIN
   DROP TABLE CNF_DBTable2Group
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'TableObjectId' AND
                Object_ID  = Object_ID(N'CNF_DBTable'))
BEGIN
  ALTER TABLE CNF_DBTable
  DROP COLUMN TableObjectId
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                WHERE TABLE_SCHEMA = 'dbo' 
                  AND TABLE_NAME = 'CNF_DBGroup')
BEGIN
Create table [CNF_DBGroup]
(
	[DBGroupId] Integer Identity(1,1) NOT NULL,
	[SubModelId] Integer NULL,
	[Name] Nvarchar(100) NULL,
	[SystemDefined] Smallint NULL,
	[Enabled] Smallint NULL,
	[Active] Smallint NULL,
	[Last_UserId_Log] Integer NULL,
	[Last_WorkstationId_Log] Integer NULL,
	[Last_DateTime_Log] Datetime NULL,
Primary Key ([DBGroupId])
) 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                WHERE TABLE_SCHEMA = 'dbo' 
                  AND TABLE_NAME = 'CNF_DBTable2DBGroup')
BEGIN
Create table [CNF_DBTable2DBGroup]
(
	[DBTable2DBGroupId] Integer Identity(1,1) NOT NULL,
	[DBTableId] Integer NOT NULL,
	[DBGroupId] Integer NOT NULL,
	[SystemDefined] Smallint NULL,
	[Enabled] Smallint NULL,
	[Active] Smallint NULL,
	[Last_UserId_Log] Integer NULL,
	[Last_WorkstationId_Log] Integer NULL,
	[Last_DateTime_Log] Datetime NULL,
Primary Key ([DBTable2DBGroupId],[DBTableId],[DBGroupId])
) 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DBGroup_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_DBGroup
  ADD CONSTRAINT [FK_CNF_DBGroup_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DBGroup_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_DBGroup
  ADD CONSTRAINT [FK_CNF_DBGroup_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DBTable2DBGroup_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_DBTable2DBGroup
  ADD CONSTRAINT [FK_CNF_DBTable2DBGroup_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DBTable2DBGroup_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_DBTable2DBGroup
  ADD CONSTRAINT [FK_CNF_DBTable2DBGroup_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DBTable2DBGroup_DBTableId')
BEGIN
  ALTER TABLE CNF_DBTable2DBGroup 
  ADD CONSTRAINT [FK_CNF_DBTable2DBGroup_DBTableId] FOREIGN KEY([DBTableId]) 
  REFERENCES [CNF_DBTable] ([DBTableId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DBTable2DBGroup_DBGroupId')
BEGIN
  ALTER TABLE CNF_DBTable2DBGroup 
  ADD CONSTRAINT [FK_CNF_DBTable2DBGroup_DBGroupId] FOREIGN KEY([DBGroupId]) 
  REFERENCES [CNF_DBGroup] ([DBGroupId])
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>3008</SQLVERSION><RMTRACKLINK>85191</RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.objects WHERE [name] = N'data_sale_SalesRestriction' AND [type] = 'TR')
BEGIN
      DROP TRIGGER [dbo].[data_sale_SalesRestriction];
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>Create trigger [dbo].[data_sale_SalesRestriction] on [dbo].[DATA_Sale] FOR update
	 as
begin
	SET NOCOUNT ON;
    IF UPDATE(Paid) or Update(StatusCode)
    BEGIN

		Declare @Temp table (	AccountID int, 
								SaleID int,
								SaleItemID int,
								PerformanceID int,
								Quantity int,
								SalesDate DateTime,
								MatrixCellID int,
								RestrictionType int
							)

		DECLARE @INS_SaleID int
		DECLARE @status int = 0 
		DECLARE @DR_status int

		DECLARE	@ReservationAccountID int
		DECLARE	@B2BAccountID int  
		DECLARE	@TicketAccountID int
		DECLARE	@SaleID int
		DECLARE	@SaleItemID int
		DECLARE	@PerformanceID int
		DECLARE	@Quantity int
		DECLARE @MatrixCellID int
		DECLARE @EventID int

		DECLARE @RestrictionType int	
			
		DECLARE @ReservationAccountOwner int = 1
		DECLARE @TicketAccountOwner int = 2
		DECLARE @CheckforRestraintOnly int = 0

		SELECT @status=i.Paid, @INS_SaleID = i.Saleid 
				FROM inserted i
				JOIN deleted d
					ON i.[SaleID] = d.[SaleID]
					AND i.[Paid] &lt;&gt; d.[Paid]

		if @status = 0 
		begin
			SELECT @DR_status = CASE WHEN i.StatusCode = 2 then  1
			            else 0
					end, 
			       @INS_SaleID = i.Saleid 
					FROM inserted i
					JOIN deleted d
						ON i.[SaleID] = d.[SaleID]
						AND i.[StatusCode] &lt;&gt; d.[StatusCode]
		end


		if @status = 1
		begin
			DECLARE SaleItem_Cursor CURSOR LOCAL FOR
					select data_reservation.accountid, 
						   data_reservation.B2bAccountID,
						   data_saleitem.Matrixcellid,
						   data_saleitem.Quantity,
						   data_saleitem2account.Accountid,
						   data_sale.saleid,
						   data_saleitem.saleitemid

					from data_sale WITH(NOLOCK)
						LEFT JOIN data_reservation WITH(NOLOCK)					on data_reservation.saleid = data_sale.saleid
						INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
						LEFT  JOIN data_saleitem2account WITH(NOLOCK)				on data_saleitem2account.SaleitemID = data_saleitem.saleitemid

					Where data_sale.saleid = @INS_SaleID
										
			OPEN SaleItem_Cursor

				FETCH NEXT FROM SaleItem_Cursor INTO
									@ReservationAccountID, 
									@B2BAccountID,
									@MatrixCellID,
									@Quantity,
									@TicketAccountID,
									@SaleID,
									@SaleItemID

				WHILE @@FETCH_STATUS = 0
				BEGIN

					--   Ticket Test   with Ticket Owner				@TicketAccountOwner              --@RestrictionType = 1	
					exec otn_sp_GetAccountRestrictions @TicketAccountID,								--AccountID
													   @MatrixCellID,									--MatrixCellID
													   null,											--PerformanceID
													   null,											--EventID
													   @Quantity,										--Quantity
													   1,												--RestrictionType
													   @SaleID,											--SaleID
													   @SaleItemID,										--SaleItemID
													   0,												--CheckforRestrictionOnly
													   @TicketAccountOwner								--ReservationorTicketAccount		

				
					--   Ticket Test   with Reservation Owner			@ReservationAccountOwner         --@RestrictionType = 1
					exec otn_sp_GetAccountRestrictions @B2BAccountID,							--AccountID
													   @MatrixCellID,									--MatrixCellID
													   null,											--PerformanceID
													   null,											--EventID
													   @Quantity,										--Quantity
													   1,												--RestrictionType
													   @SaleID,											--SaleID
													   @SaleItemID,										--SaleItemID
													   0,												--CheckforRestrictionOnly
													   @ReservationAccountOwner							--ReservationorTicketAccount	

                    --   Ticket Test   with Reservation Owner			@ReservationAccountOwner         --@RestrictionType = 1
					exec otn_sp_GetAccountRestrictions @ReservationAccountID,							--AccountID
													   @MatrixCellID,									--MatrixCellID
													   null,											--PerformanceID
													   null,											--EventID
													   @Quantity,										--Quantity
													   1,												--RestrictionType
													   @SaleID,											--SaleID
													   @SaleItemID,										--SaleItemID
													   0,												--CheckforRestrictionOnly
													   @ReservationAccountOwner							--ReservationorTicketAccount	

					DECLARE Performance_Cursor CURSOR LOCAL FOR
						  select data_saleitem2Performance.PerformanceID,
						         cnf_Performance.eventid

							from data_saleitem2Performance WITH(NOLOCK)																					   
								LEFT  JOIN cnf_Performance WITH(NOLOCK)						on cnf_Performance.PerformanceID = data_saleitem2Performance.PerformanceID
						
							Where Active = 1
							  and data_saleitem2Performance.Saleitemid = @SaleItemID

					OPEN Performance_Cursor

						FETCH NEXT FROM Performance_Cursor INTO
											@PerformanceID,
											@EventID

						WHILE @@FETCH_STATUS = 0
						BEGIN
								--	Perforamnce Test     with Ticket Owner			@TicketAccountOwner              --@RestrictionType = 2
								exec otn_sp_GetAccountRestrictions @TicketAccountID,								--AccountID
																   @MatrixCellID,									--MatrixCellID
																   @PerformanceID,									--PerformanceID
																   @EventID,										--EventID
																   @Quantity,										--Quantity
																   2,												--RestrictionType
																   @SaleID,											--SaleID
																   @SaleItemID,										--SaleItemID
																   0,												--CheckforRestrictionOnly
																   @TicketAccountOwner								--ReservationorTicketAccount	

								--   Performance Test     with Reservation Owner    @TicketAccountOwner              --@RestrictionType = 2
								exec otn_sp_GetAccountRestrictions @ReservationAccountID,							--AccountID
																   @MatrixCellID,									--MatrixCellID
																   @PerformanceID,									--PerformanceID
																   @EventID,										--EventID
																   @Quantity,										--Quantity
																   2,												--RestrictionType
																   @SaleID,											--SaleID
																   @SaleItemID,										--SaleItemID
																   0,												--CheckforRestrictionOnly
																   @ReservationAccountOwner								--ReservationorTicketAccount	


						FETCH NEXT FROM Performance_Cursor INTO
											@PerformanceID,
											@EventID
				END
				CLOSE Performance_Cursor;
				DEALLOCATE Performance_Cursor;
				FETCH NEXT FROM SaleItem_Cursor INTO
									@ReservationAccountID, 
									@B2BAccountID,
									@MatrixCellID,
									@Quantity,
									@TicketAccountID,
									@SaleID,
									@SaleItemID
			end
			CLOSE SaleItem_Cursor;
			DEALLOCATE SaleItem_Cursor;
		END

		if @DR_status = 1
		begin
			DECLARE SaleItem_Cursor CURSOR LOCAL FOR
					select data_reservation.accountid, 
						   data_reservation.B2bAccountID,
						   data_saleitem.Matrixcellid,
						   data_saleitem.Quantity,
						   data_saleitem2account.Accountid,
						   data_sale.saleid,
						   data_saleitem.saleitemid

					from data_sale WITH(NOLOCK)
						LEFT JOIN data_reservation WITH(NOLOCK)					on data_reservation.saleid = data_sale.saleid
						INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
						LEFT  JOIN data_saleitem2account WITH(NOLOCK)				on data_saleitem2account.SaleitemID = data_saleitem.saleitemid

					Where data_sale.saleid = @INS_SaleID
					  and data_saleitem.quantity &lt; 0 
					
			OPEN SaleItem_Cursor

			FETCH NEXT FROM SaleItem_Cursor INTO
								@ReservationAccountID, 
								@B2BAccountID,
								@MatrixCellID,
								@Quantity,
								@TicketAccountID,
								@SaleID,
								@SaleItemID

			WHILE @@FETCH_STATUS = 0
			BEGIN

				--   Ticket Test   with Ticket Owner				@TicketAccountOwner              --@RestrictionType = 1	
				exec otn_sp_GetAccountRestrictions @TicketAccountID,								--AccountID
				                                   @MatrixCellID,									--MatrixCellID
												   null,											--PerformanceID
												   null,											--EventID
												   @Quantity,										--Quantity
												   1,												--RestrictionType
												   @SaleID,											--SaleID
												   @SaleItemID,										--SaleItemID
												   0,												--CheckforRestrictionOnly
												   @TicketAccountOwner								--ReservationorTicketAccount		

				
				--   Ticket Test   with Reservation Owner			@ReservationAccountOwner         --@RestrictionType = 1
				exec otn_sp_GetAccountRestrictions @B2BAccountID,							        --AccountID
				                                   @MatrixCellID,									--MatrixCellID
												   null,											--PerformanceID
												   null,											--EventID
												   @Quantity,										--Quantity
												   1,												--RestrictionType
												   @SaleID,											--SaleID
												   @SaleItemID,										--SaleItemID
												   0,												--CheckforRestrictionOnly
												   @ReservationAccountOwner							--ReservationorTicketAccount
												   
				--   Ticket Test   with Reservation Owner			@ReservationAccountOwner         --@RestrictionType = 1
				exec otn_sp_GetAccountRestrictions @ReservationAccountID,							--AccountID
				                                   @MatrixCellID,									--MatrixCellID
												   null,											--PerformanceID
												   null,											--EventID
												   @Quantity,										--Quantity
												   1,												--RestrictionType
												   @SaleID,											--SaleID
												   @SaleItemID,										--SaleItemID
												   0,												--CheckforRestrictionOnly
												   @ReservationAccountOwner							--ReservationorTicketAccount													   	

			DECLARE Performance_Cursor CURSOR LOCAL FOR
						  select data_saleitem2Performance.PerformanceID,
						         cnf_Performance.eventid

							from data_saleitem2Performance WITH(NOLOCK)																					   
								LEFT  JOIN cnf_Performance WITH(NOLOCK)						on cnf_Performance.PerformanceID = data_saleitem2Performance.PerformanceID
						
							Where Active = 1
							  and data_saleitem2Performance.Saleitemid = @SaleItemID

					OPEN Performance_Cursor

						FETCH NEXT FROM Performance_Cursor INTO
											@PerformanceID,
											@EventID

						WHILE @@FETCH_STATUS = 0
						BEGIN
								--	Perforamnce Test     with Ticket Owner			@TicketAccountOwner              --@RestrictionType = 2
								exec otn_sp_GetAccountRestrictions @TicketAccountID,								--AccountID
																   @MatrixCellID,									--MatrixCellID
																   @PerformanceID,									--PerformanceID
																   @EventID,										--EventID
																   @Quantity,										--Quantity
																   2,												--RestrictionType
																   @SaleID,											--SaleID
																   @SaleItemID,										--SaleItemID
																   0,												--CheckforRestrictionOnly
																   @TicketAccountOwner								--ReservationorTicketAccount	

								--   Performance Test     with Reservation Owner    @TicketAccountOwner              --@RestrictionType = 2
								exec otn_sp_GetAccountRestrictions @ReservationAccountID,							--AccountID
																   @MatrixCellID,									--MatrixCellID
																   @PerformanceID,									--PerformanceID
																   @EventID,										--EventID
																   @Quantity,										--Quantity
																   2,												--RestrictionType
																   @SaleID,											--SaleID
																   @SaleItemID,										--SaleItemID
																   0,												--CheckforRestrictionOnly
																   @ReservationAccountOwner								--ReservationorTicketAccount	
						FETCH NEXT FROM Performance_Cursor INTO
											@PerformanceID,
											@EventID
				END
				CLOSE Performance_Cursor;
				DEALLOCATE Performance_Cursor;

				FETCH NEXT FROM SaleItem_Cursor INTO
								@ReservationAccountID, 
								@B2BAccountID,
								@MatrixCellID,
								@Quantity,
								@TicketAccountID,
								@SaleID,
								@SaleItemID

			end
			CLOSE SaleItem_Cursor;
			DEALLOCATE SaleItem_Cursor;
		end
	end
end</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>3007</SQLVERSION><RMTRACKLINK>83300</RMTRACKLINK><REASON>Added 2 new tables:
1)CNF_HL_Group
2)CNF_DBTable2Group

Added new column to CNF_DBTable: TableObjectId</REASON><TABLENAMES>CNF_HL_Group=GroupId
CNF_DBTable2Group=DBTable2GroupId
CNF_DBTable=DBTableId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                WHERE TABLE_SCHEMA = 'dbo' 
                  AND TABLE_NAME = 'CNF_HL_Group')
BEGIN
Create table [CNF_HL_Group]
(
	[GroupId] Integer Identity(1,1) NOT NULL,
	[SubModelId] Integer NULL,
	[Name] Nvarchar(100) NULL,
	[SystemGroup] Smallint NULL,
	[Last_UserId_Log] Integer NULL,
	[Last_WorkstationId_Log] Integer NULL,
	[Last_DateTime_Log] Datetime NULL,
Primary Key ([GroupId])
) 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                WHERE TABLE_SCHEMA = 'dbo' 
                  AND TABLE_NAME = 'CNF_DBTable2Group')
BEGIN
Create table [CNF_DBTable2Group]
(
	[DBTable2GroupId] Integer Identity(1,1) NOT NULL,
	[DBTableId] Integer NOT NULL,
	[GroupId] Integer NOT NULL,
	[SubModelId] Integer NULL,
	[TableObjectId] Integer NULL,
	[SystemTable] Smallint NULL,
	[Last_UserId_Log] Integer NULL,
	[Last_WorkstationId_Log] Integer NULL,
	[Last_DateTime_Log] Datetime NULL,
Primary Key ([DBTable2GroupId],[DBTableId],[GroupId])
) 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_HL_Group_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_HL_Group
  ADD CONSTRAINT [FK_CNF_HL_Group_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_HL_Group_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_HL_Group 
  ADD CONSTRAINT [FK_CNF_HL_Group_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DBTable2Group_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_DBTable2Group
  ADD CONSTRAINT [FK_CNF_DBTable2Group_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DBTable2Group_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_DBTable2Group 
  ADD CONSTRAINT [FK_CNF_DBTable2Group_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DBTable2Group_DBTableId')
BEGIN
  ALTER TABLE CNF_DBTable2Group 
  ADD CONSTRAINT [FK_CNF_DBTable2Group_DBTableId] FOREIGN KEY([DBTableId]) 
  REFERENCES [CNF_DBTable] ([DBTableId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DBTable2Group_GroupId')
BEGIN
  ALTER TABLE CNF_DBTable2Group 
  ADD CONSTRAINT [FK_CNF_DBTable2Group_GroupId] FOREIGN KEY([GroupId]) 
  REFERENCES [CNF_HL_Group] ([GroupId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
           WHERE Name = N'TableObjectId' AND
           Object_ID  = Object_ID(N'CNF_DBTable'))
BEGIN
  ALTER TABLE CNF_DBTable 
  ADD TableObjectId Smallint NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>pchen</ADDEDBY><SQLVERSION>3006</SQLVERSION><RMTRACKLINK>IDBOS-1293</RMTRACKLINK><REASON>add field ExternalPackageType to CNF_Promotion</REASON><TABLENAMES>CNF_Promotion=PromotionId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
           WHERE Name = N'ExternalPackageType' AND
           Object_ID  = Object_ID(N'CNF_Promotion'))
BEGIN
  ALTER TABLE CNF_Promotion 
  ADD ExternalPackageType Smallint NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>3005</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
          WHERE Name = N'RestrictionType' 
          AND OBJECT_ID = OBJECT_ID(N'Data_AccountLimit'))
BEGIN
  ALTER TABLE Data_AccountLimit
  ADD RestrictionType [smallint] NULL 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT * FROM sys.columns
          WHERE Name = N'RestrictionType' 
          AND OBJECT_ID = OBJECT_ID(N'Data_AccountLimit'))
BEGIN
  ALTER TABLE Data_AccountLimit
  ALTER COLUMN RestrictionType [smallint] NULL; 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * 
  FROM sys.foreign_keys 
   WHERE object_id = OBJECT_ID(N'dbo.fk_CNF_SaleLimitRestriction_CNF_Performance')
   AND parent_object_id = OBJECT_ID(N'dbo.CNF_Performance')
)
  ALTER TABLE CNF_Performance DROP CONSTRAINT fk_CNF_SaleLimitRestriction_CNF_Performance  </SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_AccountRestrictionsConversion]')
				AND type IN ( N'P'))
    DROP Procedure otn_sp_AccountRestrictionsConversion; </SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>CREATE Procedure otn_sp_AccountRestrictionsConversion(@AccountRestrictionID int)  

AS    
BEGIN
DECLARE @NEWAccountRestrictionID int


	DECLARE Restriction_Cursor CURSOR LOCAL FOR
			select SaleRestrictionId
				from CNF_saleRestriction				

	OPEN Restriction_Cursor

	FETCH NEXT FROM Restriction_Cursor INTO
						@AccountRestrictionID
						

	WHILE @@FETCH_STATUS = 0
	BEGIN
			INSERT INTO [dbo].[CNF_AccountRestriction]
						   ([StartDateTime]
						   ,[EndDateTime]
						   ,[Enabled]
						   ,[Description]
						   ,[RestrictionType]
						   ,[ReservationAccountLimit]
						   ,[TicketAccountLimit]
						   ,[PerDayLimit]
						   ,[PerWeekLimit]
						   ,[PerMonthLimit]
						   ,[PerYearLimit]
						   ,[Last_UserId_Log]
						   ,[Last_WorkstationId_Log]
						   ,[Last_DateTime_Log])
				select CNF_saleRestriction.StartDateTime,
					   CNF_saleRestriction.EndDateTime,
					   CNF_saleRestriction.Enabled,
					   CNF_saleRestriction.Description,
					   case when MaxTicketXOwnerXPerf is not null and MaxTicketXTckAccountXPerf is not null then 2
							else 1
						end as RestrictionType,
					   case when MaxTicketXOwnerXPerf is not null then MaxTicketXOwnerXPerf
							else MaxAllowed
						end as ReservationAccountLImit,
					   case when MaxTicketXTckAccountXPerf is not null then MaxTicketXTckAccountXPerf
							else MaxAllowedPerTckAccount
						end as TicketAccountLimit,
					(select MaxAllowedPerPeriod
					from CNF_SaleRestrictionValidity
					where CNF_SaleRestrictionValidity.SaleRestrictionId = CNF_saleRestriction.SaleRestrictionId
					  and Period = 0
					  and Enabled = 1) PerDayLimit,
					(select MaxAllowedPerPeriod
					from CNF_SaleRestrictionValidity
					where CNF_SaleRestrictionValidity.SaleRestrictionId = CNF_saleRestriction.SaleRestrictionId
					  and Period = 1
					  and Enabled = 1) PerWeekLimit,
					(select MaxAllowedPerPeriod
					from CNF_SaleRestrictionValidity
					where CNF_SaleRestrictionValidity.SaleRestrictionId = CNF_saleRestriction.SaleRestrictionId
					  and Period = 2
					  and Enabled = 1) PerMonthLimit,
					  (select MaxAllowedPerPeriod
					from CNF_SaleRestrictionValidity
					where CNF_SaleRestrictionValidity.SaleRestrictionId = CNF_saleRestriction.SaleRestrictionId
					  and Period = 6
					  and Enabled = 1) PerYearLimit,
					1,
					1,
					getdate()

				from CNF_saleRestriction
					where CNF_SaleRestriction.SaleRestrictionId = @AccountRestrictionID		

				SELECT @NEWAccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId 
				  FROM CNF_AccountRestriction 
				 WHERE CNF_AccountRestriction.AccountRestrictionId = SCOPE_IDENTITY()

--INSERT ALL MatrixCells
				 INSERT INTO [dbo].[CNF_AccountRestriction2MatrixCell]
							([AccountRestrictionId]
							,[MatrixCellId]
							,[Last_UserId_Log]
							,[Last_WorkstationId_Log]
							,[Last_DateTime_Log])
				  select @NEWAccountRestrictionID, 
				         Matrixcellid,
						 1,
						 1,
						 getdate()
					from CNF_SaleRestriction2MatrixCell
					where SaleRestrictionId = @AccountRestrictionID

--INSERT ALL Acounts
				INSERT INTO [dbo].[CNF_AccountRestriction2Account]
							([AccountRestrictionId]
							,[DMGCategoryID]
							,[AccountId]
							,[Last_UserId_Log]
							,[Last_WorkstationId_Log]
							,[Last_DateTime_Log])
					select distinct @NEWAccountRestrictionID,
									null,
									AccountID,
									1,
									1,
									getdate()
					from DATA_SaleLimit
					where data_salelimit.salerestrictionID = @AccountRestrictionID


					INSERT INTO [dbo].[DATA_AccountLimit]
							   ([AccountRestrictionId]
							   ,[AccountId]
							   ,[SaleId]
							   ,[SaleItemId]
							   ,[PerformanceId]
							   ,[SaleDate]
							   ,[ReservationAccountQuantity]
							   ,[TicketAccountQuantity])
					select @NEWAccountRestrictionID,
							DATA_SaleLimit.AccountID,
							DATA_SaleLimit.Saleid,
							NULL as SaleItemID,
							PerformanceID,
							GetDate() as SaleDate,
							Used,
							CountPerTckOwner
					from DATA_SaleLimit			
						INNER JOIn CNF_saleRestriction			on CNF_saleRestriction.SaleRestrictionId = DATA_SaleLimit.SaleRestrictionId
					where DATA_SaleLimit.enabled = 1





		FETCH NEXT FROM Restriction_Cursor INTO
							@AccountRestrictionID


	END	
	
	CLOSE Restriction_Cursor;
	DEALLOCATE Restriction_Cursor;

RETURN;
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>     IF(NOT EXISTS(SELECT 1 FROM dbo.cnf_AccountRestriction))
BEGIN
  exec otn_sp_AccountRestrictionsConversion 1
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>  IF EXISTS(SELECT * FROM sys.columns
          WHERE Name = N'Restrictiontype' 
          AND OBJECT_ID = OBJECT_ID(N'data_accountlimit'))
BEGIN
  ALTER TABLE data_accountlimit DROP column Restrictiontype
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>3004</SQLVERSION><RMTRACKLINK>85191 </RMTRACKLINK><REASON>Correct trigger for deleted Reservations</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.objects WHERE [name] = N'data_sale_SalesRestriction' AND [type] = 'TR')
BEGIN
      DROP TRIGGER [dbo].[data_sale_SalesRestriction];
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>Create trigger [dbo].[data_sale_SalesRestriction] on [dbo].[DATA_Sale] FOR update
	 as
begin
	SET NOCOUNT ON;
    IF UPDATE(Paid) or Update(StatusCode)
    BEGIN

		Declare @Temp table (	AccountID int, 
								SaleID int,
								SaleItemID int,
								PerformanceID int,
								Quantity int,
								SalesDate DateTime,
								MatrixCellID int,
								RestrictionType int
							)

		DECLARE @INS_SaleID int
		DECLARE @status int = 0 
		DECLARE @DR_status int

		DECLARE	@ReservationAccountID int
		DECLARE	@B2BAccountID int  
		DECLARE	@TicketAccountID int
		DECLARE	@SaleID int
		DECLARE	@SaleItemID int
		DECLARE	@PerformanceID int
		DECLARE	@Quantity int
		DECLARE @MatrixCellID int
		DECLARE @EventID int

		DECLARE @RestrictionType int	
			
		DECLARE @ReservationAccountOwner int = 1
		DECLARE @TicketAccountOwner int = 2
		DECLARE @CheckforRestraintOnly int = 0

		SELECT @status=i.Paid, @INS_SaleID = i.Saleid 
				FROM inserted i
				JOIN deleted d
					ON i.[SaleID] = d.[SaleID]
					AND i.[Paid] &lt;&gt; d.[Paid]

		if @status = 0 
		begin
			SELECT @DR_status = CASE WHEN i.StatusCode = 2 then  1
			            else 0
					end, 
			       @INS_SaleID = i.Saleid 
					FROM inserted i
					JOIN deleted d
						ON i.[SaleID] = d.[SaleID]
						AND i.[StatusCode] &lt;&gt; d.[StatusCode]
		end


		if @status = 1
		begin
			DECLARE SaleItem_Cursor CURSOR LOCAL FOR
					select data_reservation.accountid, 
						   data_reservation.B2bAccountID,
						   data_saleitem.Matrixcellid,
						   data_saleitem.Quantity,
						   data_saleitem2Performance.PerformanceID,
						   cnf_Performance.eventid,
						   data_saleitem2account.Accountid,
						   data_sale.saleid,
						   data_saleitem.saleitemid

					from data_sale WITH(NOLOCK)
						INNER JOIN data_reservation WITH(NOLOCK)					on data_reservation.saleid = data_sale.saleid
						INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
						LEFT  JOIN data_saleitem2Performance WITH(NOLOCK)			on data_saleitem2Performance.saleitemid = data_saleitem.saleitemid
																					   and Active = 1
						LEFT  JOIN cnf_Performance WITH(NOLOCK)						on cnf_Performance.PerformanceID = data_saleitem2Performance.PerformanceID
						LEFT  JOIN data_saleitem2account WITH(NOLOCK)				on data_saleitem2account.SaleitemID = data_saleitem.saleitemid

					Where data_sale.saleid = @INS_SaleID
					
					
			OPEN SaleItem_Cursor


			FETCH NEXT FROM SaleItem_Cursor INTO
								@ReservationAccountID, 
								@B2BAccountID,
								@MatrixCellID,
								@Quantity,
								@PerformanceID,
								@EventID,
								@TicketAccountID,
								@SaleID,
								@SaleItemID

			WHILE @@FETCH_STATUS = 0
			BEGIN

				--   Ticket Test   with Ticket Owner				@TicketAccountOwner              --@RestrictionType = 1	
				exec otn_sp_GetAccountRestrictions @TicketAccountID,								--AccountID
				                                   @MatrixCellID,									--MatrixCellID
												   null,											--PerformanceID
												   null,											--EventID
												   @Quantity,										--Quantity
												   1,												--RestrictionType
												   @SaleID,											--SaleID
												   @SaleItemID,										--SaleItemID
												   0,												--CheckforRestrictionOnly
												   @TicketAccountOwner								--ReservationorTicketAccount		

				
				--   Ticket Test   with Reservation Owner			@ReservationAccountOwner         --@RestrictionType = 1
				exec otn_sp_GetAccountRestrictions @ReservationAccountID,							--AccountID
				                                   @MatrixCellID,									--MatrixCellID
												   null,											--PerformanceID
												   null,											--EventID
												   @Quantity,										--Quantity
												   1,												--RestrictionType
												   @SaleID,											--SaleID
												   @SaleItemID,										--SaleItemID
												   0,												--CheckforRestrictionOnly
												   @ReservationAccountOwner							--ReservationorTicketAccount	

				--	Perforamnce Test     with Ticket Owner			@TicketAccountOwner              --@RestrictionType = 2
				exec otn_sp_GetAccountRestrictions @TicketAccountID,								--AccountID
				                                   @MatrixCellID,									--MatrixCellID
												   @PerformanceID,									--PerformanceID
												   @EventID,										--EventID
												   @Quantity,										--Quantity
												   2,												--RestrictionType
												   @SaleID,											--SaleID
												   @SaleItemID,										--SaleItemID
												   0,												--CheckforRestrictionOnly
												   @TicketAccountOwner								--ReservationorTicketAccount	

				--   Performance Test     with Reservation Owner    @TicketAccountOwner              --@RestrictionType = 2
				exec otn_sp_GetAccountRestrictions @ReservationAccountID,							--AccountID
				                                   @MatrixCellID,									--MatrixCellID
												   @PerformanceID,									--PerformanceID
												   @EventID,										--EventID
												   @Quantity,										--Quantity
												   2,												--RestrictionType
												   @SaleID,											--SaleID
												   @SaleItemID,										--SaleItemID
												   0,												--CheckforRestrictionOnly
												   @ReservationAccountOwner								--ReservationorTicketAccount	

			FETCH NEXT FROM SaleItem_Cursor INTO
								@ReservationAccountID, 
								@B2BAccountID,
								@MatrixCellID,
								@Quantity,
								@PerformanceID,
								@EventID,
								@TicketAccountID,
								@SaleID,
								@SaleItemID
			end
			CLOSE SaleItem_Cursor;
			DEALLOCATE SaleItem_Cursor;
		END

		if @DR_status = 1
		begin
			DECLARE SaleItem_Cursor CURSOR LOCAL FOR
					select data_reservation.accountid, 
						   data_reservation.B2bAccountID,
						   data_saleitem.Matrixcellid,
						   data_saleitem.Quantity,
						   data_saleitem2Performance.PerformanceID,
						   cnf_Performance.eventid,
						   data_saleitem2account.Accountid,
						   data_sale.saleid,
						   data_saleitem.saleitemid

					from data_sale WITH(NOLOCK)
						INNER JOIN data_reservation WITH(NOLOCK)					on data_reservation.saleid = data_sale.saleid
						INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
						LEFT  JOIN data_saleitem2Performance WITH(NOLOCK)			on data_saleitem2Performance.saleitemid = data_saleitem.saleitemid
																					   and Active = 1
						LEFT  JOIN cnf_Performance WITH(NOLOCK)						on cnf_Performance.PerformanceID = data_saleitem2Performance.PerformanceID
						LEFT  JOIN data_saleitem2account WITH(NOLOCK)				on data_saleitem2account.SaleitemID = data_saleitem.saleitemid

					Where data_sale.saleid = @INS_SaleID
					  and data_saleitem.quantity &lt; 0 
					
			OPEN SaleItem_Cursor

			FETCH NEXT FROM SaleItem_Cursor INTO
								@ReservationAccountID, 
								@B2BAccountID,
								@MatrixCellID,
								@Quantity,
								@PerformanceID,
								@EventID,
								@TicketAccountID,
								@SaleID,
								@SaleItemID

			WHILE @@FETCH_STATUS = 0
			BEGIN


				--   Ticket Test   with Ticket Owner				@TicketAccountOwner              --@RestrictionType = 1	
				exec otn_sp_GetAccountRestrictions @TicketAccountID,								--AccountID
				                                   @MatrixCellID,									--MatrixCellID
												   null,											--PerformanceID
												   null,											--EventID
												   @Quantity,										--Quantity
												   1,												--RestrictionType
												   @SaleID,											--SaleID
												   @SaleItemID,										--SaleItemID
												   0,												--CheckforRestrictionOnly
												   @TicketAccountOwner								--ReservationorTicketAccount		

				
				--   Ticket Test   with Reservation Owner			@ReservationAccountOwner         --@RestrictionType = 1
				exec otn_sp_GetAccountRestrictions @ReservationAccountID,							--AccountID
				                                   @MatrixCellID,									--MatrixCellID
												   null,											--PerformanceID
												   null,											--EventID
												   @Quantity,										--Quantity
												   1,												--RestrictionType
												   @SaleID,											--SaleID
												   @SaleItemID,										--SaleItemID
												   0,												--CheckforRestrictionOnly
												   @ReservationAccountOwner							--ReservationorTicketAccount	

				--	Perforamnce Test     with Ticket Owner			@TicketAccountOwner              --@RestrictionType = 2
				exec otn_sp_GetAccountRestrictions @TicketAccountID,								--AccountID
				                                   @MatrixCellID,									--MatrixCellID
												   @PerformanceID,									--PerformanceID
												   @EventID,										--EventID
												   @Quantity,										--Quantity
												   2,												--RestrictionType
												   @SaleID,											--SaleID
												   @SaleItemID,										--SaleItemID
												   0,												--CheckforRestrictionOnly
												   @TicketAccountOwner								--ReservationorTicketAccount	

				--   Performance Test     with Reservation Owner    @TicketAccountOwner              --@RestrictionType = 2
				exec otn_sp_GetAccountRestrictions @ReservationAccountID,							--AccountID
				                                   @MatrixCellID,									--MatrixCellID
												   @PerformanceID,									--PerformanceID
												   @EventID,										--EventID
												   @Quantity,										--Quantity
												   2,												--RestrictionType
												   @SaleID,											--SaleID
												   @SaleItemID,										--SaleItemID
												   0,												--CheckforRestrictionOnly
												   @ReservationAccountOwner								--ReservationorTicketAccount

				FETCH NEXT FROM SaleItem_Cursor INTO
								@ReservationAccountID, 
								@B2BAccountID,
								@MatrixCellID,
								@Quantity,
								@PerformanceID,
								@EventID,
								@TicketAccountID,
								@SaleID,
								@SaleItemID

			end
			CLOSE SaleItem_Cursor;
			DEALLOCATE SaleItem_Cursor;
		end
	end
end</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT> ALTER TABLE [dbo].[DATA_Sale] ENABLE TRIGGER [data_sale_SalesRestriction]</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fdipalma</ADDEDBY><SQLVERSION>3003</SQLVERSION><RMTRACKLINK>86385</RMTRACKLINK><REASON>Renewal Plan of Gardaland CLUB - Update 2</REASON><TABLENAMES>CNF_RenewalContract=RenewalContractId
DATA_RenewalPlan=RenewalPlanId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
WHERE Name = N'TryAfterDays' AND OBJECT_ID = OBJECT_ID(N'CNF_RenewalContract'))
BEGIN
  ALTER TABLE CNF_RenewalContract ADD TryAfterDays Smallint Default 0 NOT NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
WHERE Name = N'TryAfterDays' AND OBJECT_ID = OBJECT_ID(N'DATA_RenewalPlan'))
BEGIN
  ALTER TABLE DATA_RenewalPlan ADD TryAfterDays Smallint Default 0 NOT NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>pchen</ADDEDBY><SQLVERSION>3002</SQLVERSION><RMTRACKLINK>IDBOS-1144</RMTRACKLINK><REASON>add field ActiveFrom and ActiveTo to DATA_Coupon</REASON><TABLENAMES>DATA_Coupon=CouponId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
           WHERE Name = N'ActiveFrom' AND
           Object_ID  = Object_ID(N'DATA_Coupon'))
BEGIN
  ALTER TABLE DATA_Coupon 
  ADD ActiveFrom Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
           WHERE Name = N'ActiveTo' AND
           Object_ID  = Object_ID(N'DATA_Coupon'))
BEGIN
  ALTER TABLE DATA_Coupon 
  ADD ActiveTo Datetime NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>lfornaroli</ADDEDBY><SQLVERSION>3001</SQLVERSION><RMTRACKLINK>IDBOS-1228</RMTRACKLINK><REASON>Add new table for check payments
[0] create table
[1] add FK</REASON><TABLENAMES>DATA_PaymentCheck=PaymentId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                WHERE TABLE_SCHEMA = 'dbo' 
                  AND TABLE_NAME = 'DATA_PaymentCheck')
BEGIN
Create table DATA_PaymentCheck
(
	[PaymentId] Integer NOT NULL,
	[CheckNumber] nvarchar(200)
Primary Key ([PaymentId])
) 
 end</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>Alter table [DATA_PaymentCheck] 
  add  foreign key([PaymentId]) references [DATA_Payment] ([PaymentId]) 
</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>3000</SQLVERSION><RMTRACKLINK>86277</RMTRACKLINK><REASON></REASON><TABLENAMES>CNF_System=SystemId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'MixedTransactionMode' AND
                Object_ID  = Object_ID(N'CNF_System'))
BEGIN
  Alter Table CNF_System
  DROP COLUMN MixedTransactionMode 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'MixedTransactionMode' AND
                Object_ID  = Object_ID(N'CNF_System'))
BEGIN
  Alter Table CNF_System
  Add MixedTransactionMode Smallint 
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2999</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>New CNF_LinkedPerformance</REASON><TABLENAMES>CNF_LinkedPerformance=LinkedPerformanceId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                WHERE TABLE_SCHEMA = 'dbo' 
                  AND TABLE_NAME = 'CNF_LinkedPerformance')
BEGIN
Create table CNF_LinkedPerformance
(
	[LinkedPerformanceId] Integer Identity(1,1) NOT NULL,
	[TemplatePerformanceId] int NOT NULL,
	[ChildPerformanceId] int NULL,
	[Enabled] smallint NULL,
Primary Key ([LinkedPerformanceId])
) 
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fesposito</ADDEDBY><SQLVERSION>2998</SQLVERSION><RMTRACKLINK>77507</RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'MixedTransactionMode' AND
                Object_ID  = Object_ID(N'CNF_System'))
BEGIN
  Alter Table CNF_System
  Add MixedTransactionMode Smallint 
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>pdalben</ADDEDBY><SQLVERSION>2997</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>Added CNF_LocationMatrix.DeductionType</REASON><TABLENAMES>CNF_LocationMatrix=LocationMatrixId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
WHERE Name = N'DeductionType' AND OBJECT_ID = OBJECT_ID(N'CNF_LocationMatrix'))
BEGIN
  ALTER TABLE CNF_LocationMatrix ADD DeductionType Smallint Default 0 NOT NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>2996</SQLVERSION><RMTRACKLINK>IDBOS-1164</RMTRACKLINK><REASON>Added new field to DATA_Transaction: IsBulk</REASON><TABLENAMES>DATA_Transaction=TransactionId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
           WHERE Name = N'IsBulk' AND
           Object_ID  = Object_ID(N'DATA_Transaction'))
BEGIN
  ALTER TABLE DATA_Transaction 
  ADD IsBulk Smallint NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>pchen</ADDEDBY><SQLVERSION>2995</SQLVERSION><RMTRACKLINK>IDBOS-1144</RMTRACKLINK><REASON>add field ExternalCouponType to CNF_Promotion</REASON><TABLENAMES>CNF_Promotion=PromotionId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
           WHERE Name = N'ExternalCouponType' AND
           Object_ID  = Object_ID(N'CNF_Promotion'))
BEGIN
  ALTER TABLE CNF_Promotion 
  ADD ExternalCouponType Smallint NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>pdalben</ADDEDBY><SQLVERSION>2994</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>Added CNF_Event.EventExternalCode</REASON><TABLENAMES>CNF_Event=EventId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'EventExternalCode' AND
                Object_ID  = Object_ID(N'CNF_Event'))
BEGIN
  ALTER TABLE CNF_Event
  ADD EventExternalCode nvarchar(50) NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>pchen</ADDEDBY><SQLVERSION>2993</SQLVERSION><RMTRACKLINK>IDBOS-1144</RMTRACKLINK><REASON>alterfield Configuration to CNF_Promotion</REASON><TABLENAMES>CNF_Promotion=PromotionId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
           WHERE Name = N'Configuration' AND
           Object_ID  = Object_ID(N'CNF_Promotion'))
BEGIN
  ALTER TABLE CNF_Promotion DROP COLUMN Configuration 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
           WHERE Name = N'Configuration' AND
           Object_ID  = Object_ID(N'CNF_Promotion'))
BEGIN
  ALTER TABLE CNF_Promotion 
  ADD Configuration nvarchar(max) NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>pchen</ADDEDBY><SQLVERSION>2992</SQLVERSION><RMTRACKLINK>IDBOS-1144</RMTRACKLINK><REASON>add field Configuration to CNF_Promotion</REASON><TABLENAMES>CNF_Promotion=PromotionId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
           WHERE Name = N'Configuration' AND
           Object_ID  = Object_ID(N'CNF_Promotion'))
BEGIN
  ALTER TABLE CNF_Promotion 
  ADD Configuration Nvarchar(100) NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>2991</SQLVERSION><RMTRACKLINK>IDBOS-1124</RMTRACKLINK><REASON>Added 3 fields to CNF_Delivery: 
1) DoBulkOrder
2) MinQuantityThreshold
3) MaxQuantityThreshold</REASON><TABLENAMES>CNF_Delivery=DeliveryId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
           WHERE Name = N'DoBulkOrder' AND
           Object_ID  = Object_ID(N'CNF_Delivery'))
BEGIN
  ALTER TABLE CNF_Delivery 
  ADD DoBulkOrder Smallint NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
           WHERE Name = N'MinQuantityThreshold' AND
           Object_ID  = Object_ID(N'CNF_Delivery'))
BEGIN
  ALTER TABLE CNF_Delivery 
  ADD MinQuantityThreshold Integer NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
           WHERE Name = N'MaxQuantityThreshold' AND
           Object_ID  = Object_ID(N'CNF_Delivery'))
BEGIN
  ALTER TABLE CNF_Delivery 
  ADD MaxQuantityThreshold Integer NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dchen</ADDEDBY><SQLVERSION>2990</SQLVERSION><RMTRACKLINK>85336</RMTRACKLINK><REASON>Removing useless field.</REASON><TABLENAMES>DATA_SaleItem2Performance=SaleItem2PerformanceId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
            WHERE Name = N'MandatoryMove ' AND
                  Object_ID  = Object_ID(N'DATA_SaleItem2Performance'))
BEGIN
  ALTER TABLE DATA_SaleItem2Performance DROP COLUMN MandatoryMove
  
  ALTER TABLE DATA_SaleItem2Performance ALTER COLUMN MovedOnUpgrade SMALLINT 
END

</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>2989</SQLVERSION><RMTRACKLINK>85191</RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.objects WHERE [name] = N'data_sale_SalesRestriction' AND [type] = 'TR')
BEGIN
  DROP TRIGGER [dbo].[data_sale_SalesRestriction];
END;



</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>Create trigger [dbo].[data_sale_SalesRestriction] on [dbo].[DATA_Sale] FOR update
	 as
begin
	SET NOCOUNT ON;
    IF UPDATE(Paid)
    BEGIN

		Declare @Temp table (	AccountID int, 
								SaleID int,
								SaleItemID int,
								PerformanceID int,
								Quantity int,
								SalesDate DateTime,
								MatrixCellID int,
								RestrictionType int
							)

		DECLARE @INS_SaleID int
		DECLARE @status int

		DECLARE	@ReservationAccountID int
		DECLARE	@B2BAccountID int  
		DECLARE	@TicketAccountID int
		DECLARE	@SaleID int
		DECLARE	@SaleItemID int
		DECLARE	@PerformanceID int
		DECLARE	@Quantity int
		DECLARE @MatrixCellID int
		DECLARE @EventID int

		DECLARE @RestrictionType int	
			
		DECLARE @ReservationAccountOwner int = 1
		DECLARE @TicketAccountOwner int = 2
		DECLARE @CheckforRestraintOnly int = 0

		SELECT @status=i.Paid, @INS_SaleID = i.Saleid 
				FROM inserted i
				JOIN deleted d
					ON i.[SaleID] = d.[SaleID]
					AND i.[Paid] &lt;&gt; d.[Paid]

		if @status = 1
		begin
			DECLARE SaleItem_Cursor CURSOR LOCAL FOR
					select data_reservation.accountid, 
						   data_reservation.B2bAccountID,
						   data_saleitem.Matrixcellid,
						   data_saleitem.Quantity,
						   data_saleitem2Performance.PerformanceID,
						   cnf_Performance.eventid,
						   data_saleitem2account.Accountid,
						   data_sale.saleid,
						   data_saleitem.saleitemid

					from data_sale WITH(NOLOCK)
						INNER JOIN data_reservation WITH(NOLOCK)					on data_reservation.saleid = data_sale.saleid
						INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
						LEFT  JOIN data_saleitem2Performance WITH(NOLOCK)			on data_saleitem2Performance.saleitemid = data_saleitem.saleitemid
																					   and Active = 1
						LEFT  JOIN cnf_Performance WITH(NOLOCK)						on cnf_Performance.PerformanceID = data_saleitem2Performance.PerformanceID
						LEFT  JOIN data_saleitem2account WITH(NOLOCK)				on data_saleitem2account.SaleitemID = data_saleitem.saleitemid

					Where data_sale.saleid = @INS_SaleID
					
					
			OPEN SaleItem_Cursor


			FETCH NEXT FROM SaleItem_Cursor INTO
								@ReservationAccountID, 
								@B2BAccountID,
								@MatrixCellID,
								@Quantity,
								@PerformanceID,
								@EventID,
								@TicketAccountID,
								@SaleID,
								@SaleItemID

			WHILE @@FETCH_STATUS = 0
			BEGIN
	
				--   Ticket Test   with Ticket Owner				@TicketAccountOwner              --@RestrictionType = 1	
				exec otn_sp_GetAccountRestrictions @TicketAccountID,								--AccountID
				                                   @MatrixCellID,									--MatrixCellID
												   null,											--PerformanceID
												   null,											--EventID
												   @Quantity,										--Quantity
												   1,												--RestrictionType
												   @SaleID,											--SaleID
												   @SaleItemID,										--SaleItemID
												   0,												--CheckforRestrictionOnly
												   @TicketAccountOwner								--ReservationorTicketAccount		

				
				--   Ticket Test   with Reservation Owner			@ReservationAccountOwner         --@RestrictionType = 1
				exec otn_sp_GetAccountRestrictions @ReservationAccountID,							--AccountID
				                                   @MatrixCellID,									--MatrixCellID
												   null,											--PerformanceID
												   null,											--EventID
												   @Quantity,										--Quantity
												   1,												--RestrictionType
												   @SaleID,											--SaleID
												   @SaleItemID,										--SaleItemID
												   0,												--CheckforRestrictionOnly
												   @ReservationAccountOwner							--ReservationorTicketAccount	

				--	Perforamnce Test     with Ticket Owner			@TicketAccountOwner              --@RestrictionType = 2
				exec otn_sp_GetAccountRestrictions @TicketAccountID,								--AccountID
				                                   @MatrixCellID,									--MatrixCellID
												   @PerformanceID,									--PerformanceID
												   @EventID,										--EventID
												   @Quantity,										--Quantity
												   2,												--RestrictionType
												   @SaleID,											--SaleID
												   @SaleItemID,										--SaleItemID
												   0,												--CheckforRestrictionOnly
												   @TicketAccountOwner								--ReservationorTicketAccount	

				--   Performance Test     with Reservation Owner    @TicketAccountOwner              --@RestrictionType = 2
				exec otn_sp_GetAccountRestrictions @ReservationAccountID,							--AccountID
				                                   @MatrixCellID,									--MatrixCellID
												   @PerformanceID,									--PerformanceID
												   @EventID,										--EventID
												   @Quantity,										--Quantity
												   2,												--RestrictionType
												   @SaleID,											--SaleID
												   @SaleItemID,										--SaleItemID
												   0,												--CheckforRestrictionOnly
												   @ReservationAccountOwner								--ReservationorTicketAccount	









			FETCH NEXT FROM SaleItem_Cursor INTO
								@ReservationAccountID, 
								@B2BAccountID,
								@MatrixCellID,
								@Quantity,
								@PerformanceID,
								@EventID,
								@TicketAccountID,
								@SaleID,
								@SaleItemID
			end
			CLOSE SaleItem_Cursor;
			DEALLOCATE SaleItem_Cursor;
		END
	end
end</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>ALTER TABLE [dbo].[DATA_Sale] ENABLE TRIGGER [data_sale_SalesRestriction]</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>2988</SQLVERSION><RMTRACKLINK>86163</RMTRACKLINK><REASON>Added new field to ADM_AccessPoint: IgnoreFailedUsages</REASON><TABLENAMES>ADM_AccessPoint=WorkstationId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
           WHERE Name = N'IgnoreFailedUsages' AND
           Object_ID  = Object_ID(N'ADM_AccessPoint'))
BEGIN
  ALTER TABLE ADM_AccessPoint 
  ADD IgnoreFailedUsages Smallint NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2987</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.27.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2986</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2985</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2984</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2983</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2982</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2981</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2980</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2979</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2978</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2977</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2976</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2975</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2974</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2973</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2972</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2971</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2970</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2969</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2968</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2967</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2966</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2965</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2964</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2963</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2962</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2961</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2960</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2959</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2958</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2957</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2956</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2955</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2954</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2953</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2952</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2951</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2950</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2949</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2948</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2947</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2946</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2945</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2944</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2943</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2942</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2941</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2940</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2939</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2938</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2937</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2936</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2935</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2934</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2933</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2932</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2931</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2930</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2929</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2928</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2927</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2926</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2925</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2924</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2923</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2922</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2921</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2920</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2919</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2918</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2917</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2916</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2915</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2914</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2913</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2912</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2911</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2910</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2909</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2908</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2907</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2906</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2905</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2904</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2903</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2902</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2901</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2900</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2899</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2898</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2897</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2896</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2895</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2894</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2893</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2892</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2891</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2890</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2889</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2888</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.27.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>2887</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES>CNF_AccountRestriction2Account=AccountRestriction2AccountId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'CNF_AccountRestriction2Account'))
BEGIN
		DROP TABLE CNF_AccountRestriction2Account
END
BEGIN                    
   CREATE TABLE [dbo].[CNF_AccountRestriction2Account](
			[AccountRestriction2AccountId] [int] IDENTITY(1,1) NOT NULL,
			[AccountRestrictionId] [int] NOT NULL,
                        [DMGCategoryID] [int] NULL,
			[AccountId] [int] NULL,
			[Last_UserId_Log] [int] NULL,
			[Last_WorkstationId_Log] [int] NULL,
			[Last_DateTime_Log] [datetime] NULL
     )

END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dchen</ADDEDBY><SQLVERSION>2886</SQLVERSION><RMTRACKLINK>85336</RMTRACKLINK><REASON>Creating fields to persist information of the origin of the performance.</REASON><TABLENAMES>DATA_SaleItem2Performance=SaleItem2PerformanceId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
WHERE Name = N'MovedOnUpgrade' AND OBJECT_ID = OBJECT_ID(N'DATA_SaleItem2Performance'))
BEGIN
  ALTER TABLE DATA_SaleItem2Performance ADD MovedOnUpgrade SMALLINT 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
WHERE Name = N'MandatoryMove' AND OBJECT_ID = OBJECT_ID(N'DATA_SaleItem2Performance'))
BEGIN
  ALTER TABLE DATA_SaleItem2Performance ADD MandatoryMove SMALLINT 
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dchen</ADDEDBY><SQLVERSION>2885</SQLVERSION><RMTRACKLINK>81224</RMTRACKLINK><REASON>removing not null restrain.</REASON><TABLENAMES>DATA_AccountFinancial=AccountId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT * FROM sys.columns
WHERE Name = N'SendEmailOnThresholdLimit' AND OBJECT_ID = OBJECT_ID(N'DATA_AccountFinancial'))
BEGIN
  ALTER TABLE DATA_AccountFinancial alter column SendEmailOnThresholdLimit smallint null;
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT * FROM sys.columns
WHERE Name = N'ThresholdLimitAmount' AND OBJECT_ID = OBJECT_ID(N'DATA_AccountFinancial'))
BEGIN
  ALTER TABLE DATA_AccountFinancial alter column ThresholdLimitAmount float null;
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>2884</SQLVERSION><RMTRACKLINK>85191</RMTRACKLINK><REASON></REASON><TABLENAMES>CNF_AccountRestriction2Performance=AccountRestriction2PerformanceId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'CNF_AccountRestriction2Performance'))
BEGIN
		DROP TABLE CNF_AccountRestriction2Performance
END
BEGIN                    
	CREATE TABLE [dbo].[CNF_AccountRestriction2Performance](
		[AccountRestriction2PerformanceId] [int] IDENTITY(1,1) NOT NULL,
		[AccountRestrictionId] [int] NOT NULL,
		[Eventid] [int] NULL,
		[PerformanceId] [int] NULL,
		[Last_UserId_Log] [int] NULL,
		[Last_WorkstationId_Log] [int] NULL,
		[Last_DateTime_Log] [datetime] NULL
	)
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>2883</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES>CNF_AccountRestriction2MatrixCell=AccountRestriction2MatrixCellId
CNF_AccountRestriction2Account=AccountRestriction2AccountId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'CNF_AccountRestriction2MatrixCell'))
BEGIN
		DROP TABLE CNF_AccountRestriction2MatrixCell
END
BEGIN                    
   CREATE TABLE [dbo].[CNF_AccountRestriction2MatrixCell](
			[AccountRestriction2MatrixCellId] [int] IDENTITY(1,1) NOT NULL,
			[AccountRestrictionId] [int] NOT NULL,
			[MatrixCellId] [int] NOT NULL,
			[Last_UserId_Log] [int] NULL,
			[Last_WorkstationId_Log] [int] NULL,
			[Last_DateTime_Log] [datetime] NULL
     )

END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'CNF_AccountRestriction2Account'))
BEGIN
		DROP TABLE CNF_AccountRestriction2Account
END
BEGIN                    
   CREATE TABLE [dbo].[CNF_AccountRestriction2Account](
			[AccountRestriction2AccountId] [int] IDENTITY(1,1) NOT NULL,
			[AccountRestrictionId] [int] NOT NULL,
			[AccountId] [int] NOT NULL,
			[Last_UserId_Log] [int] NULL,
			[Last_WorkstationId_Log] [int] NULL,
			[Last_DateTime_Log] [datetime] NULL
     )

END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>2882</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>New Sales REstrictions
Data Structure</REASON><TABLENAMES>CNF_AccountRestriction=AccountRestrictionId
CNF_AccountRestriction2MatrixCell=AccountRestriction2MatrixCellId
CNF_AccountRestriction2Account=AccountRestriction2AccountId
DATA_AccountLimit=AccountLimitDataId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'CNF_AccountRestriction'))
BEGIN
		DROP TABLE CNF_AccountRestriction
END
BEGIN                    
   CREATE TABLE [dbo].[CNF_AccountRestriction](
			[AccountRestrictionId] [int] IDENTITY(1,1) NOT NULL,
			[StartDateTime] [datetime] NULL,
			[EndDateTime] [datetime] NULL,
			[Enabled] [smallint] NOT NULL,
			[Description] [nvarchar](100) NULL,
			[RestrictionType] [smallint] NOT NULL,
			[ReservationAccountLimit] [int] NULL,
			[TicketAccountLimit] [int] NULL,
			[PerDayLimit] [int] NULL,
			[PerWeekLimit] [int] NULL,
			[PerMonthLimit] [int] NULL,
			[PerYearLimit] [int] NULL,
			[Last_UserId_Log] [int] NULL,
			[Last_WorkstationId_Log] [int] NULL,
			[Last_DateTime_Log] [datetime] NULL
     )

END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'CNF_AccountRestriction2MatrixCell'))
BEGIN
		DROP TABLE CNF_AccountRestriction2MatrixCell
END
BEGIN                    
   CREATE TABLE [dbo].[CNF_AccountRestriction2MatrixCell](
			[AccountRestriction2MatrixCellId] [int] IDENTITY(1,1) NOT NULL,
			[AccountRestrictionId] [int] NOT NULL,
			[MatrixCellId] [int] NOT NULL,
			[Last_UserId_Log] [int] NULL,
			[Last_WorkstationId_Log] [int] NULL,
			[Last_DateTime_Log] [datetime] NULL
     )

END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'CNF_AccountRestriction2Account'))
BEGIN
		DROP TABLE CNF_AccountRestriction2Account
END
BEGIN                    
   CREATE TABLE [dbo].[CNF_AccountRestriction2Account](
			[AccountRestriction2AccountId] [int] IDENTITY(1,1) NOT NULL,
			[AccountRestrictionId] [int] NOT NULL,
			[AccountId] [int] NOT NULL,
			[Last_UserId_Log] [int] NULL,
			[Last_WorkstationId_Log] [int] NULL,
			[Last_DateTime_Log] [datetime] NULL
     )

END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT> IF (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'DATA_AccountLimit'))
BEGIN
		DROP TABLE DATA_AccountLimit
END
BEGIN                    
   CREATE TABLE [dbo].DATA_AccountLimit(
			[AccountLimitDataId] [int] IDENTITY(1,1) NOT NULL,
			[AccountRestrictionId] [int] NOT NULL,
			[RestrictionType] [smallint] NOT NULL,			
			[AccountId] [int] NOT NULL,
			[SaleId] [int] NULL,
			[SaleItemId] [int] NULL,
			[PerformanceId] [int] NULL,			
			[SaleDate] [datetime] NULL,
			[ReservationAccountQuantity] [int] NULL,
			[TicketAccountQuantity] [int] NULL

     )

END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dchen</ADDEDBY><SQLVERSION>2881</SQLVERSION><RMTRACKLINK>81224</RMTRACKLINK><REASON>Creating fields:
  * SendEmailOnThresholdLimit
  * ThresholdLimitAmount</REASON><TABLENAMES>DATA_AccountFinancial=AccountId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
WHERE Name = N'SendEmailOnThresholdLimit' AND OBJECT_ID = OBJECT_ID(N'DATA_AccountFinancial'))
BEGIN
  ALTER TABLE DATA_AccountFinancial ADD SendEmailOnThresholdLimit SMALLINT DEFAULT 0 NOT NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
WHERE Name = N'ThresholdLimitAmount' AND OBJECT_ID = OBJECT_ID(N'DATA_AccountFinancial'))
BEGIN
  ALTER TABLE DATA_AccountFinancial ADD ThresholdLimitAmount FLOAT DEFAULT 0 NOT NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>FABRY</ADDEDBY><SQLVERSION>2880</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>Adding some index
[0] Add Index on DATA_Ticket - ExternalReferenceId</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (	SELECT object_id 
		FROM sys.indexes
		WHERE Name = 'IDX_DATA_Ticket_ExternalReferenceId')
BEGIN
  CREATE NONCLUSTERED INDEX [IDX_DATA_Ticket_ExternalReferenceId]
  ON [dbo].[DATA_Ticket] ([ExternalReferenceId])
  INCLUDE ([TicketId])
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>pdalben</ADDEDBY><SQLVERSION>2879</SQLVERSION><RMTRACKLINK>IDBOS-996</RMTRACKLINK><REASON>Expanded  DATA_Note.Note to max val</REASON><TABLENAMES>DATA_Note=NoteId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
           WHERE Name = N'Note' AND
           Object_ID  = Object_ID(N'DATA_Note'))
BEGIN
  ALTER TABLE DATA_Note ALTER COLUMN [Note] nvarchar(max) NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>FABRY</ADDEDBY><SQLVERSION>2878</SQLVERSION><RMTRACKLINK>84734</RMTRACKLINK><REASON>Add new field on SIAE_System in order to choose which type for output file (Riepiloghi)
0 - Add OutputFileType smaillint

</REASON><TABLENAMES>SIAE_System=SystemId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
WHERE Name = N'OutputFileType' AND OBJECT_ID = OBJECT_ID(N'SIAE_System'))
BEGIN
  ALTER TABLE SIAE_System ADD OutputFileType smallint Default 0 NOT NULL
END

</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2877</SQLVERSION><RMTRACKLINK>81130</RMTRACKLINK><REASON>Adding some indexes
[0] Add Index on DATA_Transaction
[1] Add Index on DATA_PaymentCredit</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (	SELECT object_id 
		FROM sys.indexes
		WHERE Name = 'IDX_DATA_Transaction_WksID_C_Include')
BEGIN
  CREATE NONCLUSTERED INDEX IDX_DATA_Transaction_WksID_C_Include
  ON DATA_Transaction (WorkstationId, Completed)
  INCLUDE (TransactionId, SaleId)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (	SELECT object_id 
		FROM sys.indexes
		WHERE Name = 'IDX_DATA_PaymentCredit_AccountID_Include')
BEGIN
  CREATE NONCLUSTERED INDEX IDX_DATA_PaymentCredit_AccountID_Include
  ON DATA_PaymentCredit (AccountId)
  INCLUDE (PaymentId)
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>scoluccia</ADDEDBY><SQLVERSION>2876</SQLVERSION><RMTRACKLINK>IDBOS-1018</RMTRACKLINK><REASON>I have to run this DROP statemenet because I already creted the function with the patch 2868 with a wrong name before ovwTools was ready, now this function is created with ovwtools
so I Renamed the DB function otn_f_IsPromotionCalendarValid in otn_fn_IsPromotionCalendarValid in order to respect the function name prefix</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM   sys.objects
                WHERE  object_id = OBJECT_ID(N'[dbo].[otn_f_IsPromotionCalendarValid]') AND
                       type IN ( N'FN', N'IF', N'TF', N'FS', N'FT' ))
  DROP FUNCTION [dbo].[otn_f_IsPromotionCalendarValid]</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dchen</ADDEDBY><SQLVERSION>2875</SQLVERSION><RMTRACKLINK>79187</RMTRACKLINK><REASON>Need to add a new right to allow Void Usage

*Add field UpgradeRemoveUsage  </REASON><TABLENAMES>CNF_MatrixCellInfo=MatrixCellInfoId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
WHERE Name = N'UpgradeRemoveUsage' AND OBJECT_ID = OBJECT_ID(N'CNF_MatrixCellInfo'))
BEGIN
  ALTER TABLE CNF_MatrixCellInfo ADD UpgradeRemoveUsage SmallInt NULL;
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fesposito</ADDEDBY><SQLVERSION>2874</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>Changing the column definistion for CNF_Promotion.Weight</REASON><TABLENAMES>CNF_Promotion=PromotionId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT * FROM sys.columns
WHERE Name = N'Weight' AND OBJECT_ID = OBJECT_ID(N'CNF_Promotion'))
BEGIN
  ALTER TABLE CNF_Promotion alter column Weight Int NULL;
END
</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2873</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>CNF_Performance New StartPreSale datetime
CNF_Performance New EndPreSale datetime
CNF_Performance New SeasonalOwnerBlock smallint</REASON><TABLENAMES>CNF_Performance=PerformanceId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
WHERE Name = N'StartPreSale' AND OBJECT_ID = OBJECT_ID(N'CNF_Performance'))
BEGIN
  ALTER TABLE CNF_Performance ADD StartPreSale datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
WHERE Name = N'EndPreSale' AND OBJECT_ID = OBJECT_ID(N'CNF_Performance'))
BEGIN
  ALTER TABLE CNF_Performance ADD EndPreSale datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
WHERE Name = N'SeasonalOwnerBlock' AND OBJECT_ID = OBJECT_ID(N'CNF_Performance'))
BEGIN
  ALTER TABLE CNF_Performance ADD SeasonalOwnerBlock smallint NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>pchen</ADDEDBY><SQLVERSION>2872</SQLVERSION><RMTRACKLINK>83175</RMTRACKLINK><REASON>update the Enabled field to 1</REASON><TABLENAMES>ADM_AccessConfiguration=AccessConfigurationId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT * FROM sys.columns
WHERE Name = N'Enabled' AND OBJECT_ID = OBJECT_ID(N'ADM_AccessConfiguration'))
BEGIN
  UPDATE ADM_AccessConfiguration SET Enabled=1
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>pchen</ADDEDBY><SQLVERSION>2871</SQLVERSION><RMTRACKLINK>83175</RMTRACKLINK><REASON>New colum in ADM_AccessConfiguration: Enabled</REASON><TABLENAMES>ADM_AccessConfiguration=AccessConfigurationId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
WHERE Name = N'Enabled' AND OBJECT_ID = OBJECT_ID(N'ADM_AccessConfiguration'))
BEGIN
  ALTER TABLE ADM_AccessConfiguration ADD Enabled Smallint
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>scoluccia</ADDEDBY><SQLVERSION>2870</SQLVERSION><RMTRACKLINK>906</RMTRACKLINK><REASON>New colum in DATA_Biometric: BiometricType</REASON><TABLENAMES>DATA_Biometric=BiometricId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
WHERE Name = N'BiometricType' AND OBJECT_ID = OBJECT_ID(N'DATA_Biometric'))
BEGIN
  ALTER TABLE DATA_Biometric ADD BiometricType Smallint Default 0 NOT NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>2869</SQLVERSION><RMTRACKLINK>85784</RMTRACKLINK><REASON>2 new columns in CNF_MatrixCellInfo: SaleThreshold, SaleThresholdOffset</REASON><TABLENAMES>CNF_MatrixCellInfo=MatrixCellInfoId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'SaleThreshold' AND
                Object_ID  = Object_ID(N'CNF_MatrixCellInfo'))
BEGIN
  ALTER TABLE CNF_MatrixCellInfo
  ADD SaleThreshold Smallint NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'SaleThresholdOffset' AND
                Object_ID  = Object_ID(N'CNF_MatrixCellInfo'))
BEGIN
  ALTER TABLE CNF_MatrixCellInfo
  ADD SaleThresholdOffset Smallint NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>scoluccia</ADDEDBY><SQLVERSION>2868</SQLVERSION><RMTRACKLINK>IDBOS-1018</RMTRACKLINK><REASON>Add new DB function dbo.otn_f_IsPromotionCalendarValid</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT (EXISTS (SELECT * FROM   sys.objects 
                WHERE  object_id = OBJECT_ID(N'[dbo].[otn_f_IsPromotionCalendarValid]') AND 
                       type IN ( N'FN', N'IF', N'TF', N'FS', N'FT' )))
BEGIN
 EXEC('
  CREATE FUNCTION [dbo].[otn_f_IsPromotionCalendarValid](@PromotionId int)
  /* Input param:  PromotionID
     Output param: 1 = promotion valid
           0 = promotion not valid
   */
  RETURNS int
  AS
  BEGIN
    DECLARE @ret int
    IF NOT EXISTS (SELECT PromotionId FROM CNF_PromotionValidity WITH(NOLOCK) WHERE PromotionId = @PromotionId)
    BEGIN
      set @ret = 1     /* If not specified the validity the promotion is valid */
    END
    ELSE
    BEGIN
      set @ret = 0
      DECLARE @PromId as int;
      SET @PromId = 0;
      DECLARE my_cursor CURSOR FOR
              SELECT PromotionId FROM CNF_PromotionValidity WITH(NOLOCK)
                     WHERE PromotionId = @PromotionId AND
                           CAST( GETDATE() AS DATE) BETWEEN CAST(ISNULL(FromDate, GETDATE()) AS DATE) AND
                           CAST(ISNULL(ToDate, GETDATE()) AS DATE) AND
                           CAST( GETDATE() AS TIME) BETWEEN CAST(ISNULL(FromTime, GETDATE()) AS TIME) AND
                           CAST(ISNULL(ToTime, GETDATE()) AS TIME)
      OPEN my_cursor;

      FETCH NEXT FROM my_cursor INTO @PromId;

      WHILE @@FETCH_STATUS = 0
      BEGIN
        IF @PromId IS NOT NULL
        BEGIN
          set @ret = 1			/* if return the promotionId it means that the validity is ok*/
          GOTO EndLoop
        END
        FETCH NEXT FROM my_cursor INTO @PromId;
      END

      EndLoop:
      CLOSE my_cursor;
      DEALLOCATE my_cursor;
    END

    RETURN @ret;
  END')

END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>2867</SQLVERSION><RMTRACKLINK>85768</RMTRACKLINK><REASON>New colum in CNF_MatrixCellInfo: DuplicateTicketOnVoid</REASON><TABLENAMES>CNF_MatrixCellInfo=MatrixCellInfoId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'DuplicateTicketOnVoid' AND
                Object_ID  = Object_ID(N'CNF_MatrixCellInfo'))
BEGIN
  ALTER TABLE CNF_MatrixCellInfo
  ADD DuplicateTicketOnVoid Smallint NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>aeaton</ADDEDBY><SQLVERSION>2866</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES>CNF_Promotion=PromotionId
CNF_StatisticalGroup2Promotion=StatisticalGroup2PromotionId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Weight' AND
                Object_ID  = Object_ID(N'CNF_Promotion'))
BEGIN
  ALTER TABLE CNF_Promotion
  ADD Weight int NOT NULL DEFAULT((0)) 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'CNF_StatisticalGroup2Promotion'))
                    
BEGIN
	Create table CNF_StatisticalGroup2Promotion
	(
		[StatisticalGroup2PromotionId] Integer Identity(1,1) NOT NULL,
		[PromotionId] Integer NOT NULL,
		[StatisticalGroupId] Integer NOT NULL,
		[Last_UserId_Log] Integer,
		[Last_WorkstationId_Log] Integer,
		[Last_DateTime_Log] Datetime,
	Primary Key ([StatisticalGroup2PromotionId])
	) 

END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_CNF_StatisticalGroup2Promotion_StatisticalGroupId')
BEGIN                                                                              
  ALTER TABLE [CNF_StatisticalGroup2Promotion] WITH CHECK ADD CONSTRAINT [FK_CNF_StatisticalGroup2Promotion_StatisticalGroupId] FOREIGN KEY([StatisticalGroupId])
  REFERENCES [CNF_StatisticalGroup] ([StatisticalGroupId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_CNF_StatisticalGroup2Promotion_PromotionId')
BEGIN                                                                              
  ALTER TABLE [CNF_StatisticalGroup2Promotion] WITH CHECK ADD CONSTRAINT [FK_CNF_StatisticalGroup2Promotion_PromotionId] FOREIGN KEY([PromotionId])
  REFERENCES [CNF_Promotion] ([PromotionId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_CNF_StatisticalGroup2Promotion_Last_UserId_Log')
BEGIN                                                                              
  ALTER TABLE [CNF_StatisticalGroup2Promotion] WITH CHECK ADD CONSTRAINT [FK_CNF_StatisticalGroup2Promotion_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log])
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_CNF_StatisticalGroup2Promotion_Last_WorkstationId_Log')
BEGIN                                                                              
  ALTER TABLE [CNF_StatisticalGroup2Promotion] WITH CHECK ADD CONSTRAINT [FK_CNF_StatisticalGroup2Promotion_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log])
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fesposito</ADDEDBY><SQLVERSION>2865</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>===== Mixed Transaction =====
Adding the ItemTransactionType into SaleItem and TransactionItem to persist the operation with the item.</REASON><TABLENAMES>DATA_SaleItem=SaleItemId
DATA_TransactionItem=ItemId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
            WHERE Name = N'OperationType' AND
        Object_ID  = Object_ID(N'DATA_SaleItem'))
BEGIN
  ALTER TABLE DATA_SaleItem
  DROP COLUMN OperationType 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'ItemTransactionType' AND
                Object_ID  = Object_ID(N'DATA_SaleItem'))
BEGIN
  ALTER TABLE DATA_SaleItem
  ADD ItemTransactionType smallint null 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'ItemTransactionType' AND
                Object_ID  = Object_ID(N'DATA_TransactionItem'))
BEGIN
  ALTER TABLE DATA_TransactionItem
  ADD ItemTransactionType smallint null 
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dchen</ADDEDBY><SQLVERSION>2864</SQLVERSION><RMTRACKLINK>85681</RMTRACKLINK><REASON>// Need to be able to set Down Payment as first payment for Installment Billing Renewals

We discussed adding a new field to the database to separate out the Down Payment Financed Amount. This way, it can be included in the Financed Amount shown on the screen, but we can have this field for reporting that shows of the Financed Amount how much is from the Down Payment and how much is the First Payment.</REASON><TABLENAMES>DATA_PaymentFlex=PaymentId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
WHERE Name = N'FinancedDownPayment' AND OBJECT_ID = OBJECT_ID(N'DATA_PaymentFlex'))
BEGIN
  ALTER TABLE DATA_PaymentFlex ADD FinancedDownPayment float NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dapicella</ADDEDBY><SQLVERSION>2863</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES>CNF_PerformanceCategoryValidity=PerfCatValidityId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
WHERE Name = N'SubscriptionId' AND OBJECT_ID = OBJECT_ID(N'CNF_PerformanceCategoryValidity'))
BEGIN
  ALTER TABLE CNF_PerformanceCategoryValidity ADD SubscriptionId int NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_CNF_PerformanceCategoryValidity_SubscriptionId')
BEGIN                                                                              
  ALTER TABLE [CNF_PerformanceCategoryValidity] WITH CHECK ADD CONSTRAINT [FK_CNF_PerformanceCategoryValidity_SubscriptionId] FOREIGN KEY([SubscriptionId])
  REFERENCES [CNF_Subscription] ([SubscriptionId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>ALTER TABLE CNF_PerformanceCategoryValidity CHECK CONSTRAINT [FK_CNF_PerformanceCategoryValidity_SubscriptionId]</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fdipalma</ADDEDBY><SQLVERSION>2862</SQLVERSION><RMTRACKLINK>85595</RMTRACKLINK><REASON>GDL Club - Feedback</REASON><TABLENAMES>DATA_RenewalPlanDetails=RenewalPlanDetailsId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF (EXISTS(SELECT * FROM sys.columns
WHERE Name = N'MaxAttemptCount' AND OBJECT_ID = OBJECT_ID(N'DATA_RenewalPlanDetails'))) and
(not EXISTS(SELECT * FROM sys.columns
WHERE Name = N'AttemptCount' AND OBJECT_ID = OBJECT_ID(N'DATA_RenewalPlanDetails')))
BEGIN
  exec sp_rename 'DATA_RenewalPlanDetails.MaxAttemptCount' , 'AttemptCount', 'COLUMN'
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fdipalma</ADDEDBY><SQLVERSION>2861</SQLVERSION><RMTRACKLINK>85595</RMTRACKLINK><REASON>GDL Club - Feedback</REASON><TABLENAMES>DATA_RenewalPlanDetails=RenewalPlanDetailsId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF (NOT EXISTS(SELECT * FROM sys.columns
WHERE Name = N'MaxAttemptCount' AND OBJECT_ID = OBJECT_ID(N'DATA_RenewalPlanDetails'))) AND
(NOT EXISTS(SELECT * FROM sys.columns
WHERE Name = N'AttemptCount' AND OBJECT_ID = OBJECT_ID(N'DATA_RenewalPlanDetails'))) 
BEGIN
  ALTER TABLE DATA_RenewalPlanDetails ADD MaxAttemptCount Smallint Default 0 NOT NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
WHERE Name = N'LastAttemptDate' AND OBJECT_ID = OBJECT_ID(N'DATA_RenewalPlanDetails'))
BEGIN
  ALTER TABLE DATA_RenewalPlanDetails ADD LastAttemptDate DateTime NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fdipalma</ADDEDBY><SQLVERSION>2860</SQLVERSION><RMTRACKLINK>85595</RMTRACKLINK><REASON>GDL Club - Feedback</REASON><TABLENAMES>CNF_RenewalContract=RenewalContractId
DATA_RenewalPlan=RenewalPlanId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
WHERE Name = N'MaxAttemptCount' AND OBJECT_ID = OBJECT_ID(N'CNF_RenewalContract'))
BEGIN
  ALTER TABLE CNF_RenewalContract ADD MaxAttemptCount Smallint Default 0 NOT NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
WHERE Name = N'MaxAttemptCount' AND OBJECT_ID = OBJECT_ID(N'DATA_RenewalPlan'))
BEGIN
  ALTER TABLE DATA_RenewalPlan ADD MaxAttemptCount Smallint Default 0 NOT NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>2859</SQLVERSION><RMTRACKLINK>81277</RMTRACKLINK><REASON>Added new field to DATA_UserLog: WebServicePath</REASON><TABLENAMES>DATA_UserLog=LogID</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'WebServicePath' AND
                Object_ID  = Object_ID(N'DATA_UserLog'))
BEGIN
  ALTER TABLE DATA_UserLog
  ADD WebServicePath Nvarchar(100) null 
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dchen</ADDEDBY><SQLVERSION>2858</SQLVERSION><RMTRACKLINK>77508</RMTRACKLINK><REASON>===== Mixed Transaction =====
Adding the Operation Type into SaleItem to persist the operation with the item.</REASON><TABLENAMES>DATA_SaleItem=SaleItemId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'OperationType' AND
                Object_ID  = Object_ID(N'DATA_SaleItem'))
BEGIN
  ALTER TABLE DATA_SaleItem
  ADD OperationType nvarchar(10) null 
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>2857</SQLVERSION><RMTRACKLINK>85352</RMTRACKLINK><REASON>Changed StrValue from not null to null
Flipped values of data control rights set to 2 and 4

12/10/2022 Davide Stornaiuolo :
For the Script1 I removed this SQL Statement because there
was an error during the update of  a customer DB.
IF EXISTS ( SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND  TABLE_NAME = 'DATA_Right' ) 
BEGIN
   ALTER Table DATA_Right
   ALTER Column StrValue Nvarchar(200) NULL
END

In script 3054 this Column will be updated to 500...</REASON><TABLENAMES>DATA_Right=DataRightId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS ( SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND  TABLE_NAME = 'DATA_Right' ) 
BEGIN

  UPDATE DATA_Right 
  SET StrValue = '5' 
  FROM DATA_Right 
  INNER JOIN CNF_Right CR ON CR.RightId = DATA_Right.RightId 
  WHERE CR.DataType = 18 AND StrValue = '4'
  
  UPDATE DATA_Right 
  SET StrValue = '4' 
  FROM DATA_Right 
  INNER JOIN CNF_Right CR ON CR.RightId = DATA_Right.RightId 
  WHERE CR.DataType = 18 AND StrValue = '2'
  
  UPDATE DATA_Right 
  SET StrValue = '2' 
  FROM DATA_Right 
  INNER JOIN CNF_Right CR ON CR.RightId = DATA_Right.RightId 
  WHERE CR.DataType = 18 AND StrValue = '5'
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>SELECT 1</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2856</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2855</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2854</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2853</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2852</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2851</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2850</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2849</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2848</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2847</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2846</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2845</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2844</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2843</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2842</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2841</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2840</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2839</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2838</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2837</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2836</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2835</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2834</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2833</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2832</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2831</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2830</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2829</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2828</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2827</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2826</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2825</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2824</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2823</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2822</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2821</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2820</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2819</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2818</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2817</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2816</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2815</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2814</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2813</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2812</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2811</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2810</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2809</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2808</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2807</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2806</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2805</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2804</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2803</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2802</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2801</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2800</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2799</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2798</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2797</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2796</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2795</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2794</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2793</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2792</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2791</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2790</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2789</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2788</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2787</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2786</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2785</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2784</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2783</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2782</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2781</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2780</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2779</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2778</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2777</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2776</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2775</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2774</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2773</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2772</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2771</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2770</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2769</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2768</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2767</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2766</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2765</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2764</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2763</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2762</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2761</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2760</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2759</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2758</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2757</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fdipalma</ADDEDBY><SQLVERSION>2756</SQLVERSION><RMTRACKLINK>83374</RMTRACKLINK><REASON>GDL Club - Renewal Task</REASON><TABLENAMES>DATA_AccountCardOnFile=AccountCardOnFileId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
WHERE Name = N'CardName' AND OBJECT_ID = OBJECT_ID(N'DATA_AccountCardOnFile'))
BEGIN
  ALTER TABLE DATA_AccountCardOnFile ADD CardName Nvarchar(50) NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
WHERE Name = N'CardNumber' AND OBJECT_ID = OBJECT_ID(N'DATA_AccountCardOnFile'))
BEGIN
  ALTER TABLE DATA_AccountCardOnFile ADD CardNumber Nvarchar(20) NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
WHERE Name = N'Expiration' AND OBJECT_ID = OBJECT_ID(N'DATA_AccountCardOnFile'))
BEGIN
  ALTER TABLE DATA_AccountCardOnFile ADD Expiration Nvarchar(7) NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
WHERE Name = N'HolderName' AND OBJECT_ID = OBJECT_ID(N'DATA_AccountCardOnFile'))
BEGIN
  ALTER TABLE DATA_AccountCardOnFile ADD HolderName Nvarchar(100) NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>pchen</ADDEDBY><SQLVERSION>2755</SQLVERSION><RMTRACKLINK>83554</RMTRACKLINK><REASON>Append a new field IsDefault in CNF_ExternalMediaType</REASON><TABLENAMES>CNF_ExternalMediaType=ExternalMediaTypeId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'IsDefault' AND
                Object_ID  = Object_ID(N'CNF_ExternalMediaType'))
BEGIN
  Alter Table CNF_ExternalMediaType
  Add IsDefault Smallint NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>2754</SQLVERSION><RMTRACKLINK>84666</RMTRACKLINK><REASON>Deleted 2 tables: TPR_CNF_Group, TPR_DATA_MediaIdentifier</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS ( SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND  TABLE_NAME = 'TPR_DATA_MediaIdentifier' )

BEGIN
   DROP TABLE TPR_DATA_MediaIdentifier
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS ( SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND  TABLE_NAME = 'TPR_CNF_Group' )

BEGIN
   DROP TABLE TPR_CNF_Group
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>2753</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>85253 - Deleting table DATA_Seat and all the reference to it</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS ( SELECT * 
                FROM INFORMATION_SCHEMA.TABLES 
                WHERE TABLE_SCHEMA = 'dbo' 
	        AND TABLE_NAME = 'DATA_SEAT')
BEGIN
    DROP TABLE data_seat;
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_ui_DATA_Seat_delete]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_ui_DATA_Seat_delete</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_ui_DATA_Seat_update]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_ui_DATA_Seat_update</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2752</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES>DATA_SpaceStructureQuota=SpaceStructureQuotaId
DATA_SpaceStructureCounter=SpaceStructureCounterId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS ( SELECT * 
                FROM INFORMATION_SCHEMA.TABLES 
                WHERE TABLE_SCHEMA = 'dbo' 
	        AND TABLE_NAME = 'DATA_SpaceStructureQuota')
BEGIN
CREATE TABLE [dbo].[DATA_SpaceStructureQuota](
	[SpaceStructureQuotaId] [int] IDENTITY(1,1) NOT NULL,
	[SpaceStructureId] [int] NULL,
	[PerformanceId] [int] NULL,
	[DmgCategoryId] [int] NULL,
	[Quota] [int] NULL,
	[Counter] [int] NULL,
PRIMARY KEY CLUSTERED 
(
	[SpaceStructureQuotaId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END </SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS ( SELECT * 
                FROM INFORMATION_SCHEMA.TABLES 
                WHERE TABLE_SCHEMA = 'dbo' 
	        AND TABLE_NAME = 'DATA_SpaceStructureCounter')
BEGIN
create TABLE [dbo].[DATA_SpaceStructureCounter](
	[SpaceStructureCounterId] [int] IDENTITY(1,1) NOT NULL,
	[SpaceStructureQuotaId] [int] NULL,
	[AccountId] [int] NULL,
	[SpaceStructureId] [int] NULL,
	[Counter] [int] NULL,
PRIMARY KEY CLUSTERED 
(
	[SpaceStructureCounterId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END </SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fdipalma</ADDEDBY><SQLVERSION>2751</SQLVERSION><RMTRACKLINK>83372</RMTRACKLINK><REASON>GDL Club - Season Pass Auto Renew</REASON><TABLENAMES>CNF_Scheduler=SchedulerId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
WHERE Name = N'CalendarId' AND OBJECT_ID = OBJECT_ID(N'CNF_Scheduler'))
BEGIN
  ALTER TABLE CNF_Scheduler ADD CalendarId Integer NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_CNF_Scheduler_CalendarId')
BEGIN                                                                              
  Alter table [CNF_Scheduler] add constraint FK_CNF_Scheduler_CalendarId foreign key([CalendarId]) references [CNF_Calendar] ([CalendarId])  on update no action on delete no action    
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fdipalma</ADDEDBY><SQLVERSION>2750</SQLVERSION><RMTRACKLINK>83372</RMTRACKLINK><REASON>GDL Club - Season Pass Auto Renew</REASON><TABLENAMES>CNF_RenewalContract=RenewalContractId
DATA_RenewalPlan=RenewalPlanId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
WHERE Name = N'TryBeforeDays' AND OBJECT_ID = OBJECT_ID(N'CNF_RenewalContract'))
BEGIN
  ALTER TABLE CNF_RenewalContract ADD TryBeforeDays Smallint Default 0 NOT NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
WHERE Name = N'TryBeforeDays' AND OBJECT_ID = OBJECT_ID(N'DATA_RenewalPlan'))
BEGIN
  ALTER TABLE DATA_RenewalPlan ADD TryBeforeDays Smallint Default 0 NOT NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>2749</SQLVERSION><RMTRACKLINK>79804</RMTRACKLINK><REASON>New field in DATA_TransactionItem: QuantityToPrint</REASON><TABLENAMES>DATA_TransactionItem=ItemId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'QuantityToPrint' AND
                Object_ID  = Object_ID(N'DATA_TransactionItem'))
BEGIN
  Alter Table DATA_TransactionItem
  Add QuantityToPrint Integer NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fdipalma</ADDEDBY><SQLVERSION>2748</SQLVERSION><RMTRACKLINK>83372</RMTRACKLINK><REASON>GDL Club - Season Pass Auto Renew</REASON><TABLENAMES>DATA_RenewalPlanDetails=RenewalPlanDetailsId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS ( SELECT * 
                FROM INFORMATION_SCHEMA.TABLES 
                WHERE TABLE_SCHEMA = 'dbo' 
	        AND TABLE_NAME = 'DATA_RenewalPlanDetails')
BEGIN
Create table [DATA_RenewalPlanDetails]
(
	[RenewalPlanDetailsId] Integer Identity(1,1) NOT NULL,
	[RenewalPlanId] Integer NOT NULL,
	[RenewalNumber] Smallint NOT NULL,
	[RenewalTransactionId] Integer NULL,
	[OriginalTicketId] Integer NULL,
	[OriginalMatrixCellId] Integer NOT NULL,
	[RenewalTicketId] Integer NULL,
	[RenewalMatrixCellId] Integer NOT NULL,
	[RenewalScheduledDate] Datetime NULL,
	[MandatoryRenewal] Smallint NOT NULL,
	[Status] Smallint NOT NULL,
	[Last_UserId_Log] Integer NULL,
	[Last_WorkstationId_Log] Integer NULL,
	[Last_DateTime_Log] Datetime NULL,
Primary Key ([RenewalPlanDetailsId])
) 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_DATA_RenewalPlanDetails_UserId')
BEGIN                                                                              
  Alter table [DATA_RenewalPlanDetails] add constraint FK_DATA_RenewalPlanDetails_UserId foreign key([Last_UserId_Log]) references [CNF_User] ([UserId])  on update no action on delete no action   
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_DATA_RenewalPlanDetails_WorkstationId')
BEGIN                                                                              
  Alter table [DATA_RenewalPlanDetails] add constraint FK_DATA_RenewalPlanDetails_WorkstationId foreign key([Last_WorkstationId_Log]) references [CNF_Workstation] ([WorkstationId])  on update no action on delete no action    
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_DATA_RenewalPlanDetails_TransactionId')
BEGIN                                                                              
  Alter table [DATA_RenewalPlanDetails] add constraint FK_DATA_RenewalPlanDetails_TransactionId foreign key([RenewalTransactionId]) references [DATA_Transaction] ([TransactionId])  on update no action on delete no action  
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_DATA_RenewalPlanDetails_RenewalPlanId')
BEGIN                                                                              
  Alter table [DATA_RenewalPlanDetails] add constraint FK_DATA_RenewalPlanDetails_RenewalPlanId foreign key([RenewalPlanId]) references [DATA_RenewalPlan] ([RenewalPlanId])  on update no action on delete no action   
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_DATA_RenewalPlanDetails_OriginalMatrixCellId')
BEGIN                                                                              
  Alter table [DATA_RenewalPlanDetails] add constraint FK_DATA_RenewalPlanDetails_OriginalMatrixCellId foreign key([OriginalMatrixCellId]) references [CNF_MatrixCell] ([MatrixCellId])  on update no action on delete no action    
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_DATA_RenewalPlanDetails_RenewalMatrixCellId')
BEGIN                                                                              
  Alter table [DATA_RenewalPlanDetails] add constraint FK_DATA_RenewalPlanDetails_RenewalMatrixCellId foreign key([RenewalMatrixCellId]) references [CNF_MatrixCell] ([MatrixCellId])  on update no action on delete no action    
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_DATA_RenewalPlanDetails_OriginalTicketId')
BEGIN                                                                              
  Alter table [DATA_RenewalPlanDetails] add constraint FK_DATA_RenewalPlanDetails_OriginalTicketId foreign key([OriginalTicketId]) references [DATA_Ticket] ([TicketId])  on update no action on delete no action     
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_DATA_RenewalPlanDetails_RenewalTicketId')
BEGIN                                                                              
  Alter table [DATA_RenewalPlanDetails] add constraint FK_DATA_RenewalPlanDetails_RenewalTicketId foreign key([RenewalTicketId]) references [DATA_Ticket] ([TicketId])  on update no action on delete no action     
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fdipalma</ADDEDBY><SQLVERSION>2747</SQLVERSION><RMTRACKLINK>83372</RMTRACKLINK><REASON>GDL Club - Season Pass Auto Renew</REASON><TABLENAMES>DATA_RenewalPlan=RenewalPlanId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS ( SELECT * 
                FROM INFORMATION_SCHEMA.TABLES 
                WHERE TABLE_SCHEMA = 'dbo' 
	        AND TABLE_NAME = 'DATA_RenewalPlan')
BEGIN
Create table [DATA_RenewalPlan]
(
	[RenewalPlanId] Integer Identity(1,1) NOT NULL,
	[RenewalPlanAK] Varchar(32) NOT NULL, UNIQUE ([RenewalPlanAK]),
	[RenewalContractId] Integer NOT NULL,
	[AccountId] Integer NOT NULL,
	[NumberMandatoryRenewal] Integer NOT NULL,
	[MandatoryRenewalOnly] Smallint NULL,
	[Status] Smallint NOT NULL,
	[ContractStartingDate] Datetime NULL,
	[ContractFilename] Nvarchar(100) NULL,
	[Last_UserId_Log] Integer NULL,
	[Last_WorkstationId_Log] Integer NULL,
	[Last_DateTime_Log] Datetime NULL,
Primary Key ([RenewalPlanId])
) 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_DATA_RenewalPlan_UserId')
BEGIN                                                                              
  Alter table [DATA_RenewalPlan] add constraint FK_DATA_RenewalPlan_UserId foreign key([Last_UserId_Log]) references [CNF_User] ([UserId])  on update no action on delete no action   
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_DATA_RenewalPlan_WorkstationId')
BEGIN                                                                              
  Alter table [DATA_RenewalPlan] add constraint FK_DATA_RenewalPlan_WorkstationId foreign key([Last_WorkstationId_Log]) references [CNF_Workstation] ([WorkstationId])  on update no action on delete no action    
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_DATA_RenewalPlan_AccountId')
BEGIN                                                                              
  Alter table [DATA_RenewalPlan] add constraint FK_DATA_RenewalPlan_AccountId foreign key([AccountId]) references [DATA_Account] ([AccountId])  on update no action on delete no action 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_DATA_RenewalPlan_RenewalContractId')
BEGIN                                                                              
  Alter table [DATA_RenewalPlan] add constraint FK_DATA_RenewalPlan_RenewalContractId foreign key([RenewalContractId]) references [CNF_RenewalContract] ([RenewalContractId])  on update no action on delete no action 
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fdipalma</ADDEDBY><SQLVERSION>2746</SQLVERSION><RMTRACKLINK>83372</RMTRACKLINK><REASON>Changing column name</REASON><TABLENAMES>CNF_RenewalContract=RenewalContractId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT * FROM sys.columns
WHERE Name = N'StardDate' AND OBJECT_ID = OBJECT_ID(N'CNF_RenewalContract'))
BEGIN
  exec sp_rename 'CNF_RenewalContract.StardDate' , 'StartDate', 'COLUMN'
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fdipalma</ADDEDBY><SQLVERSION>2745</SQLVERSION><RMTRACKLINK>83372</RMTRACKLINK><REASON>GDL Club - Season Pass Auto Renew</REASON><TABLENAMES>CNF_RenewalContract=RenewalContractId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS ( SELECT * 
                FROM INFORMATION_SCHEMA.TABLES 
                WHERE TABLE_SCHEMA = 'dbo' 
	        AND TABLE_NAME = 'CNF_RenewalContract')
BEGIN
Create table [CNF_RenewalContract]
(
	[RenewalContractId] Integer Identity(1,1) NOT NULL,
	[RenewalContractAK] Varchar(32) NOT NULL, UNIQUE ([RenewalContractAK]),
	[RenewalContractCode] Nvarchar(10) NOT NULL,
	[RenewalContractName] Nvarchar(50) NOT NULL,
	[Description] Nvarchar(4000) NULL,
	[NumberMandatoryRenewal] Integer NOT NULL,
	[MandatoryRenewalOnly] Smallint NULL,
	[Enabled] Smallint NOT NULL,
	[StartDate] Datetime NULL,
	[EndDate] Datetime NULL,
	[TermsAndConditions] Nvarchar(4000) NULL,
	[PreviewDocTemplateId] Integer NULL,
	[FinalDocTemplateId] Integer NULL,
	[Last_UserId_Log] Integer NULL,
	[Last_WorkstationId_Log] Integer NULL,
	[Last_DateTime_Log] Datetime NULL,
Primary Key ([RenewalContractId])
) 
END </SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_CNF_RenewalContract_PreviewDocTemplateId')
BEGIN                                                                              
  Alter table [CNF_RenewalContract] add constraint FK_CNF_RenewalContract_PreviewDocTemplateId foreign key([PreviewDocTemplateId]) references [CNF_DocTemplate] ([DocTemplateId])  on update no action on delete no action 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_CNF_RenewalContract_FinalDocTemplateId')
BEGIN                                                                              
  Alter table [CNF_RenewalContract] add constraint FK_CNF_RenewalContract_FinalDocTemplateId foreign key([FinalDocTemplateId]) references [CNF_DocTemplate] ([DocTemplateId])  on update no action on delete no action 
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_CNF_RenewalContract_UserId')
BEGIN                                                                              
  Alter table [CNF_RenewalContract] add constraint FK_CNF_RenewalContract_UserId foreign key([Last_UserId_Log]) references [CNF_User] ([UserId])  on update no action on delete no action   
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_CNF_RenewalContract_WorkstationId')
BEGIN                                                                              
  Alter table [CNF_RenewalContract] add constraint FK_CNF_RenewalContract_WorkstationId foreign key([Last_WorkstationId_Log]) references [CNF_Workstation] ([WorkstationId])  on update no action on delete no action    
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT * FROM sys.columns
WHERE Name = N'StardDate' AND OBJECT_ID = OBJECT_ID(N'CNF_RenewalContract'))
BEGIN
  exec sp_rename 'CNF_RenewalContract.StardDate' , 'StartDate', 'COLUMN'
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fdipalma</ADDEDBY><SQLVERSION>2744</SQLVERSION><RMTRACKLINK>83373</RMTRACKLINK><REASON>GDL Club - Card on File Management</REASON><TABLENAMES>DATA_AccountCardOnFile=AccountCardOnFileId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS ( SELECT * 
                FROM INFORMATION_SCHEMA.TABLES 
                WHERE TABLE_SCHEMA = 'dbo' 
	        AND TABLE_NAME = 'DATA_AccountCardOnFile')
BEGIN
Create table [DATA_AccountCardOnFile]
(
	[AccountCardOnFileId] Integer Identity(1,1) NOT NULL,
	[AccountId] Integer NOT NULL,
	[CardOnFileType] Smallint NOT NULL,
	[OrderOfPriority] Smallint NOT NULL,
	[StoredPaymentMethodId] Varchar(100) NULL,
	[Last_UserId_Log] Integer NULL,
	[Last_WorkstationId_Log] Integer NULL,
	[Last_DateTime_Log] Datetime NULL,
Primary Key ([AccountCardOnFileId])
) 
END </SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_DATA_AccountCardOnFile_AccountId')
BEGIN                                                                              
  Alter table [DATA_AccountCardOnFile] add constraint FK_DATA_AccountCardOnFile_AccountId foreign key([AccountId]) references [DATA_Account] ([AccountId])  on update no action on delete no action  
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_DATA_AccountCardOnFile_UserId')
BEGIN                                                                              
  Alter table [DATA_AccountCardOnFile] add constraint FK_DATA_AccountCardOnFile_UserId foreign key([Last_UserId_Log]) references [CNF_User] ([UserId])  on update no action on delete no action   
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_DATA_AccountCardOnFile_WorkstationId')
BEGIN                                                                              
  Alter table [DATA_AccountCardOnFile] add constraint FK_DATA_AccountCardOnFile_WorkstationId foreign key([Last_WorkstationId_Log]) references [CNF_Workstation] ([WorkstationId])  on update no action on delete no action    
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>lfornaroli</ADDEDBY><SQLVERSION>2743</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES>CNF_MatrixCellinfo=MatrixCellInfoId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Points' AND
                Object_ID  = Object_ID(N'CNF_MatrixCellInfo'))
BEGIN

alter table CNF_MatrixCellInfo
 add Points Integer NULL
 
END </SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>lfornaroli</ADDEDBY><SQLVERSION>2742</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>0: drop table CNF_LocationMatrix2Attribute
1: create table CNF_LocationMatrix2MatrixCell
3: create script</REASON><TABLENAMES>CNF_LocationMatrix2MatrixCell=LocMatrix2MatrixCellId
CNF_LocationMatrix=LocationMatrixId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>drop table CNF_LocationMatrix2Attribute</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT> Create table [CNF_LocationMatrix2MatrixCell]
(
	[LocMatrix2MatrixCellId] Integer Identity(1,1) NOT NULL,
	[MatrixCellId] Integer NOT NULL,
	[Last_UserId_Log] Integer NOT NULL,
	[Last_WorkstationId_Log] Integer NOT NULL,
	[LocationMatrixId] Integer NOT NULL,
	[Last_DateTime_Log] Datetime NULL,
Primary Key ([LocMatrix2MatrixCellId])
) 


</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>Create Index [Idx_LocMatrix2Attr_LocId_AttrId] ON [CNF_LocationMatrix2MatrixCell] ([LocationMatrixId] ) 
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT> alter table CNF_LocationMatrix
 add ParentLocationMatrixId Integer NULL</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>Alter table CNF_LocationMatrix 
  add  foreign key(ParentLocationMatrixId) references CNF_LocationMatrix (LocationMatrixId) </SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>Alter table CNF_LocationMatrix2MatrixCell 
  add  foreign key(MatrixCellId) references CNF_MatrixCell (MatrixCellId)  

</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2741</SQLVERSION><RMTRACKLINK>79002</RMTRACKLINK><REASON>Create table CNF_LocationMatrix2Attribute
0) Create table
1) Create index
2) Create foreign key - LocationMatrixId
3) Create foreign key - AttributeId
4) Create foreign key - WorkstationId
5) Check constraint
6) Create foreign key - UserId
7) Check constraint
8) Create Index LocationMatrixId-AttributeId
9) Drop column AttributesIds from table CNF_LocationMatrix</REASON><TABLENAMES>CNF_LocationMatrix2Attribute=LocMatrix2AttrId
CNF_LocationMatrix=LocationMatrixId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS ( SELECT * 
            FROM INFORMATION_SCHEMA.TABLES 
            WHERE TABLE_SCHEMA = 'dbo' 
	    AND TABLE_NAME = 'CNF_LocationMatrix2Attribute')
BEGIN
  DROP TABLE CNF_LocationMatrix2Attribute
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS ( SELECT * 
                FROM INFORMATION_SCHEMA.TABLES 
                WHERE TABLE_SCHEMA = 'dbo' 
	        AND TABLE_NAME = 'CNF_LocationMatrix2Attribute')
BEGIN
  Create table [CNF_LocationMatrix2Attribute]
  (
	[LocMatrix2AttrId] Integer Identity(1,1) NOT NULL,
	[LocationMatrixId] Integer NOT NULL,
	[AttributeId] Integer NOT NULL,
 	[Last_UserId_Log] Integer NOT NULL,
	[Last_WorkstationId_Log] Integer NOT NULL,
	[Last_DateTime_Log] Datetime NULL,
  Primary Key ([LocMatrix2AttrId])
  )
END </SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_CNF_LocationMatrix2Attribute_LocationMatrixId')
BEGIN                                                                              
  Alter table [CNF_LocationMatrix2Attribute] add  foreign key([LocationMatrixId]) references [CNF_LocationMatrix] ([LocationMatrixId])  on update no action on delete no action 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_CNF_LocationMatrix2Attribute_AttributeId')
BEGIN      
  Alter table [CNF_LocationMatrix2Attribute] add  foreign key([AttributeId]) references [CNF_Attribute] ([AttributeId])  on update no action on delete no action
END </SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_CNF_LocationMatrix2Attribute_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_LocationMatrix2Attribute  WITH CHECK ADD  CONSTRAINT [FK_CNF_LocationMatrix2Attribute_Last_WorkstationId_Log] FOREIGN KEY(Last_WorkstationId_Log)
  REFERENCES CNF_Workstation (WorkstationId)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>ALTER TABLE CNF_LocationMatrix2Attribute CHECK CONSTRAINT [FK_CNF_LocationMatrix2Attribute_Last_WorkstationId_Log]</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_CNF_LocationMatrix2Attribute_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_LocationMatrix2Attribute  WITH CHECK ADD  CONSTRAINT [FK_CNF_LocationMatrix2Attribute_Last_UserId_Log] FOREIGN KEY(Last_UserId_Log)
  REFERENCES CNF_User (UserId)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>ALTER TABLE CNF_LocationMatrix2Attribute CHECK CONSTRAINT [FK_CNF_LocationMatrix2Attribute_Last_UserId_Log]</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (	SELECT * 
		FROM sys.indexes
		WHERE Name = 'Idx_LocMatrix2Attr_LocId_AttrId')
BEGIN
  CREATE NONCLUSTERED INDEX [Idx_LocMatrix2Attr_LocId_AttrId] ON [CNF_LocationMatrix2Attribute] ([LocationMatrixId] ,[AttributeId])
END

</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
           WHERE Name = N'AttributeIDs' AND
           Object_ID  = Object_ID(N'CNF_LocationMatrix'))
BEGIN
  ALTER TABLE CNF_LocationMatrix
  DROP COLUMN AttributeIDs
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>pdalben</ADDEDBY><SQLVERSION>2740</SQLVERSION><RMTRACKLINK>77498</RMTRACKLINK><REASON>ADM_Gate Added ExternalLocationId</REASON><TABLENAMES>ADM_Gate=GateId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'ExternalLocationId' AND
                Object_ID  = Object_ID(N'ADM_Gate'))
BEGIN
  Alter Table ADM_Gate
  Add ExternalLocationId int NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>2739</SQLVERSION><RMTRACKLINK>84827</RMTRACKLINK><REASON>COA - Remove Varchar Fields in RR_DATA_Revenue Table</REASON><TABLENAMES>RR_Data_Revenue=RevenueRecognitionDataId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'rrCode' AND
                Object_ID  = Object_ID(N'rr_data_revenue'))
BEGIN
  ALTER TABLE rr_data_revenue
  DROP COLUMN rrCode
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'COAAccountCode' AND
                Object_ID  = Object_ID(N'rr_data_revenue'))
BEGIN
  ALTER TABLE rr_data_revenue
  DROP COLUMN COAAccountCode
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Matrixcellcode' AND
                Object_ID  = Object_ID(N'rr_data_revenue'))
BEGIN
  ALTER TABLE rr_data_revenue
  DROP COLUMN Matrixcellcode
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'FRevenueDate' AND
                Object_ID  = Object_ID(N'rr_data_revenue'))
BEGIN
  ALTER TABLE rr_data_revenue
  DROP COLUMN FRevenueDate
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dapicella</ADDEDBY><SQLVERSION>2738</SQLVERSION><RMTRACKLINK>79002</RMTRACKLINK><REASON></REASON><TABLENAMES>CNF_LocationMatrix=LocationMatrixId
CNF_LocationMatrixPrice=LocationMatrixPriceId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (	SELECT * 
            FROM INFORMATION_SCHEMA.TABLES 
            WHERE TABLE_SCHEMA = 'dbo' 
				AND TABLE_NAME = 'CNF_LocationMatrix')
BEGIN
	DROP TABLE CNF_LocationMatrix
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>CREATE TABLE CNF_LocationMatrix(
	LocationMatrixId int IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
	LocationMatrixAK varchar(32) NOT NULL,
	LocationMatrixType smallint NOT NULL,
	Code nvarchar(10) NOT NULL,
	Name nvarchar(50) NOT NULL,
	Description nvarchar(max) NULL,
	LocationId int NOT NULL,
	AttributeIDs varchar(4000) NULL,
	Enabled smallint NOT NULL,
	SortOrder smallint NULL,
	Last_UserId_Log int NULL,
	Last_WorkstationId_Log int NULL,
	Last_DateTime_Log datetime NULL,
PRIMARY KEY CLUSTERED 
(
	LocationMatrixId ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
UNIQUE NONCLUSTERED 
(
	LocationMatrixAK ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_CNF_LocationMatrix_Last_UserId_Log')
BEGIN
	ALTER TABLE CNF_LocationMatrix  WITH CHECK ADD  CONSTRAINT [FK_CNF_LocationMatrix_Last_UserId_Log] FOREIGN KEY(Last_UserId_Log)
	REFERENCES CNF_User (UserId)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>ALTER TABLE CNF_LocationMatrix CHECK CONSTRAINT [FK_CNF_LocationMatrix_Last_UserId_Log]</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_CNF_LocationMatrix_Last_WorkstationId_Log')
BEGIN
	ALTER TABLE CNF_LocationMatrix  WITH CHECK ADD  CONSTRAINT [FK_CNF_LocationMatrix_Last_WorkstationId_Log] FOREIGN KEY(Last_WorkstationId_Log)
	REFERENCES CNF_Workstation (WorkstationId)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>ALTER TABLE CNF_LocationMatrix CHECK CONSTRAINT [FK_CNF_LocationMatrix_Last_WorkstationId_Log]</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_CNF_LocationMatrix_LocationId')
BEGIN
	ALTER TABLE CNF_LocationMatrix  WITH CHECK ADD  CONSTRAINT [FK_CNF_LocationMatrix_LocationId] FOREIGN KEY(LocationId)
	REFERENCES CNF_Location (LocationId)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>ALTER TABLE CNF_LocationMatrix CHECK CONSTRAINT [FK_CNF_LocationMatrix_LocationId]</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (	SELECT * 
				FROM sys.indexes
				WHERE Name = 'IDX_CNF_LocationMatrix_LocationId')
BEGIN
	CREATE NONCLUSTERED INDEX [IDX_CNF_LocationMatrix_LocationId] ON CNF_LocationMatrix
	(
		LocationId ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (	SELECT * 
            FROM INFORMATION_SCHEMA.TABLES 
            WHERE TABLE_SCHEMA = 'dbo' 
				AND TABLE_NAME = 'CNF_LocationMatrixPrice')
BEGIN
	DROP TABLE CNF_LocationMatrixPrice
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>CREATE TABLE CNF_LocationMatrixPrice(
	LocationMatrixPriceId int IDENTITY(1,1) NOT NULL,
	LocationMatrixId int NOT NULL,
	FromGateId int NOT NULL,
	ToGateId int NOT NULL,
	AmountIn float NULL,
	AmountOut float NULL,
	Last_UserId_Log int NULL,
	Last_WorkstationId_Log int NULL,
	Last_DateTime_Log datetime NULL,
PRIMARY KEY CLUSTERED 
(
	LocationMatrixPriceId ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_CNF_LocationMatrixPrice_FromGateId')
BEGIN
	ALTER TABLE CNF_LocationMatrixPrice  WITH CHECK ADD  CONSTRAINT [FK_CNF_LocationMatrixPrice_FromGateId] FOREIGN KEY(FromGateId)
	REFERENCES ADM_Gate (GateId)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>ALTER TABLE CNF_LocationMatrixPrice CHECK CONSTRAINT [FK_CNF_LocationMatrixPrice_FromGateId]</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_CNF_LocationMatrixPrice_ToGateId')
BEGIN
	ALTER TABLE CNF_LocationMatrixPrice  WITH CHECK ADD  CONSTRAINT [FK_CNF_LocationMatrixPrice_ToGateId] FOREIGN KEY(ToGateId)
	REFERENCES ADM_Gate (GateId)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>ALTER TABLE CNF_LocationMatrixPrice CHECK CONSTRAINT [FK_CNF_LocationMatrixPrice_ToGateId]</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_CNF_LocationMatrixPrice_Last_UserId_Log')
BEGIN
	ALTER TABLE CNF_LocationMatrixPrice  WITH CHECK ADD  CONSTRAINT [FK_CNF_LocationMatrixPrice_Last_UserId_Log] FOREIGN KEY(Last_UserId_Log)
	REFERENCES CNF_User (UserId)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>ALTER TABLE CNF_LocationMatrixPrice CHECK CONSTRAINT [FK_CNF_LocationMatrixPrice_Last_UserId_Log]</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_CNF_LocationMatrixPrice_Last_WorkstationId_Log')
BEGIN
	ALTER TABLE CNF_LocationMatrixPrice  WITH CHECK ADD  CONSTRAINT [FK_CNF_LocationMatrixPrice_Last_WorkstationId_Log] FOREIGN KEY(Last_WorkstationId_Log)
	REFERENCES CNF_Workstation (WorkstationId)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>ALTER TABLE CNF_LocationMatrixPrice CHECK CONSTRAINT [FK_CNF_LocationMatrixPrice_Last_WorkstationId_Log]</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (	SELECT * 
				FROM sys.indexes
				WHERE Name = 'IDX_CNF_LocationMatrixPrice_LocationMatrixId')
BEGIN
	CREATE NONCLUSTERED INDEX [IDX_CNF_LocationMatrixPrice_LocationMatrixId] ON CNF_LocationMatrixPrice
	(
		LocationMatrixId ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (	SELECT * 
				FROM sys.indexes
				WHERE Name = 'IDX_CNF_LocationMatrixPrice_FromGateId')
BEGIN
	CREATE NONCLUSTERED INDEX [IDX_CNF_LocationMatrixPrice_FromGateId] ON CNF_LocationMatrixPrice
	(
		FromGateId ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (	SELECT * 
				FROM sys.indexes
				WHERE Name = 'IDX_CNF_LocationMatrixPrice_ToGateId')
BEGIN
	CREATE NONCLUSTERED INDEX [IDX_CNF_LocationMatrixPrice_ToGateId] ON CNF_LocationMatrixPrice
	(
		ToGateId ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2737</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES>CNF_Seat=SeatId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Row' AND
                Object_ID  = Object_ID(N'CNF_Seat'))
BEGIN
  Alter Table CNF_Seat
  Add Row int Null
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Col' AND
                Object_ID  = Object_ID(N'CNF_Seat'))
BEGIN
  Alter Table CNF_Seat
  Add Col int Null
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Status' AND
                Object_ID  = Object_ID(N'CNF_Seat'))
BEGIN
  Alter Table CNF_Seat
  Add Status smallint Null
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'HoldDateTime' AND
                Object_ID  = Object_ID(N'CNF_Seat'))
BEGIN
  Alter Table CNF_Seat
  Add HoldDateTime datetime Null
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'AdditionalCategory' AND
                Object_ID  = Object_ID(N'CNF_Seat'))
BEGIN
  Alter Table CNF_Seat
  Add AdditionalCategory varchar(200) Null
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>2736</SQLVERSION><RMTRACKLINK>83001</RMTRACKLINK><REASON>Added 2 new columns to CNF_MatrixCellInfo:
1)IsThirdPartyItem
2)ThirdPartyItemThreshold</REASON><TABLENAMES>CNF_MatrixCellInfo=MatrixCellInfoId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'IsThirdPartyItem' AND
                Object_ID  = Object_ID(N'CNF_MatrixCellInfo'))
BEGIN
  Alter Table CNF_MatrixCellInfo
  Add IsThirdPartyItem Smallint Null,
      ThirdPartyItemThreshold Smallint Null
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>2735</SQLVERSION><RMTRACKLINK>83533</RMTRACKLINK><REASON>3 history fields removed from ARC_Index, CNF_ImportMatch</REASON><TABLENAMES>ARC_Index=IndexId
CNF_ImportMatch=ImportMatchId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_ARC_Index_Last_UserId_Log')
BEGIN
  ALTER TABLE ARC_Index
  DROP CONSTRAINT FK_ARC_Index_Last_UserId_Log
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_ARC_Index_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE ARC_Index
  DROP CONSTRAINT FK_ARC_Index_Last_WorkstationId_Log
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'ARC_Index'))
BEGIN
  ALTER TABLE ARC_Index
  DROP COLUMN Last_UserId_Log, Last_WorkstationId_Log, Last_DateTime_Log
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_ImportMatch_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_ImportMatch
  DROP CONSTRAINT FK_CNF_ImportMatch_Last_UserId_Log
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_ImportMatch_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_ImportMatch
  DROP CONSTRAINT FK_CNF_ImportMatch_Last_WorkstationId_Log
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_ImportMatch'))
BEGIN
  ALTER TABLE CNF_ImportMatch
  DROP COLUMN Last_UserId_Log, Last_WorkstationId_Log, Last_DateTime_Log
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>UPDATE CNF_DBTable Set Logged = 0 WHERE TableName = 'CNF_ImportMatch'</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>pchen</ADDEDBY><SQLVERSION>2734</SQLVERSION><RMTRACKLINK>79137</RMTRACKLINK><REASON>Append field DocStatus into DATA_Ticket
Append field Mandatory into DATA_Ticket2Document</REASON><TABLENAMES>DATA_Ticket=TicketId
DATA_Ticket2Document=Ticket2DocumentId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'DocStatus' AND
                Object_ID  = Object_ID(N'DATA_Ticket'))
BEGIN
  Alter Table DATA_Ticket
  Add DocStatus Smallint Null
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Mandatory' AND
                Object_ID  = Object_ID(N'DATA_Ticket2Document'))
BEGIN
  Alter Table DATA_Ticket2Document
  Add Mandatory Smallint Null
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>2733</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_HIL_CreateHILTrigger]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_HIL_CreateHILTrigger</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>CREATE Procedure dbo.otn_sp_HIL_CreateHILTrigger
	@TABLE_NAME sysname
AS 
BEGIN
	DECLARE @Logged int
	set @Logged = 0

	IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME= 'DATA_HL_Master')
	BEGIN

		
		INSERT INTO dbo.cnf_dbtable
			   (TABLENAME,
				Active,
				Logged,
				Last_UserId_Log,
				Last_WorkstationId_Log,
				Last_DateTime_Log)
		SELECT @TABLE_NAME, 
				0,
				0,  
				1,
				1,
				GetDate()
		FROM sys.tables AS t WITH(NOLOCK)
		where t.name = @TABLE_NAME
		  and t.name not in (select tablename from cnf_dbtable WITH(NOLOCK))	
		  	 
		INSERT INTO dbo.cnf_dbcolumn
			   (DBTableId,
				ColumnName,
				Active,
				logged,
				Last_UserId_Log,
				Last_WorkstationId_Log,
				Last_DateTime_Log)
		SELECT distinct HT.dbtableid AS tablesID, 
				c.name,
				0,
				0,
				1,
				1,  
				GetDate()
		FROM sys.tables AS t WITH(NOLOCK)
			INNER JOIN sys.columns c WITH(NOLOCK)				ON t.OBJECT_ID = c.OBJECT_ID 
			INNER JOIN cnf_dbtable HT WITH(NOLOCK)              ON HT.TableName = t.name	

		WHERE SCHEMA_NAME(schema_id) = 'dbo'
			and t.name = @TABLE_NAME
			AND (cast(HT.dbTableID as Varchar(5000)) + c.Name) not in (select (cast(DBTableID as Varchar(5000)) + ColumnName) from cnf_dbcolumn WITH(NOLOCK))


--ACtivate logged and active
	Update cnf_dbtable
	   set Logged = 1,
	       Active = 1
	WHERE  TableName = @TABLE_NAME
	    AND TableName in (
	  						SELECT distinct t.name AS table_name
								FROM sys.tables AS t WITH(NOLOCK)
									INNER JOIN sys.columns c WITH(NOLOCK)				ON t.OBJECT_ID = c.OBJECT_ID 	
								WHERE c.name LIKE '%LAST%LOG'
									and SCHEMA_NAME(schema_id) = 'dbo'
						)
		AND TableName in (
							SELECT distinct t.name AS table_name
								FROM sys.tables AS t WITH(NOLOCK)
									INNER JOIN sys.columns c WITH(NOLOCK)				ON t.OBJECT_ID = c.OBJECT_ID 	
								WHERE c.name LIKE '%LAST%LOG'
									and SCHEMA_NAME(schema_id) = 'dbo'
									and ((T.name like '%ADM_%') or (t.name like '%CNF_%') or
											(t.name in ('DATA_Account', 'DATA_AccountFinancial', 'DATA_AccountRelationship', 'DATA_DmgData',
														'DATA_DmgData_Translate', 'DATA_Right')))
							)
		AND TableName NOT IN (SELECT table_name
							FROM information_schema.columns WITH(NOLOCK)
							where data_type in ('NTEXT', 'TEXT')
								AND TABLE_NAME in (
	  												SELECT distinct t.name AS table_name
														FROM sys.tables AS t WITH(NOLOCK)
															INNER JOIN sys.columns c WITH(NOLOCK)				ON t.OBJECT_ID = c.OBJECT_ID 	
														WHERE c.name LIKE '%LAST%LOG'
															and SCHEMA_NAME(schema_id) = 'dbo'
												))

	Update cnf_dbtable
	   set Logged = 0,
	       Active = 0
	WHERE  TableName = @TABLE_NAME
	  and TableName not in (select name
							  from sys.tables)


	Update cnf_dbcolumn
	  set Active = 1,
	      Logged = 1
	where DBTableid in (select dbtableid from cnf_dbtable WITH(NOLOCK) where active = 1 and logged = 1 and tablename = @TABLE_NAME)
	  and ColumnName not in ('Last_UserID_log', 'Last_WorkstationID_LOG', 'Last_DateTime_Log')
	  and columnName in (select c.name
							from sys.tables AS t WITH(NOLOCK)				
								INNER JOIN sys.columns c WITH(NOLOCK)				ON t.OBJECT_ID = c.OBJECT_ID 
							where t.name = @TABLE_NAME)  

	Update cnf_dbcolumn
	  set Active = 0,
	      Logged = 0
	where DBTableid in (select dbtableid from cnf_dbtable WITH(NOLOCK) where active = 1 and logged = 1 and tablename = @TABLE_NAME)
	  and columnName not in (select c.name
							from sys.tables AS t WITH(NOLOCK)				
								INNER JOIN sys.columns c WITH(NOLOCK)				ON t.OBJECT_ID = c.OBJECT_ID 
							where t.name = @TABLE_NAME)  


	select @Logged = Logged from cnf_dbtable WITH(NOLOCK) where tablename = @TABLE_NAME
	if @Logged = 1 
	BEGIN
		DECLARE @sql NVARCHAR(max),
				@SQL1 NVARCHAR(MAX)

		SET NOCOUNT ON  

		EXEC('IF OBJECT_ID (''' + @TABLE_NAME + '_CT'', ''TR'') IS NOT NULL DROP TRIGGER ' + @TABLE_NAME + '_CT')
		SELECT @sql = 
		'create trigger ' + @TABLE_NAME + '_CT on ' + @TABLE_NAME + ' FOR insert, update, delete
		as
		declare @TName varchar(128),
		        @TID nvarchar(max),
				@TLog int,  
				@PKC varchar(max),
				@PKV varchar(max),  
				@sql nvarchar(max), 
				@Type nvarchar(1),
				@MId nvarchar(max) = ''0'', 
				@ColumnID nvarchar(max) = ''0'',
				@CName varchar(128),
				@CValue1 nvarchar(max),
				@CValue2 nvarchar(max)

		if exists(select top 1 1 from cnf_system where ISNULL(BOSHistoryLogEnabled, 1) = 1 and offlinemode = 0)
		BEGIN
			select @TName = ''' + @TABLE_NAME + ''', @TID=dbtableid, @TLog = (case when Active = 1 and Logged = 1 then 1 else 0 end) from cnf_dbtable WITH(NOLOCK) where TableName=''' + @TABLE_NAME + '''

			if @TLog = 1
			begin
				if exists (select * from inserted)
				if exists (select * from deleted)
				select @Type = ''2''      --Update
				else
				select @Type = ''3''      --Insert
				else
				select @Type = ''1''      --Delete

				select * into #ins from inserted
				select * into #del from deleted

				select @PKC = coalesce(@PKC + '' and'', '' on'') + '' i.'' + c.COLUMN_NAME + '' = d.'' + c.COLUMN_NAME, @PKV = coalesce(@PKV+''+'','''') + ''convert(varchar(100), coalesce(i.'' + COLUMN_NAME + '',d.'' + COLUMN_NAME + ''))''
				  from INFORMATION_SCHEMA.TABLE_CONSTRAINTS p WITH(NOLOCK)
					   INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE c WITH(NOLOCK) on c.CONSTRAINT_NAME = p.CONSTRAINT_NAME and c.TABLE_NAME = p.TABLE_NAME
				 where p.TABLE_NAME=@TName and CONSTRAINT_TYPE=''PRIMARY KEY''

				DECLARE TCursor CURSOR LOCAL FOR
								select columnName,
									   dbcolumnid
								from(
								select CNF_DBColumn.ColumnName,
									CNF_DBColumn.DBColumnId,
									(case when cnf_dbcolumn.Active = 1 and cnf_dbcolumn.Logged = 1 then 1 else 0 end) Active
									from sys.tables AS t WITH(NOLOCK)				
										INNER JOIN sys.columns c WITH(NOLOCK)				ON t.OBJECT_ID = c.OBJECT_ID 
										INNER JOIN cnf_dbtable WITH(NOLOCK)					on cnf_dbtable.tablename = t.name
										INNER JOIN cnf_dbcolumn WITH(NOLOCK)				on cnf_dbcolumn.dbtableid = cnf_dbtable.dbtableid and cnf_dbcolumn.columnname = c.name
								where cnf_dbcolumn.dbtableid = @TID
								)p
								where Active = 1

				OPEN TCursor

				FETCH NEXT FROM TCursor INTO
					@CName, @ColumnID
					'
			SELECT @sql1 = '
				WHILE @@FETCH_STATUS = 0
				BEGIN

					set @sql =''Select @CValue1 = '' + @CName +'' from #ins ''
					EXEC sp_executesql @sql, N''@CValue1 nvarchar(max) OUTPUT'', @CValue1 OUTPUT

					set @sql =''Select @CValue2 = '' + @CName +'' from #del ''
					EXEC sp_executesql @sql, N''@CValue2 nvarchar(max) OUTPUT'', @CValue2 OUTPUT

					if ISNULL(@CValue1, ''&amp;*()_2'') &lt;&gt; ISNULL(@CValue2, ''&amp;*()_2'')
					begin
						if @MId = 0
						begin
							set @sql = ''insert DATA_HL_Master (OperationType, dbtableid, ReferenceId, UserId, WorkstationId, InsDateTime, DelDateTime)''
							set @sql = @sql + '' select '''''' + @Type + ''''''''												
							set @sql = @sql + '', '''''' + @TID + ''''''''		
							set @sql = @sql + '','' + @PKV		
							set @sql = @sql + '', convert(varchar(1000), i.Last_UserId_Log), convert(varchar(1000), i.Last_WorkstationId_Log), convert(varchar(1000),i.Last_DateTime_Log, 120), convert(varchar(1000),getdate(), 120) ''
							set @sql = @sql + '' from #ins i full outer join #del d ''
							set @sql = @sql + @PKC 
							set @sql = @sql + '' SELECT @MId = SCOPE_IDENTITY()''
							EXEC sp_executesql @sql, N''@MId nvarchar(max) OUTPUT'', @MId OUTPUT
						end
						if @Type &lt;&gt; ''3''
						BEGIN
							set @sql = ''insert data_HL_Detail (MasterId, OriginalValue, ModifiedValue, DBColumnID)''						
							set @sql = @sql + '' select convert(varchar(1000),'' + @MId + ''), convert(varchar(1000),d.'' + @CName + ''), convert(varchar(1000),i.'' + @CName + '')''				
							set @sql = @sql + '', convert(varchar(1000),'' + @ColumnID + '')  ''
							set @sql = @sql + '' from #ins i full outer join #del d '' + @PKC				
							EXEC sp_executesql @sql 																	
						END		
						
					END
					FETCH NEXT FROM TCursor INTO
					   @CName, @ColumnID
				END  --While loop
				CLOSE TCursor;
				DEALLOCATE TCursor; 
			END    --Table Check
		END	-- System Check
		'

	EXEC(@sql + @sql1)
	END	
  END
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>declare @TABLE_NAME sysname

SELECT @TABLE_NAME = MIN(Table_Name)
  FROM INFORMATION_SCHEMA.Tables 
 WHERE TABLE_TYPE = 'BASE TABLE' 
	AND TABLE_NAME != 'sysdiagrams'
	AND TABLE_SCHEMA = 'dbo'


WHILE @TABLE_NAME IS NOT NULL
BEGIN
	Exec otn_sp_HIL_CreateHILTrigger @TABLE_NAME

	SELECT @TABLE_NAME = MIN(Table_Name)
	  FROM INFORMATION_SCHEMA.Tables 
     WHERE TABLE_NAME &gt; @TABLE_NAME
	   AND TABLE_TYPE = 'BASE TABLE' 
	   AND TABLE_NAME != 'sysdiagrams'
	   AND TABLE_SCHEMA = 'dbo'

END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>2732</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_HIL_CreateHILTrigger]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_HIL_CreateHILTrigger</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>CREATE Procedure dbo.otn_sp_HIL_CreateHILTrigger
	@TABLE_NAME sysname
AS 
BEGIN
	DECLARE @Logged int
	set @Logged = 0

	IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME= 'DATA_HL_Master')
	BEGIN

		
		INSERT INTO dbo.cnf_dbtable
			   (TABLENAME,
				Active,
				Logged,
				Last_UserId_Log,
				Last_WorkstationId_Log,
				Last_DateTime_Log)
		SELECT @TABLE_NAME, 
				0,
				0,  
				1,
				1,
				GetDate()
		FROM sys.tables AS t WITH(NOLOCK)
		where t.name = @TABLE_NAME
		  and t.name not in (select tablename from cnf_dbtable WITH(NOLOCK))	
		  	 
		INSERT INTO dbo.cnf_dbcolumn
			   (DBTableId,
				ColumnName,
				Active,
				logged,
				Last_UserId_Log,
				Last_WorkstationId_Log,
				Last_DateTime_Log)
		SELECT distinct HT.dbtableid AS tablesID, 
				c.name,
				0,
				0,
				1,
				1,  
				GetDate()
		FROM sys.tables AS t WITH(NOLOCK)
			INNER JOIN sys.columns c WITH(NOLOCK)				ON t.OBJECT_ID = c.OBJECT_ID 
			INNER JOIN cnf_dbtable HT WITH(NOLOCK)              ON HT.TableName = t.name	

		WHERE SCHEMA_NAME(schema_id) = 'dbo'
			and t.name = @TABLE_NAME
			AND (cast(HT.dbTableID as Varchar(5000)) + c.Name) not in (select (cast(DBTableID as Varchar(5000)) + ColumnName) from cnf_dbcolumn WITH(NOLOCK))


--ACtivate logged and active
	Update cnf_dbtable
	   set Logged = 1,
	       Active = 1
	WHERE  TableName = @TABLE_NAME
	    AND TableName in (
	  						SELECT distinct t.name AS table_name
								FROM sys.tables AS t WITH(NOLOCK)
									INNER JOIN sys.columns c WITH(NOLOCK)				ON t.OBJECT_ID = c.OBJECT_ID 	
								WHERE c.name LIKE '%LAST%LOG'
									and SCHEMA_NAME(schema_id) = 'dbo'
						)
		AND TableName in (
							SELECT distinct t.name AS table_name
								FROM sys.tables AS t WITH(NOLOCK)
									INNER JOIN sys.columns c WITH(NOLOCK)				ON t.OBJECT_ID = c.OBJECT_ID 	
								WHERE c.name LIKE '%LAST%LOG'
									and SCHEMA_NAME(schema_id) = 'dbo'
									and ((T.name like '%ADM_%') or (t.name like '%CNF_%') or
											(t.name in ('DATA_Account', 'DATA_AccountFinancial', 'DATA_AccountRelationship', 'DATA_DmgData',
														'DATA_DmgData_Translate', 'DATA_Right')))
							)
		AND TableName NOT IN (SELECT table_name
							FROM information_schema.columns WITH(NOLOCK)
							where data_type in ('NTEXT', 'TEXT')
								AND TABLE_NAME in (
	  												SELECT distinct t.name AS table_name
														FROM sys.tables AS t WITH(NOLOCK)
															INNER JOIN sys.columns c WITH(NOLOCK)				ON t.OBJECT_ID = c.OBJECT_ID 	
														WHERE c.name LIKE '%LAST%LOG'
															and SCHEMA_NAME(schema_id) = 'dbo'
												))

	Update cnf_dbtable
	   set Logged = 0,
	       Active = 0
	WHERE  TableName = @TABLE_NAME
	  and TableName not in (select name
							  from sys.tables)


	Update cnf_dbcolumn
	  set Active = 1,
	      Logged = 1
	where DBTableid in (select dbtableid from cnf_dbtable WITH(NOLOCK) where active = 1 and logged = 1 and tablename = @TABLE_NAME)
	  and ColumnName not in ('Last_UserID_log', 'Last_WorkstationID_LOG', 'Last_DateTime_Log')
	  and columnName in (select c.name
							from sys.tables AS t WITH(NOLOCK)				
								INNER JOIN sys.columns c WITH(NOLOCK)				ON t.OBJECT_ID = c.OBJECT_ID 
							where t.name = @TABLE_NAME)  

	Update cnf_dbcolumn
	  set Active = 0,
	      Logged = 0
	where DBTableid in (select dbtableid from cnf_dbtable WITH(NOLOCK) where active = 1 and logged = 1 and tablename = @TABLE_NAME)
	  and columnName not in (select c.name
							from sys.tables AS t WITH(NOLOCK)				
								INNER JOIN sys.columns c WITH(NOLOCK)				ON t.OBJECT_ID = c.OBJECT_ID 
							where t.name = @TABLE_NAME)  


	select @Logged = Logged from cnf_dbtable WITH(NOLOCK) where tablename = @TABLE_NAME
	if @Logged = 1 
	BEGIN
		DECLARE @sql NVARCHAR(max),
				@SQL1 NVARCHAR(MAX)

		SET NOCOUNT ON  

		EXEC('IF OBJECT_ID (''' + @TABLE_NAME + '_CT'', ''TR'') IS NOT NULL DROP TRIGGER ' + @TABLE_NAME + '_CT')
		SELECT @sql = 
		'create trigger ' + @TABLE_NAME + '_CT on ' + @TABLE_NAME + ' FOR insert, update, delete
		as
		declare @TName varchar(128),
		        @TID nvarchar(max),
				@TLog int,  
				@PKC varchar(max),
				@PKV varchar(max),  
				@sql nvarchar(max), 
				@Type nvarchar(1),
				@MId nvarchar(max) = ''0'', 
				@ColumnID nvarchar(max) = ''0'',
				@CName varchar(128),
				@CValue1 nvarchar(max),
				@CValue2 nvarchar(max),
				@DelDate nvarchar(max)

		if exists(select top 1 1 from cnf_system where ISNULL(BOSHistoryLogEnabled, 1) = 1 and offlinemode = 0)
		BEGIN
			select @TName = ''' + @TABLE_NAME + ''', @TID=dbtableid, @TLog = (case when Active = 1 and Logged = 1 then 1 else 0 end) from cnf_dbtable WITH(NOLOCK) where TableName=''' + @TABLE_NAME + '''

			if @TLog = 1
			begin
				if exists (select * from inserted)
				if exists (select * from deleted)
				select @Type = ''2''      --Update
				else
				select @Type = ''3''      --Insert
				else
				select @Type = ''1''      --Delete

				select * into #ins from inserted
				select * into #del from deleted

				select @PKC = coalesce(@PKC + '' and'', '' on'') + '' i.'' + c.COLUMN_NAME + '' = d.'' + c.COLUMN_NAME, @PKV = coalesce(@PKV+''+'','''') + ''convert(varchar(100), coalesce(i.'' + COLUMN_NAME + '',d.'' + COLUMN_NAME + ''))''
				  from INFORMATION_SCHEMA.TABLE_CONSTRAINTS p WITH(NOLOCK)
					   INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE c WITH(NOLOCK) on c.CONSTRAINT_NAME = p.CONSTRAINT_NAME and c.TABLE_NAME = p.TABLE_NAME
				 where p.TABLE_NAME=@TName and CONSTRAINT_TYPE=''PRIMARY KEY''

				DECLARE TCursor CURSOR LOCAL FOR
								select columnName,
									   dbcolumnid
								from(
								select CNF_DBColumn.ColumnName,
									CNF_DBColumn.DBColumnId,
									(case when cnf_dbcolumn.Active = 1 and cnf_dbcolumn.Logged = 1 then 1 else 0 end) Active
									from sys.tables AS t WITH(NOLOCK)				
										INNER JOIN sys.columns c WITH(NOLOCK)				ON t.OBJECT_ID = c.OBJECT_ID 
										INNER JOIN cnf_dbtable WITH(NOLOCK)					on cnf_dbtable.tablename = t.name
										INNER JOIN cnf_dbcolumn WITH(NOLOCK)				on cnf_dbcolumn.dbtableid = cnf_dbtable.dbtableid and cnf_dbcolumn.columnname = c.name
								where cnf_dbcolumn.dbtableid = @TID
								)p
								where Active = 1

				OPEN TCursor

				FETCH NEXT FROM TCursor INTO
					@CName, @ColumnID
					'
			SELECT @sql1 = '
				WHILE @@FETCH_STATUS = 0
				BEGIN
					if @Type = ''1''
					  set @DelDate = getdate()
	                else
					  set @DelDate = ''null ''

					set @sql =''Select @CValue1 = '' + @CName +'' from #ins ''
					EXEC sp_executesql @sql, N''@CValue1 nvarchar(max) OUTPUT'', @CValue1 OUTPUT

					set @sql =''Select @CValue2 = '' + @CName +'' from #del ''
					EXEC sp_executesql @sql, N''@CValue2 nvarchar(max) OUTPUT'', @CValue2 OUTPUT

					if ISNULL(@CValue1, ''&amp;*()_2'') &lt;&gt; ISNULL(@CValue2, ''&amp;*()_2'')
					begin
						if @MId = 0
						begin
							set @sql = ''insert DATA_HL_Master (OperationType, dbtableid, ReferenceId, UserId, WorkstationId, InsDateTime, DelDateTime)''
							set @sql = @sql + '' select '''''' + @Type + ''''''''												
							set @sql = @sql + '', '''''' + @TID + ''''''''		
							set @sql = @sql + '','' + @PKV		
							set @sql = @sql + '',convert(varchar(1000), i.Last_UserId_Log), convert(varchar(1000), i.Last_WorkstationId_Log), convert(varchar(1000),i.Last_DateTime_Log, 120), ''
							set @sql = @sql + '''' + @DelDate  + ''''
							set @sql = @sql + '' from #ins i full outer join #del d ''
							set @sql = @sql + @PKC 
							set @sql = @sql + '' SELECT @MId = SCOPE_IDENTITY()''
							EXEC sp_executesql @sql, N''@MId nvarchar(max) OUTPUT'', @MId OUTPUT
						end
						if @Type &lt;&gt; ''3''
						BEGIN
							set @sql = ''insert data_HL_Detail (MasterId, OriginalValue, ModifiedValue, DBColumnID)''						
							set @sql = @sql + '' select convert(varchar(1000),'' + @MId + ''), convert(varchar(1000),d.'' + @CName + ''), convert(varchar(1000),i.'' + @CName + '')''				
							set @sql = @sql + '', convert(varchar(1000),'' + @ColumnID + '')  ''
							set @sql = @sql + '' from #ins i full outer join #del d '' + @PKC				
							EXEC sp_executesql @sql 																	
						END		
						
					END
					FETCH NEXT FROM TCursor INTO
					   @CName, @ColumnID
				END  --While loop
				CLOSE TCursor;
				DEALLOCATE TCursor; 
			END    --Table Check
		END	-- System Check
		'

	EXEC(@sql + @sql1)
	END	
  END
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>--declare @TABLE_NAME sysname

--SELECT @TABLE_NAME = MIN(Table_Name)
--  FROM INFORMATION_SCHEMA.Tables 
-- WHERE TABLE_TYPE = 'BASE TABLE' 
--	AND TABLE_NAME != 'sysdiagrams'
--	AND TABLE_SCHEMA = 'dbo'


--WHILE @TABLE_NAME IS NOT NULL
--BEGIN
--	Exec otn_sp_HIL_CreateHILTrigger @TABLE_NAME

--	SELECT @TABLE_NAME = MIN(Table_Name)
--	  FROM INFORMATION_SCHEMA.Tables 
--     WHERE TABLE_NAME &gt; @TABLE_NAME
--	   AND TABLE_TYPE = 'BASE TABLE' 
--	   AND TABLE_NAME != 'sysdiagrams'
--	   AND TABLE_SCHEMA = 'dbo'

--E</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dchen</ADDEDBY><SQLVERSION>2731</SQLVERSION><RMTRACKLINK>83472</RMTRACKLINK><REASON>Create a new activity type for Reset Password
* Creating a column with naming consistency</REASON><TABLENAMES>DATA_UserLog=LogID</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'EntityId' AND
                Object_ID  = Object_ID(N'DATA_UserLog'))
BEGIN
  ALTER TABLE DATA_UserLog
  DROP COLUMN EntityId
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'EntityTargetId' AND
                Object_ID  = Object_ID(N'DATA_UserLog'))
BEGIN
  ALTER TABLE DATA_UserLog
  DROP COLUMN EntityTargetId
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'EntityId' AND
                Object_ID  = Object_ID(N'DATA_UserLog'))
BEGIN
  ALTER TABLE DATA_UserLog
  ADD EntityId Integer
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'EntityTable' AND
                Object_ID  = Object_ID(N'DATA_UserLog'))
BEGIN
  ALTER TABLE DATA_UserLog
  ADD EntityTable Integer
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dkonnov</ADDEDBY><SQLVERSION>2730</SQLVERSION><RMTRACKLINK>83472</RMTRACKLINK><REASON>Create a new activity type for Reset Password
Solution: Extending User Activity Log</REASON><TABLENAMES>DATA_UserLog=LogID</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'EntityId' AND
                Object_ID  = Object_ID(N'DATA_UserLog'))
BEGIN
  ALTER TABLE DATA_UserLog
  ADD EntityId Integer
END

</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'EntityTargetId' AND
                Object_ID  = Object_ID(N'DATA_UserLog'))
BEGIN
  ALTER TABLE DATA_UserLog
  ADD EntityTargetId Integer
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>2729</SQLVERSION><RMTRACKLINK>82994</RMTRACKLINK><REASON>New Index</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>if not exists(SELECT * 
				FROM sys.indexes 
				where name = 'IDX_DATA_Saleitem_BaseSaleID' AND object_id = OBJECT_ID('dbo.data_saleitem'))
begin
	CREATE NONCLUSTERED INDEX [IDX_DATA_Saleitem_BaseSaleID] ON [dbo].[DATA_SaleItem]
	(
		[BaseSaleId] ASC
	)
	INCLUDE ( 	[SaleId]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2728</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>New DATA_Product
New DATA_SaleItem2Product</REASON><TABLENAMES>DATA_Product=ProductId
DATA_SaleItem2Product=SaleItem2ProductId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                WHERE TABLE_SCHEMA = 'dbo' 
                  AND TABLE_NAME = 'DATA_Product')
BEGIN

CREATE TABLE [dbo].[DATA_Product](
	[ProductId] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
	[WorkstationId] [int] NOT NULL,
	[AccountId] [int] NULL,
	[TicketId] [int] NULL,
	[FSaleDate] [datetime] NULL,
	[SiteId] [int] NOT NULL,
	[VoidType] [smallint] NOT NULL,
	[SaleDateTime] [datetime] NULL,
	[CurrencyId] [int] NOT NULL,
	[Price] [float] NOT NULL,
	[RawPrice] [float] NULL,
	[Taxes] [float] NOT NULL,
	[ActiveFrom] [datetime] NULL,
	[ActiveTo] [datetime] NULL,
	[TaxExempt] [smallint] NULL,
	[MatrixCellId] [int] NOT NULL,
	[DmgCategoryId] [int] NULL,
	[SaleItemId] [int] NULL,
	[ProductTaxType] [smallint] NOT NULL,
	[TaxPackageId] [int] NULL,
	[CreationType] [smallint] NOT NULL,
	[PeopleCount] [int] NOT NULL,
	[ExternalReferenceId] [varchar](400) NULL,
	[LastVoidType] [smallint] NULL,
	[ProductType] [smallint] NOT NULL
PRIMARY KEY CLUSTERED 
(
	[ProductId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_DATA_Product_AccountId')
BEGIN

ALTER TABLE [dbo].[DATA_Product]  ADD CONSTRAINT [FK_DATA_Product_AccountId] FOREIGN KEY([AccountId])
REFERENCES [dbo].[DATA_Account] ([AccountId])

END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_DATA_Product_TicketId')
BEGIN

ALTER TABLE [dbo].[DATA_Product]  ADD CONSTRAINT [FK_DATA_Product_TicketId] FOREIGN KEY([TicketId])
REFERENCES [dbo].[DATA_Ticket] ([TicketId])

END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_DATA_Product_CurrencyId')
BEGIN
ALTER TABLE [dbo].[DATA_Product]  ADD CONSTRAINT [FK_DATA_Product_CurrencyId]  FOREIGN KEY([CurrencyId])
REFERENCES [dbo].[CNF_Currency] ([CurrencyId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_DATA_Product_DmgCategoryId')
BEGIN
ALTER TABLE [dbo].[DATA_Product]  ADD CONSTRAINT [FK_DATA_Product_DmgCategoryId] FOREIGN KEY([DmgCategoryId])
REFERENCES [dbo].[CNF_DmgCategory] ([DmgCategoryId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_DATA_Product_MatrixCellId')
BEGIN
ALTER TABLE [dbo].[DATA_Product]  ADD CONSTRAINT [FK_DATA_Product_MatrixCellId] FOREIGN KEY([MatrixCellId])
REFERENCES [dbo].[CNF_MatrixCell] ([MatrixCellId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_DATA_Product_SaleItemId')
BEGIN
ALTER TABLE [dbo].[DATA_Product]  ADD CONSTRAINT [FK_DATA_Product_SaleItemId] FOREIGN KEY([SaleItemId])
REFERENCES [dbo].[DATA_SaleItem] ([SaleItemId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_DATA_Product_TaxPackageId')
BEGIN
ALTER TABLE [dbo].[DATA_Product]  ADD CONSTRAINT [FK_DATA_Product_TaxPackageId] FOREIGN KEY([TaxPackageId])
REFERENCES [dbo].[CNF_TaxPackage] ([TaxPackageId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_DATA_Product_WorkstationId')
BEGIN
ALTER TABLE [dbo].[DATA_Product]  ADD CONSTRAINT [FK_DATA_Product_WorkstationId] FOREIGN KEY([WorkstationId])
REFERENCES [dbo].[CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_DATA_Product_SiteId')
BEGIN
ALTER TABLE [dbo].[DATA_Product]  ADD CONSTRAINT [FK_DATA_Product_SiteId] FOREIGN KEY([SiteId])
REFERENCES [dbo].[CNF_Site] ([SiteId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                 FROM sys.indexes
                WHERE Name = 'IDX_DATA_Product_AccountId')
BEGIN
CREATE NONCLUSTERED INDEX [IDX_DATA_Product_AccountId] ON [dbo].[DATA_Product]
(
	[AccountId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                 FROM sys.indexes
                WHERE Name = 'IDX_DATA_Product_MatrixCellId')
BEGIN
CREATE NONCLUSTERED INDEX [IDX_DATA_Product_MatrixCellId] ON [dbo].[DATA_Product]
(
	[MatrixCellId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                 FROM sys.indexes
                WHERE Name = 'IDX_DATA_Product_TicketId')
BEGIN
CREATE NONCLUSTERED INDEX [IDX_DATA_Product_TicketId] ON [dbo].[DATA_Product]
(
	[TicketId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                 FROM sys.indexes
                WHERE Name = 'IDX_DATA_Product_SaleItemId')
BEGIN
CREATE NONCLUSTERED INDEX [IDX_DATA_Product_SaleItemId] ON [dbo].[DATA_Product]
(
	[SaleItemId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                 FROM sys.indexes
                WHERE Name = 'IDX_DATA_Product_WorkstationId')
BEGIN

CREATE NONCLUSTERED INDEX [IDX_DATA_Product_WorkstationId] ON [dbo].[DATA_Product]
(
	[WorkstationId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                WHERE TABLE_SCHEMA = 'dbo' 
                  AND TABLE_NAME = 'DATA_SaleItem2Product')
BEGIN
CREATE TABLE [dbo].[DATA_SaleItem2Product](
	[SaleItem2ProductId] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
	[ProductId] [int] NOT NULL,
	[SaleItemId] [int] NOT NULL,
	[OperationType] [smallint] NOT NULL,
PRIMARY KEY CLUSTERED 
(
	[SaleItem2ProductId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_DATA_SaleItem2Product_SaleItemId')
BEGIN

ALTER TABLE [dbo].[DATA_SaleItem2Product]  ADD CONSTRAINT [FK_DATA_SaleItem2Product_SaleItemId] FOREIGN KEY([SaleItemId])
REFERENCES [dbo].[DATA_SaleItem] ([SaleItemId])

END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_DATA_SaleItem2Product_ProductId')
BEGIN
ALTER TABLE [dbo].[DATA_SaleItem2Product]  ADD CONSTRAINT [FK_DATA_SaleItem2Product_ProductId] FOREIGN KEY([ProductId])
REFERENCES [dbo].[DATA_Product] ([ProductId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                 FROM sys.indexes
                WHERE Name = 'idxDATA_SaleItem2Product_SaleItemId')
BEGIN
CREATE NONCLUSTERED INDEX [idxDATA_SaleItem2Product_SaleItemId] ON [dbo].[DATA_SaleItem2Product]
(
	[SaleItemId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                 FROM sys.indexes      
                WHERE Name = 'idxDATA_SaleItem2Product_ProductId')
BEGIN
CREATE NONCLUSTERED INDEX [idxDATA_SaleItem2Product_ProductId] ON [dbo].[DATA_SaleItem2Product]
(
	[ProductId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>2727</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_HIL_CreateHILTrigger]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_HIL_CreateHILTrigger</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>CREATE Procedure dbo.otn_sp_HIL_CreateHILTrigger
	@TABLE_NAME sysname
AS 
BEGIN
	DECLARE @Logged int
	set @Logged = 0

	IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME= 'DATA_HL_Master')
	BEGIN

		
		INSERT INTO dbo.cnf_dbtable
			   (TABLENAME,
				Active,
				Logged,
				Last_UserId_Log,
				Last_WorkstationId_Log,
				Last_DateTime_Log)
		SELECT @TABLE_NAME, 
				0,
				0,  
				1,
				1,
				GetDate()
		FROM sys.tables AS t WITH(NOLOCK)
		where t.name = @TABLE_NAME
		  and t.name not in (select tablename from cnf_dbtable WITH(NOLOCK))	
		  	 
		INSERT INTO dbo.cnf_dbcolumn
			   (DBTableId,
				ColumnName,
				Active,
				logged,
				Last_UserId_Log,
				Last_WorkstationId_Log,
				Last_DateTime_Log)
		SELECT distinct HT.dbtableid AS tablesID, 
				c.name,
				0,
				0,
				1,
				1,  
				GetDate()
		FROM sys.tables AS t WITH(NOLOCK)
			INNER JOIN sys.columns c WITH(NOLOCK)				ON t.OBJECT_ID = c.OBJECT_ID 
			INNER JOIN cnf_dbtable HT WITH(NOLOCK)              ON HT.TableName = t.name	

		WHERE SCHEMA_NAME(schema_id) = 'dbo'
			and t.name = @TABLE_NAME
			AND (cast(HT.dbTableID as Varchar(5000)) + c.Name) not in (select (cast(DBTableID as Varchar(5000)) + ColumnName) from cnf_dbcolumn WITH(NOLOCK))


--ACtivate logged and active
	Update cnf_dbtable
	   set Logged = 1,
	       Active = 1
	WHERE  TableName = @TABLE_NAME
	    AND TableName in (
	  						SELECT distinct t.name AS table_name
								FROM sys.tables AS t WITH(NOLOCK)
									INNER JOIN sys.columns c WITH(NOLOCK)				ON t.OBJECT_ID = c.OBJECT_ID 	
								WHERE c.name LIKE '%LAST%LOG'
									and SCHEMA_NAME(schema_id) = 'dbo'
						)
		AND TableName in (
							SELECT distinct t.name AS table_name
								FROM sys.tables AS t WITH(NOLOCK)
									INNER JOIN sys.columns c WITH(NOLOCK)				ON t.OBJECT_ID = c.OBJECT_ID 	
								WHERE c.name LIKE '%LAST%LOG'
									and SCHEMA_NAME(schema_id) = 'dbo'
									and ((T.name like '%ADM_%') or (t.name like '%CNF_%') or
											(t.name in ('DATA_Account', 'DATA_AccountFinancial', 'DATA_AccountRelationship', 'DATA_DmgData',
														'DATA_DmgData_Translate', 'DATA_Right')))
							)
		AND TableName NOT IN (SELECT table_name
							FROM information_schema.columns WITH(NOLOCK)
							where data_type in ('NTEXT', 'TEXT')
								AND TABLE_NAME in (
	  												SELECT distinct t.name AS table_name
														FROM sys.tables AS t WITH(NOLOCK)
															INNER JOIN sys.columns c WITH(NOLOCK)				ON t.OBJECT_ID = c.OBJECT_ID 	
														WHERE c.name LIKE '%LAST%LOG'
															and SCHEMA_NAME(schema_id) = 'dbo'
												))

	Update cnf_dbcolumn
	  set Active = 1,
	      Logged = 1
	where DBTableid in (select dbtableid from cnf_dbtable WITH(NOLOCK) where active = 1 and logged = 1 and tablename = @TABLE_NAME)
	  and ColumnName not in ('Last_UserID_log', 'Last_WorkstationID_LOG', 'Last_DateTime_Log')
	  and columnName in (select c.name
							from sys.tables AS t WITH(NOLOCK)				
								INNER JOIN sys.columns c WITH(NOLOCK)				ON t.OBJECT_ID = c.OBJECT_ID 
							where t.name = @TABLE_NAME)  

	Update cnf_dbcolumn
	  set Active = 0,
	      Logged = 0
	where DBTableid in (select dbtableid from cnf_dbtable WITH(NOLOCK) where active = 1 and logged = 1 and tablename = @TABLE_NAME)
	  and columnName not in (select c.name
							from sys.tables AS t WITH(NOLOCK)				
								INNER JOIN sys.columns c WITH(NOLOCK)				ON t.OBJECT_ID = c.OBJECT_ID 
							where t.name = @TABLE_NAME)  


	select @Logged = Logged from cnf_dbtable WITH(NOLOCK) where tablename = @TABLE_NAME
	if @Logged = 1 
	BEGIN
		DECLARE @sql NVARCHAR(max),
				@SQL1 NVARCHAR(MAX)

		SET NOCOUNT ON  

		EXEC('IF OBJECT_ID (''' + @TABLE_NAME + '_CT'', ''TR'') IS NOT NULL DROP TRIGGER ' + @TABLE_NAME + '_CT')
		SELECT @sql = 
		'create trigger ' + @TABLE_NAME + '_CT on ' + @TABLE_NAME + ' FOR insert, update, delete
		as
		declare @TName varchar(128),
		        @TID nvarchar(max),
				@TLog int,  
				@PKC varchar(max),
				@PKV varchar(max),  
				@sql nvarchar(max), 
				@Type nvarchar(1),
				@MId nvarchar(max) = ''0'', 
				@ColumnID nvarchar(max) = ''0'',
				@CName varchar(128),
				@CValue1 nvarchar(max),
				@CValue2 nvarchar(max)


		if exists(select top 1 1 from cnf_system where ISNULL(BOSHistoryLogEnabled, 1) = 1 and offlinemode = 0)
		BEGIN
			select @TName = ''' + @TABLE_NAME + ''', @TID=dbtableid, @TLog = (case when Active = 1 and Logged = 1 then 1 else 0 end) from cnf_dbtable WITH(NOLOCK) where TableName=''' + @TABLE_NAME + '''

			if @TLog = 1
			begin
				if exists (select * from inserted)
				if exists (select * from deleted)
				select @Type = ''2''
				else
				select @Type = ''3''
				else
				select @Type = ''1''

				select * into #ins from inserted
				select * into #del from deleted

				select @PKC = coalesce(@PKC + '' and'', '' on'') + '' i.'' + c.COLUMN_NAME + '' = d.'' + c.COLUMN_NAME, @PKV = coalesce(@PKV+''+'','''') + ''convert(varchar(100), coalesce(i.'' + COLUMN_NAME + '',d.'' + COLUMN_NAME + ''))''
				  from INFORMATION_SCHEMA.TABLE_CONSTRAINTS p WITH(NOLOCK)
					   INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE c WITH(NOLOCK) on c.CONSTRAINT_NAME = p.CONSTRAINT_NAME and c.TABLE_NAME = p.TABLE_NAME
				 where p.TABLE_NAME=@TName and CONSTRAINT_TYPE=''PRIMARY KEY''

				DECLARE TCursor CURSOR LOCAL FOR
								select columnName,
									   dbcolumnid
								from(
								select CNF_DBColumn.ColumnName,
									CNF_DBColumn.DBColumnId,
									(case when cnf_dbcolumn.Active = 1 and cnf_dbcolumn.Logged = 1 then 1 else 0 end) Active
									from sys.tables AS t WITH(NOLOCK)				
										INNER JOIN sys.columns c WITH(NOLOCK)				ON t.OBJECT_ID = c.OBJECT_ID 
										INNER JOIN cnf_dbtable WITH(NOLOCK)					on cnf_dbtable.tablename = t.name
										INNER JOIN cnf_dbcolumn WITH(NOLOCK)				on cnf_dbcolumn.dbtableid = cnf_dbtable.dbtableid and cnf_dbcolumn.columnname = c.name
								where cnf_dbcolumn.dbtableid = @TID
								)p
								where Active = 1

				OPEN TCursor

				FETCH NEXT FROM TCursor INTO
					@CName, @ColumnID
					'
			SELECT @sql1 = '
				WHILE @@FETCH_STATUS = 0
				BEGIN

					set @sql =''Select @CValue1 = '' + @CName +'' from #ins ''
					EXEC sp_executesql @sql, N''@CValue1 nvarchar(max) OUTPUT'', @CValue1 OUTPUT

					set @sql =''Select @CValue2 = '' + @CName +'' from #del ''
					EXEC sp_executesql @sql, N''@CValue2 nvarchar(max) OUTPUT'', @CValue2 OUTPUT

					if ISNULL(@CValue1, ''&amp;*()_2'') &lt;&gt; ISNULL(@CValue2, ''&amp;*()_2'')
					begin
						if @MId = 0
						begin
							set @sql = ''insert DATA_HL_Master (OperationType, dbtableid, ReferenceId, UserId, WorkstationId, InsDateTime, DelDateTime)''
							set @sql = @sql + '' select '''''' + @Type + ''''''''												
							set @sql = @sql + '', '''''' + @TID + ''''''''		
							set @sql = @sql + '','' + @PKV		
							set @sql = @sql + '',convert(varchar(1000), i.Last_UserId_Log), convert(varchar(1000), i.Last_WorkstationId_Log), convert(varchar(1000),i.Last_DateTime_Log, 120), getdate()''
							set @sql = @sql + '' from #ins i full outer join #del d ''
							set @sql = @sql + @PKC 
							set @sql = @sql + '' SELECT @MId = SCOPE_IDENTITY()''
							EXEC sp_executesql @sql, N''@MId nvarchar(max) OUTPUT'', @MId OUTPUT
						end
						if @Type &lt;&gt; ''1''
						BEGIN
							set @sql = ''insert data_HL_Detail (MasterId, OriginalValue, ModifiedValue, DBColumnID)''						
							set @sql = @sql + '' select convert(varchar(1000),'' + @MId + ''), convert(varchar(1000),d.'' + @CName + ''), convert(varchar(1000),i.'' + @CName + '')''				
							set @sql = @sql + '', convert(varchar(1000),'' + @ColumnID + '')  ''
							set @sql = @sql + '' from #ins i full outer join #del d '' + @PKC				
							EXEC sp_executesql @sql 																	
						END		
						
					END
					FETCH NEXT FROM TCursor INTO
					   @CName, @ColumnID
				END  --While loop
				CLOSE TCursor;
				DEALLOCATE TCursor; 
			END    --Table Check
		END	-- System Check
		'

	EXEC(@sql + @sql1)
	END	
  END
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>declare @TABLE_NAME sysname

SELECT @TABLE_NAME = MIN(Table_Name)
  FROM INFORMATION_SCHEMA.Tables 
 WHERE TABLE_TYPE = 'BASE TABLE' 
	AND TABLE_NAME != 'sysdiagrams'
	AND TABLE_SCHEMA = 'dbo'


WHILE @TABLE_NAME IS NOT NULL
BEGIN
	Exec otn_sp_HIL_CreateHILTrigger @TABLE_NAME

	SELECT @TABLE_NAME = MIN(Table_Name)
	  FROM INFORMATION_SCHEMA.Tables 
     WHERE TABLE_NAME &gt; @TABLE_NAME
	   AND TABLE_TYPE = 'BASE TABLE' 
	   AND TABLE_NAME != 'sysdiagrams'
	   AND TABLE_SCHEMA = 'dbo'

END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>ecandido</ADDEDBY><SQLVERSION>2726</SQLVERSION><RMTRACKLINK>82436</RMTRACKLINK><REASON>Add End Validity Dates for Users</REASON><TABLENAMES>CNF_User=UserId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'ExpirationDate ' AND
                Object_ID  = Object_ID(N'CNF_User'))
BEGIN
  ALTER TABLE CNF_User
  ADD ExpirationDate DATETIME
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>pchen</ADDEDBY><SQLVERSION>2725</SQLVERSION><RMTRACKLINK>79137</RMTRACKLINK><REASON>Adding DocTemplateId column to DATA_Ticket2Document</REASON><TABLENAMES>DATA_Ticket2Document=Ticket2DocumentId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'DocTemplateId ' AND
                Object_ID  = Object_ID(N'DATA_Ticket2Document'))
BEGIN
  Alter Table DATA_Ticket2Document
  Add DocTemplateId Integer Null
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_DocTemplateId')
BEGIN
Alter table [DATA_Ticket2Document] 
ADD CONSTRAINT [FK_DocTemplateId] foreign key([DocTemplateId]) references [CNF_DocTemplate] ([DocTemplateId])
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2724</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2723</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2722</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2721</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2720</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2719</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2718</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2717</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2716</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2715</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2714</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2713</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2712</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2711</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2710</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2709</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2708</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2707</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2706</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2705</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2704</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2703</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2702</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2701</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2700</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2699</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2698</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2697</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2696</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2695</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2694</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2693</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2692</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2691</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2690</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2689</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2688</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2687</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2686</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2685</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2684</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2683</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2682</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2681</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2680</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2679</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2678</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2677</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2676</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2675</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2674</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2673</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2672</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2671</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2670</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2669</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2668</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2667</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2666</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2665</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2664</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2663</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2662</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2661</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2660</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2659</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2658</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2657</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2656</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2655</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2654</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2653</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2652</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2651</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2650</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2649</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2648</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2647</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2646</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2645</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2644</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2643</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2642</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2641</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2640</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2639</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2638</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2637</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2636</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2635</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2634</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2633</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2632</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2631</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2630</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2629</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2628</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2627</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2626</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2625</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2624</SQLVERSION><RMTRACKLINK>78709</RMTRACKLINK><REASON>[0] Adding ExternalCode column to CNF_Site
[1] Create table DATA_DeviceOperaions
[2] Create foreign keys
[3] Create indexes</REASON><TABLENAMES>CNF_Site=SiteId
DATA_DeviceOperations=DevOpId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'ExternalCode' AND
                Object_ID  = Object_ID(N'CNF_Site'))
BEGIN
  Alter Table CNF_Site
  Add ExternalCode NVarChar(50) Null
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                WHERE TABLE_SCHEMA = 'dbo' 
                  AND TABLE_NAME = 'DATA_DeviceOperations')
BEGIN
Create table [DATA_DeviceOperations]
(
	[DevOpId] Integer Identity(1,1) NOT NULL,
	[Last_UserId_Log] Integer NOT NULL,
	[Last_WorkstationId_Log] Integer NOT NULL,
	[Last_DateTime_Log] Datetime NULL,
	[DeviceCode] Nvarchar(20) NULL,
	[OperationTimeStamp] Datetime NULL,
	[OperationCategory] Nvarchar(10) NULL,
	[OperationType] Nvarchar(10) NULL,
	[OperationSubType] Nvarchar(10) NULL,
	[OperationNo] Integer NULL,
	[OperationSeq] Integer NULL,
	[OperationValue] Float NULL,
	[OperationInfo] Nvarchar(30) NULL,
	[OperationExtInfo] Nvarchar(3000) NULL,
Primary Key ([DevOpId])
) 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                 FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_DeviceOperations_Last_UserId_Log')
BEGIN
  ALTER TABLE [dbo].[DATA_DeviceOperations] WITH CHECK ADD CONSTRAINT [FK_DATA_DeviceOperations_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log])
  REFERENCES [dbo].[CNF_User] ([UserId])

  ALTER TABLE [dbo].[DATA_DeviceOperations] CHECK CONSTRAINT [FK_DATA_DeviceOperations_Last_UserId_Log]
END

IF NOT EXISTS (SELECT * 
                 FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_DeviceOperations_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE [dbo].[DATA_DeviceOperations] WITH CHECK ADD CONSTRAINT [FK_DATA_DeviceOperations_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log])
  REFERENCES [dbo].[CNF_Workstation] ([WorkstationId])

  ALTER TABLE [dbo].[DATA_DeviceOperations] CHECK CONSTRAINT [FK_DATA_DeviceOperations_Last_WorkstationId_Log]
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * 
                 FROM sys.indexes
                WHERE Name = 'Idx_DevOp_DevCode_OpCat')
BEGIN
  Create Index [Idx_DevOp_DevCode_OpCat] ON [DATA_DeviceOperations] ([DeviceCode] ,[OperationCategory] )
END 

IF NOT EXISTS (SELECT * 
                 FROM sys.indexes
                WHERE Name = 'Idx_DevOp_DevCode_OpCat_OpType')
BEGIN
  Create Index [Idx_DevOp_DevCode_OpCat_OpType] ON [DATA_DeviceOperations] ([DeviceCode] ,[OperationCategory] ,[OperationType] )
END 

IF NOT EXISTS (SELECT * 
                 FROM sys.indexes
                WHERE Name = 'Idx_DevOp_DevCode_OpCat_OpType_OpSubType')
BEGIN
  Create Index [Idx_DevOp_DevCode_OpCat_OpType_OpSubType] ON [DATA_DeviceOperations] ([DeviceCode] ,[OperationCategory] ,[OperationType] ,[OperationSubType] )
END 

</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2623</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>Add  ExtInfoDocTemplateId on CNF_MAtrixCellInfo
Add RequireSO on RES_CNF_Event</REASON><TABLENAMES>CNF_MatrixCellInfo=MatrixCellInfoId
RES_CNF_Event=EventId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'ExtInfoDocTemplateId' AND
                Object_ID  = Object_ID(N'CNF_MatrixCellInfo'))
BEGIN
  Alter Table CNF_MatrixCellInfo
  Add ExtInfoDocTemplateId integer Null
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_ExtInfoDocTemplateId')
BEGIN
Alter table [CNF_MatrixCellInfo] 
ADD CONSTRAINT [FK_ExtInfoDocTemplateId] foreign key([ExtInfoDocTemplateId]) references [CNF_DocTemplate] ([DocTemplateId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'RequireSO' AND
                Object_ID  = Object_ID(N'RES_CNF_Event'))
BEGIN
  Alter Table RES_CNF_Event
  Add RequireSO smallint Null
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>2622</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>if not exists(SELECT * 
				FROM sys.indexes 
				WHERE name='IDX_DATA_HL_Detail_MasterId' AND object_id = OBJECT_ID('dbo.DATA_HL_Detail'))
begin
  CREATE NONCLUSTERED INDEX [IDX_DATA_HL_Detail_MasterId]
  ON [dbo].[DATA_HL_Detail] ([MasterId])
end</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>if not exists(SELECT * 
				FROM sys.indexes 
				WHERE name='IDX_DATA_HL_Master_DBTableId' AND object_id = OBJECT_ID('dbo.DATA_HL_Master'))
begin
	CREATE NONCLUSTERED INDEX [IDX_DATA_HL_Master_DBTableId]
	ON [dbo].[DATA_HL_Master] ([DBTableId])
	INCLUDE ([MasterId],[ReferenceId],[OperationType],[UserId],[WorkstationId],[InsDateTime])
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>2621</SQLVERSION><RMTRACKLINK>83176</RMTRACKLINK><REASON>Offline Configuration Sync is failing on Delete Sale</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>if exists(select * from sys.triggers where name = 'ddl_trig_alterTable' )
  DROP TRIGGER ddl_trig_alterTable ON DATABASE;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>Create TRIGGER [ddl_trig_alterTable]   
ON DATABASE   
FOR ALTER_TABLE  
AS  
DECLARE @Data XML 
DECLARE @TableName sysname 
DECLARE @Command varchar(max)

SET @Data = EventData()
SET @TableName = @Data.value('(/EVENT_INSTANCE/ObjectName)[1]', 'nvarchar(200)')
SET @Command =  @Data.value('(/EVENT_INSTANCE/TSQLCommand/CommandText)[1]', 'varchar(max)')


if CHARINDEX('constraint all' ,@Command) = 0
begin

	INSERT INTO dbo.cnf_dbcolumn
			(DBTableId,
			ColumnName,
			Active,
			LOgged,
			Last_UserId_Log,
			Last_WorkstationId_Log,
			Last_DateTime_Log)  
	SELECT distinct HT.dbtableid AS tablesID, 
			c.name,
			HT.Active,
			HT.logged,
			1,
			1,  
			GetDate()
	FROM sys.tables AS t 
				INNER JOIN sys.columns c				ON t.OBJECT_ID = c.OBJECT_ID 
				INNER JOIN cnf_dbtable HT               ON HT.TableName = t.name	
	WHERE SCHEMA_NAME(schema_id) = 'dbo'
		and t.name = @TableName
		AND (cast(HT.dbTableID as Varchar(5000)) + c.Name) not in (select (cast(DBTableID as Varchar(5000)) + ColumnName) from cnf_dbcolumn)


	update cnf_dbcolumn
	   set Active = 0,
		   logged = 0
	 where  ColumnName not in (SELECT c.name
								FROM sys.tables AS t 
											INNER JOIN sys.columns c				ON t.OBJECT_ID = c.OBJECT_ID 
											INNER JOIN cnf_dbtable HT               ON HT.TableName = t.name	
								WHERE SCHEMA_NAME(schema_id) = 'dbo'
									and t.name = @TableName
								)
	   and dbtableid in (select dbtableid from cnf_dbtable where tablename = @TableName)

	Exec otn_sp_HIL_CreateHILTrigger @TableName
END



</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_HIL_CreateHILTrigger]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_HIL_CreateHILTrigger</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>CREATE Procedure dbo.otn_sp_HIL_CreateHILTrigger
	@TABLE_NAME sysname
AS 
BEGIN
	DECLARE @Logged int
	set @Logged = 0

	IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME= 'DATA_HL_Master')
	BEGIN

		
		INSERT INTO dbo.cnf_dbtable
			   (TABLENAME,
				Active,
				Logged,
				Last_UserId_Log,
				Last_WorkstationId_Log,
				Last_DateTime_Log)
		SELECT @TABLE_NAME, 
				0,
				0,  
				1,
				1,
				GetDate()
		FROM sys.tables AS t WITH(NOLOCK)
		where t.name = @TABLE_NAME
		  and t.name not in (select tablename from cnf_dbtable WITH(NOLOCK))	
		  	 
		INSERT INTO dbo.cnf_dbcolumn
			   (DBTableId,
				ColumnName,
				Active,
				logged,
				Last_UserId_Log,
				Last_WorkstationId_Log,
				Last_DateTime_Log)
		SELECT distinct HT.dbtableid AS tablesID, 
				c.name,
				0,
				0,
				1,
				1,  
				GetDate()
		FROM sys.tables AS t WITH(NOLOCK)
			INNER JOIN sys.columns c WITH(NOLOCK)				ON t.OBJECT_ID = c.OBJECT_ID 
			INNER JOIN cnf_dbtable HT WITH(NOLOCK)              ON HT.TableName = t.name	

		WHERE SCHEMA_NAME(schema_id) = 'dbo'
			and t.name = @TABLE_NAME
			AND (cast(HT.dbTableID as Varchar(5000)) + c.Name) not in (select (cast(DBTableID as Varchar(5000)) + ColumnName) from cnf_dbcolumn WITH(NOLOCK))


--ACtivate logged and active
	Update cnf_dbtable
	   set Logged = 1,
	       Active = 1
	WHERE  TableName = @TABLE_NAME
	    AND TableName in (
	  						SELECT distinct t.name AS table_name
								FROM sys.tables AS t WITH(NOLOCK)
									INNER JOIN sys.columns c WITH(NOLOCK)				ON t.OBJECT_ID = c.OBJECT_ID 	
								WHERE c.name LIKE '%LAST%LOG'
									and SCHEMA_NAME(schema_id) = 'dbo'
						)
		AND TableName in (
							SELECT distinct t.name AS table_name
								FROM sys.tables AS t WITH(NOLOCK)
									INNER JOIN sys.columns c WITH(NOLOCK)				ON t.OBJECT_ID = c.OBJECT_ID 	
								WHERE c.name LIKE '%LAST%LOG'
									and SCHEMA_NAME(schema_id) = 'dbo'
									and ((T.name like '%ADM_%') or (t.name like '%CNF_%') or
											(t.name in ('DATA_Account', 'DATA_AccountFinancial', 'DATA_AccountRelationship', 'DATA_DmgData',
														'DATA_DmgData_Translate', 'DATA_Right')))
							)
		AND TableName NOT IN (SELECT table_name
							FROM information_schema.columns WITH(NOLOCK)
							where data_type in ('NTEXT', 'TEXT')
								AND TABLE_NAME in (
	  												SELECT distinct t.name AS table_name
														FROM sys.tables AS t WITH(NOLOCK)
															INNER JOIN sys.columns c WITH(NOLOCK)				ON t.OBJECT_ID = c.OBJECT_ID 	
														WHERE c.name LIKE '%LAST%LOG'
															and SCHEMA_NAME(schema_id) = 'dbo'
												))

	Update cnf_dbcolumn
	  set Active = 1,
	      Logged = 1
	where DBTableid in (select dbtableid from cnf_dbtable WITH(NOLOCK) where active = 1 and logged = 1 and tablename = @TABLE_NAME)
	  and ColumnName not in ('Last_UserID_log', 'Last_WorkstationID_LOG', 'Last_DateTime_Log')
	  and columnName in (select c.name
							from sys.tables AS t WITH(NOLOCK)				
								INNER JOIN sys.columns c WITH(NOLOCK)				ON t.OBJECT_ID = c.OBJECT_ID 
							where t.name = @TABLE_NAME)  

	Update cnf_dbcolumn
	  set Active = 0,
	      Logged = 0
	where DBTableid in (select dbtableid from cnf_dbtable WITH(NOLOCK) where active = 1 and logged = 1 and tablename = @TABLE_NAME)
	  and columnName not in (select c.name
							from sys.tables AS t WITH(NOLOCK)				
								INNER JOIN sys.columns c WITH(NOLOCK)				ON t.OBJECT_ID = c.OBJECT_ID 
							where t.name = @TABLE_NAME)  


	select @Logged = Logged from cnf_dbtable WITH(NOLOCK) where tablename = @TABLE_NAME
	if @Logged = 1 
	BEGIN
		DECLARE @sql NVARCHAR(max),
				@SQL1 NVARCHAR(MAX)

		SET NOCOUNT ON  

		EXEC('IF OBJECT_ID (''' + @TABLE_NAME + '_CT'', ''TR'') IS NOT NULL DROP TRIGGER ' + @TABLE_NAME + '_CT')
		SELECT @sql = 
		'create trigger ' + @TABLE_NAME + '_CT on ' + @TABLE_NAME + ' FOR insert, update, delete
		as
		declare @TName varchar(128),
		        @TID nvarchar(max),
				@TLog int,  
				@PKC varchar(max),
				@PKV varchar(max),  
				@sql nvarchar(max), 
				@Type nvarchar(1),
				@MId nvarchar(max) = ''0'', 
				@ColumnID nvarchar(max) = ''0'',
				@CName varchar(128),
				@CValue1 nvarchar(max),
				@CValue2 nvarchar(max)


		if exists(select top 1 1 from cnf_system where ISNULL(BOSHistoryLogEnabled, 1) = 1 and offlinemode = 0)
		BEGIN
			select @TName = ''' + @TABLE_NAME + ''', @TID=dbtableid, @TLog = (case when Active = 1 and Logged = 1 then 1 else 0 end) from cnf_dbtable WITH(NOLOCK) where TableName=''' + @TABLE_NAME + '''

			if @TLog = 1
			begin
				if exists (select * from inserted)
				if exists (select * from deleted)
				select @Type = ''2''
				else
				select @Type = ''3''
				else
				select @Type = ''1''

				select * into #ins from inserted
				select * into #del from deleted

				select @PKC = coalesce(@PKC + '' and'', '' on'') + '' i.'' + c.COLUMN_NAME + '' = d.'' + c.COLUMN_NAME, @PKV = coalesce(@PKV+''+'','''') + ''convert(varchar(100), coalesce(i.'' + COLUMN_NAME + '',d.'' + COLUMN_NAME + ''))''
				  from INFORMATION_SCHEMA.TABLE_CONSTRAINTS p WITH(NOLOCK)
					   INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE c WITH(NOLOCK) on c.CONSTRAINT_NAME = p.CONSTRAINT_NAME and c.TABLE_NAME = p.TABLE_NAME
				 where p.TABLE_NAME=@TName and CONSTRAINT_TYPE=''PRIMARY KEY''

				DECLARE TCursor CURSOR LOCAL FOR
								select columnName,
									   dbcolumnid
								from(
								select CNF_DBColumn.ColumnName,
									CNF_DBColumn.DBColumnId,
									(case when cnf_dbcolumn.Active = 1 and cnf_dbcolumn.Logged = 1 then 1 else 0 end) Active
									from sys.tables AS t WITH(NOLOCK)				
										INNER JOIN sys.columns c WITH(NOLOCK)				ON t.OBJECT_ID = c.OBJECT_ID 
										INNER JOIN cnf_dbtable WITH(NOLOCK)					on cnf_dbtable.tablename = t.name
										INNER JOIN cnf_dbcolumn WITH(NOLOCK)				on cnf_dbcolumn.dbtableid = cnf_dbtable.dbtableid and cnf_dbcolumn.columnname = c.name
								where cnf_dbcolumn.dbtableid = @TID
								)p
								where Active = 1

				OPEN TCursor

				FETCH NEXT FROM TCursor INTO
					@CName, @ColumnID
					'
			SELECT @sql1 = '
				WHILE @@FETCH_STATUS = 0
				BEGIN

					set @sql =''Select @CValue1 = '' + @CName +'' from #ins ''
					EXEC sp_executesql @sql, N''@CValue1 nvarchar(max) OUTPUT'', @CValue1 OUTPUT

					set @sql =''Select @CValue2 = '' + @CName +'' from #del ''
					EXEC sp_executesql @sql, N''@CValue2 nvarchar(max) OUTPUT'', @CValue2 OUTPUT

					if ISNULL(@CValue1, ''&amp;*()_2'') &lt;&gt; ISNULL(@CValue2, ''&amp;*()_2'')
					begin
						if @MId = 0
						begin
							set @sql = ''insert DATA_HL_Master (OperationType, dbtableid, ReferenceId, UserId, WorkstationId, InsDateTime, DelDateTime)''
							set @sql = @sql + '' select '''''' + @Type + ''''''''												
							set @sql = @sql + '', '''''' + @TID + ''''''''		
							set @sql = @sql + '','' + @PKV		
							set @sql = @sql + '',convert(varchar(1000),i.Last_UserId_Log), convert(varchar(1000), i.Last_WorkstationId_Log), convert(varchar(1000),i.Last_DateTime_Log), getdate()''
							set @sql = @sql + '' from #ins i full outer join #del d ''
							set @sql = @sql + @PKC 
							set @sql = @sql + '' SELECT @MId = SCOPE_IDENTITY()''
							EXEC sp_executesql @sql, N''@MId nvarchar(max) OUTPUT'', @MId OUTPUT
						end
						if @Type &lt;&gt; ''1''
						BEGIN
							set @sql = ''insert data_HL_Detail (MasterId, OriginalValue, ModifiedValue, DBColumnID)''						
							set @sql = @sql + '' select convert(varchar(1000),'' + @MId + ''), convert(varchar(1000),d.'' + @CName + ''), convert(varchar(1000),i.'' + @CName + '')''				
							set @sql = @sql + '', convert(varchar(1000),'' + @ColumnID + '')  ''
							set @sql = @sql + '' from #ins i full outer join #del d '' + @PKC				
							EXEC sp_executesql @sql 																	
						END		
						
					END
					FETCH NEXT FROM TCursor INTO
					   @CName, @ColumnID
				END  --While loop
				CLOSE TCursor;
				DEALLOCATE TCursor; 
			END    --Table Check
		END	-- System Check
		'

	EXEC(@sql + @sql1)
	END	
  END
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>declare @TABLE_NAME sysname

SELECT @TABLE_NAME = MIN(Table_Name)
  FROM INFORMATION_SCHEMA.Tables 
 WHERE TABLE_TYPE = 'BASE TABLE' 
	AND TABLE_NAME != 'sysdiagrams'
	AND TABLE_SCHEMA = 'dbo'


WHILE @TABLE_NAME IS NOT NULL
BEGIN
	Exec otn_sp_HIL_CreateHILTrigger @TABLE_NAME

	SELECT @TABLE_NAME = MIN(Table_Name)
	  FROM INFORMATION_SCHEMA.Tables 
     WHERE TABLE_NAME &gt; @TABLE_NAME
	   AND TABLE_TYPE = 'BASE TABLE' 
	   AND TABLE_NAME != 'sysdiagrams'
	   AND TABLE_SCHEMA = 'dbo'

END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>2620</SQLVERSION><RMTRACKLINK>72604</RMTRACKLINK><REASON>New column in DATA_HL_Master: 'DelDateTime'</REASON><TABLENAMES>DATA_HL_Master=MasterId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'DelDateTime' AND
                Object_ID  = Object_ID(N'DATA_HL_Master'))
BEGIN
  Alter Table DATA_HL_Master
  Add DelDateTime Datetime Null
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fesposito</ADDEDBY><SQLVERSION>2619</SQLVERSION><RMTRACKLINK>83003</RMTRACKLINK><REASON></REASON><TABLENAMES>TPR_CNF_Group=GroupId
TPR_DATA_MediaIdentifier=MediaIdentifierId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'TPR_CNF_Group'))
                    
BEGIN
Create table [TPR_CNF_Group]
(
	[GroupId] Integer Identity(1,1) NOT NULL,
	[Code] Nvarchar(10),
	[Name] Nvarchar(30),
	[Description] Nvarchar(255),
	[Enabled] Smallint,
	[Threshold] Integer,
	[Last_UserId_Log] Integer,
	[Last_WorkstationId_Log] Integer,
	[Last_DateTime_Log] Datetime,
Primary Key ([GroupId])
) 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'TPR_DATA_MediaIdentifier'))
                    
BEGIN
Create table [TPR_DATA_MediaIdentifier]
(
	[MediaIdentifierId] Integer Identity(1,1) NOT NULL,
	[GroupId] Integer,
	[IdentifierCode] Nvarchar(400),
	[Last_UserId_Log] Integer,
	[Last_WorkstationId_Log] Integer,
	[Last_DateTime_Log] Datetime,
Primary Key ([MediaIdentifierId])
) 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_TPR_CNF_Group_UserId')
BEGIN
  ALTER TABLE TPR_CNF_Group
  ADD CONSTRAINT [FK_TPR_CNF_Group_UserId] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_TPR_CNF_Group_WorkstationId')
BEGIN
  ALTER TABLE TPR_CNF_Group
  ADD CONSTRAINT [FK_TPR_CNF_Group_WorkstationId] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_TPR_DATA_MediaIdentifier_WorkstationId')
BEGIN
  ALTER TABLE TPR_DATA_MediaIdentifier
  ADD CONSTRAINT [FK_TPR_DATA_MediaIdentifier_WorkstationId] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_TPR_DATA_MediaIdentifier_UserId')
BEGIN
  ALTER TABLE TPR_DATA_MediaIdentifier
  ADD CONSTRAINT [FK_TPR_DATA_MediaIdentifier_UserId] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_TPR_DATA_MediaIdentifier_GroupId')
BEGIN
  ALTER TABLE TPR_DATA_MediaIdentifier
  ADD CONSTRAINT [FK_TPR_DATA_MediaIdentifier_GroupId] FOREIGN KEY([GroupId]) 
  REFERENCES [TPR_CNF_Group] ([GroupId])
END
</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>lfornaroli</ADDEDBY><SQLVERSION>2618</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>Add FK to docTempalte in Survey Configuration</REASON><TABLENAMES>CNF_Survey=SurveyId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'DocTemplateId' AND
                Object_ID  = Object_ID(N'CNF_Survey'))
BEGIN
Alter table CNF_Survey
 add DocTemplateId Integer NULL
END

</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_CNF_Survey_DocTemplateId')
BEGIN
Alter table [CNF_Survey] 
add CONSTRAINT [FK_CNF_Survey_DocTemplateId] foreign key([DocTemplateId]) references [CNF_DocTemplate] ([DocTemplateId]) 
END


</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>marosio</ADDEDBY><SQLVERSION>2617</SQLVERSION><RMTRACKLINK>79923</RMTRACKLINK><REASON>Adding the reference between Event and Route</REASON><TABLENAMES>CNF_Location=LocationId
CNF_LocationRoute=LocationRouteId
CNF_Event=EventId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.foreign_keys WHERE Name = 'FK_CNF_Location_LocationRouteId')
BEGIN
  ALTER TABLE CNF_Location
  DROP CONSTRAINT [FK_CNF_Location_LocationRouteId] 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns WHERE Name = N'LocationRouteId' AND Object_ID  = Object_ID(N'CNF_Location'))
BEGIN
  ALTER TABLE CNF_Location
  DROP COLUMN LocationRouteId
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'LocationRouteId' AND
                Object_ID  = Object_ID(N'CNF_Event'))
BEGIN
  ALTER TABLE CNF_Event
  ADD LocationRouteId Integer null 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Event_LocationRouteId')
BEGIN
  ALTER TABLE CNF_Event
  ADD CONSTRAINT [FK_CNF_Event_LocationRouteId] FOREIGN KEY([LocationRouteId]) 
  REFERENCES [CNF_LocationRoute] ([LocationRouteId])
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>2616</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES>RES_CNF_Requirement=Requirementid
RES_CNF_RequirementTemplate=RequirementTemplateId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>if exists(select * from sys.triggers where name = 'ddl_trig_alterTable' )
  DROP TRIGGER ddl_trig_alterTable ON DATABASE;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>Create TRIGGER [ddl_trig_alterTable]   
ON DATABASE   
FOR ALTER_TABLE  
AS  
DECLARE @Data XML 
DECLARE @TableName sysname 

SET @Data = EventData()
SET @TableName = @Data.value('(/EVENT_INSTANCE/ObjectName)[1]', 'nvarchar(100)')


INSERT INTO dbo.cnf_dbcolumn
		(DBTableId,
		ColumnName,
		Active,
        LOgged,
		Last_UserId_Log,
		Last_WorkstationId_Log,
		Last_DateTime_Log)  
SELECT distinct HT.dbtableid AS tablesID, 
		c.name,
		HT.Active,
		HT.logged,
        1,
		1,  
		GetDate()
FROM sys.tables AS t 
			INNER JOIN sys.columns c				ON t.OBJECT_ID = c.OBJECT_ID 
			INNER JOIN cnf_dbtable HT               ON HT.TableName = t.name	
WHERE SCHEMA_NAME(schema_id) = 'dbo'
	and t.name = @TableName
	AND (cast(HT.dbTableID as Varchar(5000)) + c.Name) not in (select (cast(DBTableID as Varchar(5000)) + ColumnName) from cnf_dbcolumn)


update cnf_dbcolumn
   set Active = 0,
       logged = 0
 where  ColumnName not in (SELECT c.name
							FROM sys.tables AS t 
										INNER JOIN sys.columns c				ON t.OBJECT_ID = c.OBJECT_ID 
										INNER JOIN cnf_dbtable HT               ON HT.TableName = t.name	
							WHERE SCHEMA_NAME(schema_id) = 'dbo'
								and t.name = @TableName
							)
   and dbtableid in (select dbtableid from cnf_dbtable where tablename = @TableName)

Exec otn_sp_HIL_CreateHILTrigger @TableName</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Note' AND
                Object_ID  = Object_ID(N'RES_CNF_Requirement'))
BEGIN
  ALTER TABLE RES_CNF_Requirement
  ADD Note_Convert varchar(max)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Note_Convert' AND
                Object_ID  = Object_ID(N'RES_CNF_Requirement'))
BEGIN
	Update RES_CNF_Requirement
	   Set Note_Convert = Note
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'NOte' AND
                Object_ID  = Object_ID(N'RES_CNF_Requirement'))
BEGIN
  ALTER TABLE RES_CNF_Requirement
  Drop Column Note
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Note_Convert' AND
                Object_ID  = Object_ID(N'RES_CNF_Requirement'))
BEGIN 
	EXEC sp_rename 'RES_CNF_Requirement.Note_Convert', 'Note', 'COLUMN'
END </SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Note' AND
                Object_ID  = Object_ID(N'RES_CNF_RequirementTemplate'))
BEGIN
  ALTER TABLE RES_CNF_RequirementTemplate
  ADD Note_Convert varchar(max)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Note_Convert' AND
                Object_ID  = Object_ID(N'RES_CNF_RequirementTemplate'))
BEGIN
	Update RES_CNF_RequirementTemplate
	   Set Note_Convert = Note
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'NOte' AND
                Object_ID  = Object_ID(N'RES_CNF_RequirementTemplate'))
BEGIN
  ALTER TABLE RES_CNF_RequirementTemplate
  Drop Column Note
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Note_Convert' AND
                Object_ID  = Object_ID(N'RES_CNF_RequirementTemplate'))
BEGIN 
	EXEC sp_rename 'RES_CNF_RequirementTemplate.Note_Convert', 'Note', 'COLUMN'
END </SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>2615</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE 
                Object_ID  = Object_ID(N'data_hl_detail'))
BEGIN
   delete from data_hl_detail;
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE 
                Object_ID  = Object_ID(N'data_hl_master'))
BEGIN
   delete from data_hl_master;
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE 
                Object_ID  = Object_ID(N'cnf_dbcolumn'))
BEGIN
   delete from cnf_dbcolumn;
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE 
                Object_ID  = Object_ID(N'cnf_dbtable'))
BEGIN
   delete from cnf_dbtable;
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>--if exists(select * from sys.triggers where name = 'ddl_trig_alterTable' )
  --DROP TRIGGER ddl_trig_alterTable ON DATABASE;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>--Create TRIGGER ddl_trig_alterTable   
--ON DATABASE   
--FOR ALTER_TABLE  
--AS  
--DECLARE @Data XML 
--DECLARE @TableName sysname 

--SET @Data = EventData()
--SET @TableName = @Data.value('(/EVENT_INSTANCE/ObjectName)[1]', 'nvarchar(100)')


--INSERT INTO dbo.cnf_dbcolumn
--		(DBTableId,
--		ColumnName,
--		Active,
--        LOgged,
--		Last_UserId_Log,
--		Last_WorkstationId_Log,
--		Last_DateTime_Log)  
--SELECT distinct HT.dbtableid AS tablesID, 
--		c.name,
--		HT.Active,
--		HT.logged,
--        1,
--		1,  
--		GetDate()
--FROM sys.tables AS t 
--			INNER JOIN sys.columns c				ON t.OBJECT_ID = c.OBJECT_ID 
--			INNER JOIN cnf_dbtable HT               ON HT.TableName = t.name	
--WHERE SCHEMA_NAME(schema_id) = 'dbo'
--	and t.name = @Data.value('(/EVENT_INSTANCE/ObjectName)[1]', 'nvarchar(100)')
--	AND (cast(HT.dbTableID as Varchar(5000)) + c.Name) not in (select (cast(DBTableID as Varchar(5000)) + ColumnName) from cnf_dbcolumn)


--update cnf_dbcolumn
--   set Active = 0,
--       logged = 0
-- where  ColumnName not in (SELECT c.name
--							FROM sys.tables AS t 
--										INNER JOIN sys.columns c				ON t.OBJECT_ID = c.OBJECT_ID 
--										INNER JOIN cnf_dbtable HT               ON HT.TableName = t.name	
--							WHERE SCHEMA_NAME(schema_id) = 'dbo'
--								and t.name = @Data.value('(/EVENT_INSTANCE/ObjectName)[1]', 'nvarchar(100)')
--							)
--   and dbtableid in (select dbtableid from cnf_dbtable where tablename = @Data.value('(/EVENT_INSTANCE/ObjectName)[1]', 'nvarchar(100)'</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>--declare @TABLE_NAME sysname

--SELECT @TABLE_NAME = MIN(Table_Name)
--  FROM INFORMATION_SCHEMA.Tables 
-- WHERE TABLE_TYPE = 'BASE TABLE' 
--	AND TABLE_NAME != 'sysdiagrams'
--	AND TABLE_SCHEMA = 'dbo'


--WHILE @TABLE_NAME IS NOT NULL
--BEGIN
--	Exec otn_sp_HIL_CreateHILTrigger @TABLE_NAME

--	SELECT @TABLE_NAME = MIN(Table_Name)
--	  FROM INFORMATION_SCHEMA.Tables 
--     WHERE TABLE_NAME &gt; @TABLE_NAME
--	   AND TABLE_TYPE = 'BASE TABLE' 
--	   AND TABLE_NAME != 'sysdiagrams'
--	   AND TABLE_SCHEMA = 'dbo'

--E</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>marosio</ADDEDBY><SQLVERSION>2614</SQLVERSION><RMTRACKLINK>79923</RMTRACKLINK><REASON>Adding the reference between Location and Route</REASON><TABLENAMES>CNF_Location=LocationId
CNF_LocationRoute=LocationRouteId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'LocationRouteId' AND
                Object_ID  = Object_ID(N'CNF_Location'))
BEGIN
  ALTER TABLE CNF_Location
  ADD LocationRouteId Integer null 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Location_LocationRouteId')
BEGIN
  ALTER TABLE CNF_Location
  ADD CONSTRAINT [FK_CNF_Location_LocationRouteId] FOREIGN KEY([LocationRouteId]) 
  REFERENCES [CNF_LocationRoute] ([LocationRouteId])
END
</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>2613</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE 
                Object_ID  = Object_ID(N'data_hl_detail'))
BEGIN
   delete from data_hl_detail;
END


</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE 
                Object_ID  = Object_ID(N'data_hl_master'))
BEGIN
   delete from data_hl_master;
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE 
                Object_ID  = Object_ID(N'cnf_dbcolumn'))
BEGIN
   delete from cnf_dbcolumn;
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE 
                Object_ID  = Object_ID(N'cnf_dbtable'))
BEGIN
   delete from cnf_dbtable;
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>--if exists(select * from sys.triggers where name = 'ddl_trig_alterTable' )
 -- DROP TRIGGER ddl_trig_alterTable ON DATABASE;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>--Create TRIGGER ddl_trig_alterTable   
--ON DATABASE   
--FOR ALTER_TABLE  
--AS  
--DECLARE @Data XML 
--DECLARE @TableName sysname 

--SET @Data = EventData()
--SET @TableName = @Data.value('(/EVENT_INSTANCE/ObjectName)[1]', 'nvarchar(100)')


--INSERT INTO dbo.cnf_dbcolumn
--		(DBTableId,
--		ColumnName,
--		Active,
--        LOgged,
--		Last_UserId_Log,
--		Last_WorkstationId_Log,
--		Last_DateTime_Log)  
--SELECT distinct HT.dbtableid AS tablesID, 
--		c.name,
--		HT.Active,
--		HT.logged,
--        1,
--		1,  
--		GetDate()
--FROM sys.tables AS t 
--			INNER JOIN sys.columns c				ON t.OBJECT_ID = c.OBJECT_ID 
--			INNER JOIN cnf_dbtable HT               ON HT.TableName = t.name	
--WHERE SCHEMA_NAME(schema_id) = 'dbo'
--	and t.name = @Data.value('(/EVENT_INSTANCE/ObjectName)[1]', 'nvarchar(100)')
--	AND (cast(HT.dbTableID as Varchar(5000)) + c.Name) not in (select (cast(DBTableID as Varchar(5000)) + ColumnName) from cnf_dbcolumn)


--update cnf_dbcolumn
--   set Active = 0,
--       logged = 0
-- where  ColumnName not in (SELECT c.name
--							FROM sys.tables AS t 
--										INNER JOIN sys.columns c				ON t.OBJECT_ID = c.OBJECT_ID 
--										INNER JOIN cnf_dbtable HT               ON HT.TableName = t.name	
--							WHERE SCHEMA_NAME(schema_id) = 'dbo'
--								and t.name = @Data.value('(/EVENT_INSTANCE/ObjectName)[1]', 'nvarchar(100)')
--							)
                                    
                                    
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_HIL_CreateHILTrigger]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_HIL_CreateHILTrigger</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>CREATE Procedure dbo.otn_sp_HIL_CreateHILTrigger
	@TABLE_NAME sysname
AS 
BEGIN
	DECLARE @Logged int
	set @Logged = 0

	IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME= 'DATA_HL_Master')
	BEGIN

		
		INSERT INTO dbo.cnf_dbtable
			   (TABLENAME,
				Active,
				Logged,
				Last_UserId_Log,
				Last_WorkstationId_Log,
				Last_DateTime_Log)
		SELECT @TABLE_NAME, 
				0,
				0,  
				1,
				1,
				GetDate()
		FROM sys.tables AS t WITH(NOLOCK)
		where t.name = @TABLE_NAME
		  and t.name not in (select tablename from cnf_dbtable WITH(NOLOCK))	
		  	 
		INSERT INTO dbo.cnf_dbcolumn
			   (DBTableId,
				ColumnName,
				Active,
				logged,
				Last_UserId_Log,
				Last_WorkstationId_Log,
				Last_DateTime_Log)
		SELECT distinct HT.dbtableid AS tablesID, 
				c.name,
				0,
				0,
				1,
				1,  
				GetDate()
		FROM sys.tables AS t WITH(NOLOCK)
			INNER JOIN sys.columns c WITH(NOLOCK)				ON t.OBJECT_ID = c.OBJECT_ID 
			INNER JOIN cnf_dbtable HT WITH(NOLOCK)              ON HT.TableName = t.name	

		WHERE SCHEMA_NAME(schema_id) = 'dbo'
			and t.name = @TABLE_NAME
			AND (cast(HT.dbTableID as Varchar(5000)) + c.Name) not in (select (cast(DBTableID as Varchar(5000)) + ColumnName) from cnf_dbcolumn WITH(NOLOCK))


--ACtivate logged and active
	Update cnf_dbtable
	   set Logged = 1,
	       Active = 1
	WHERE  TableName = @TABLE_NAME
	    AND TableName in (
	  						SELECT distinct t.name AS table_name
								FROM sys.tables AS t WITH(NOLOCK)
									INNER JOIN sys.columns c WITH(NOLOCK)				ON t.OBJECT_ID = c.OBJECT_ID 	
								WHERE c.name LIKE '%LAST%LOG'
									and SCHEMA_NAME(schema_id) = 'dbo'
						)
		AND TableName in (
							SELECT distinct t.name AS table_name
								FROM sys.tables AS t WITH(NOLOCK)
									INNER JOIN sys.columns c WITH(NOLOCK)				ON t.OBJECT_ID = c.OBJECT_ID 	
								WHERE c.name LIKE '%LAST%LOG'
									and SCHEMA_NAME(schema_id) = 'dbo'
									and ((T.name like '%ADM_%') or (t.name like '%CNF_%') or
											(t.name in ('DATA_Account', 'DATA_AccountFinancial', 'DATA_AccountRelationship', 'DATA_DmgData',
														'DATA_DmgData_Translate', 'DATA_Right')))
							)
		AND TableName NOT IN (SELECT table_name
							FROM information_schema.columns WITH(NOLOCK)
							where data_type in ('NTEXT', 'TEXT')
								AND TABLE_NAME in (
	  												SELECT distinct t.name AS table_name
														FROM sys.tables AS t WITH(NOLOCK)
															INNER JOIN sys.columns c WITH(NOLOCK)				ON t.OBJECT_ID = c.OBJECT_ID 	
														WHERE c.name LIKE '%LAST%LOG'
															and SCHEMA_NAME(schema_id) = 'dbo'
												))

	Update cnf_dbcolumn
	  set Active = 1,
	      Logged = 1
	where DBTableid in (select dbtableid from cnf_dbtable WITH(NOLOCK) where active = 1 and logged = 1 and tablename = @TABLE_NAME)
	  and ColumnName not in ('Last_UserID_log', 'Last_WorkstationID_LOG', 'Last_DateTime_Log')


	select @Logged = Logged from cnf_dbtable WITH(NOLOCK) where tablename = @TABLE_NAME
	if @Logged = 1 
	BEGIN
		DECLARE @sql NVARCHAR(max),
				@SQL1 NVARCHAR(MAX)

		SET NOCOUNT ON  

		EXEC('IF OBJECT_ID (''' + @TABLE_NAME + '_CT'', ''TR'') IS NOT NULL DROP TRIGGER ' + @TABLE_NAME + '_CT')
		SELECT @sql = 
		'create trigger ' + @TABLE_NAME + '_CT on ' + @TABLE_NAME + ' FOR insert, update, delete
		as
		declare @TName varchar(128),
		        @TID nvarchar(max),
				@TLog int,  
				@PKC varchar(max),
				@PKV varchar(max),  
				@sql nvarchar(max), 
				@Type nvarchar(1),
				@MId nvarchar(max) = ''0'', 
				@ColumnID nvarchar(max) = ''0'',
				@CName varchar(128),
				@CValue1 nvarchar(max),
				@CValue2 nvarchar(max) 


		if exists(select top 1 1 from cnf_system where ISNULL(BOSHistoryLogEnabled, 1) = 1)
		BEGIN
			select @TName = ''' + @TABLE_NAME + ''', @TID=dbtableid, @TLog = (case when Active = 1 and Logged = 1 then 1 else 0 end) from cnf_dbtable WITH(NOLOCK) where TableName=''' + @TABLE_NAME + '''

			if @TLog = 1
			begin
				if exists (select * from inserted)
				if exists (select * from deleted)
				select @Type = ''2''
				else
				select @Type = ''3''
				else
				select @Type = ''1''

				select * into #ins from inserted
				select * into #del from deleted

				select @PKC = coalesce(@PKC + '' and'', '' on'') + '' i.'' + c.COLUMN_NAME + '' = d.'' + c.COLUMN_NAME, @PKV = coalesce(@PKV+''+'','''') + ''convert(varchar(100), coalesce(i.'' + COLUMN_NAME + '',d.'' + COLUMN_NAME + ''))''
				  from INFORMATION_SCHEMA.TABLE_CONSTRAINTS p WITH(NOLOCK)
					   INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE c WITH(NOLOCK) on c.CONSTRAINT_NAME = p.CONSTRAINT_NAME and c.TABLE_NAME = p.TABLE_NAME
				 where p.TABLE_NAME=@TName and CONSTRAINT_TYPE=''PRIMARY KEY''

				DECLARE TCursor CURSOR LOCAL FOR
								select columnName,
									   dbcolumnid
								from(
								select CNF_DBColumn.ColumnName,
									CNF_DBColumn.DBColumnId,
									(case when Active = 1 and Logged = 1 then 1 else 0 end) Active
								from CNF_DBColumn WITH(NOLOCK)	
								where cnf_dbcolumn.dbtableid = @TID
								)p
								where Active = 1

				OPEN TCursor

				FETCH NEXT FROM TCursor INTO
					@CName, @ColumnID
					'
			SELECT @sql1 = '
				WHILE @@FETCH_STATUS = 0
				BEGIN

					set @sql =''Select @CValue1 = '' + @CName +'' from #ins ''
					EXEC sp_executesql @sql, N''@CValue1 nvarchar(max) OUTPUT'', @CValue1 OUTPUT

					set @sql =''Select @CValue2 = '' + @CName +'' from #del ''
					EXEC sp_executesql @sql, N''@CValue2 nvarchar(max) OUTPUT'', @CValue2 OUTPUT

					if ISNULL(@CValue1, ''&amp;*()_2'') &lt;&gt; ISNULL(@CValue2, ''&amp;*()_2'')
					begin
						if @MId = 0
						begin
							set @sql = ''insert DATA_HL_Master (OperationType, dbtableid, ReferenceId, UserId, WorkstationId, InsDateTime)''
							set @sql = @sql + '' select '''''' + @Type + ''''''''												
							set @sql = @sql + '', '''''' + @TID + ''''''''		
							set @sql = @sql + '','' + @PKV		
							set @sql = @sql + '',convert(varchar(1000),i.Last_UserId_Log), convert(varchar(1000), i.Last_WorkstationId_Log), convert(varchar(1000),i.Last_DateTime_Log)''
							set @sql = @sql + '' from #ins i full outer join #del d ''
							set @sql = @sql + @PKC 
							set @sql = @sql + '' SELECT @MId = SCOPE_IDENTITY()''
							EXEC sp_executesql @sql, N''@MId nvarchar(max) OUTPUT'', @MId OUTPUT
						end
						if @Type &lt;&gt; ''1''
						BEGIN
							set @sql = ''insert data_HL_Detail (MasterId, OriginalValue, ModifiedValue, DBColumnID)''						
							set @sql = @sql + '' select convert(varchar(1000),'' + @MId + ''), convert(varchar(1000),d.'' + @CName + ''), convert(varchar(1000),i.'' + @CName + '')''				
							set @sql = @sql + '', convert(varchar(1000),'' + @ColumnID + '')  ''
							set @sql = @sql + '' from #ins i full outer join #del d '' + @PKC				
							EXEC sp_executesql @sql 																	
						END		
						
					END
					FETCH NEXT FROM TCursor INTO
					   @CName, @ColumnID
				END  --While loop
				CLOSE TCursor;
				DEALLOCATE TCursor; 
			END    --Table Check
		END	-- System Check
		'

	EXEC(@sql + @sql1)
	END	
  END
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>--declare @TABLE_NAME sysname

--SELECT @TABLE_NAME = MIN(Table_Name)
--  FROM INFORMATION_SCHEMA.Tables 
-- WHERE TABLE_TYPE = 'BASE TABLE' 
--	AND TABLE_NAME != 'sysdiagrams'
--	AND TABLE_SCHEMA = 'dbo'


--WHILE @TABLE_NAME IS NOT NULL
--BEGIN
--	Exec otn_sp_HIL_CreateHILTrigger @TABLE_NAME

--	SELECT @TABLE_NAME = MIN(Table_Name)
--	  FROM INFORMATION_SCHEMA.Tables 
--     WHERE TABLE_NAME &gt; @TABLE_NAME
--	   AND TABLE_TYPE = 'BASE TABLE' 
--	   AND TABLE_NAME != 'sysdiagrams'
--	   AND TABLE_SCHEMA = 'dbo'

--E</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>pchen</ADDEDBY><SQLVERSION>2612</SQLVERSION><RMTRACKLINK>79137</RMTRACKLINK><REASON>append 3 standard fields: Last_UserId_Log, Last_WorkstationId_Log, Last_DateTime_Log
and QuestionList into DATA_Ticket2Document</REASON><TABLENAMES>DATA_Ticket2Document=Ticket2DocumentId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_Ticket2Document'))
BEGIN
  ALTER TABLE DATA_Ticket2Document
  ADD Last_UserId_Log Integer null 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_WorkstationId_Log' AND
                Object_ID  = Object_ID(N'DATA_Ticket2Document'))
BEGIN
  ALTER TABLE DATA_Ticket2Document
  ADD Last_WorkstationId_Log Integer null 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_DateTime_Log' AND
                Object_ID  = Object_ID(N'DATA_Ticket2Document'))
BEGIN
  ALTER TABLE DATA_Ticket2Document
  ADD Last_DateTime_Log DateTime null 
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>2611</SQLVERSION><RMTRACKLINK>72604</RMTRACKLINK><REASON>New column in CNF_DBColumn: 'Logged'</REASON><TABLENAMES>CNF_DBColumn=DBColumnId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Logged' AND
                Object_ID  = Object_ID(N'CNF_DBColumn'))
BEGIN
  Alter Table CNF_DBColumn
  Add Logged Smallint Null
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>2610</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>History Triggrs</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>if exists(select * from sys.triggers where name = 'ddl_trig_createTable' )
  DROP TRIGGER ddl_trig_createTable ON DATABASE;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>CREATE TRIGGER ddl_trig_createTable   
ON DATABASE 
FOR CREATE_TABLE   
AS   
    
    DECLARE @TABLE_NAME varchar(255) 

    SET @TABLE_NAME =  EVENTDATA().value('(/EVENT_INSTANCE/ObjectName)[1]','nvarchar(100)')

    Exec otn_sp_HIL_CreateHILTrigger @TABLE_NAME </SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>--if exists(select * from sys.triggers where name = 'ddl_trig_alterTable' )
 -- DROP TRIGGER ddl_trig_alterTable ON DATABASE;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>--Create TRIGGER ddl_trig_alterTable   
--ON DATABASE   
--FOR ALTER_TABLE  
--AS  
--DECLARE @Data XML 
--DECLARE @TableName sysname 

--SET @Data = EventData()
--SET @TableName = @Data.value('(/EVENT_INSTANCE/ObjectName)[1]', 'nvarchar(100)')


--INSERT INTO dbo.cnf_dbcolumn
--		(DBTableId,
--		ColumnName,
--		Active,
--		Last_UserId_Log,
--		Last_WorkstationId_Log,
--		Last_DateTime_Log)  
--SELECT distinct HT.dbtableid AS tablesID, 
--		c.name,
--		HT.Active,
--		1,
--		1,  
--		GetDate()
--FROM sys.tables AS t 
--			INNER JOIN sys.columns c				ON t.OBJECT_ID = c.OBJECT_ID 
--			INNER JOIN cnf_dbtable HT               ON HT.TableName = t.name	
--WHERE SCHEMA_NAME(schema_id) = 'dbo'
--	and t.name = @Data.value('(/EVENT_INSTANCE/ObjectName)[1]', 'nvarchar(100)')
--	AND (cast(HT.dbTableID as Varchar(5000)) + c.Name) not in (select (cast(DBTableID as Varchar(5000)) + ColumnName) from cnf_dbcolumn)

--update cnf_dbcolumn
--   set Active = 0,
-- where  ColumnName not in (SELECT c.name
--							FROM sys.tables AS t 
--										INNER JOIN sys.columns c				ON t.OBJECT_ID = c.OBJECT_ID 
--										INNER JOIN cnf_dbtable HT               ON HT.TableName = t.name	
--							WHERE SCHEMA_NAME(schema_id) = 'dbo'
--								and t.name = @Data.value('(/EVENT_INSTANCE/ObjectName)[1]', 'nvarchar(100)')
--							)
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>if exists(select * from sys.triggers where name = 'ddl_trig_dropTable' )
  DROP TRIGGER ddl_trig_dropTable ON DATABASE;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>CREATE TRIGGER ddl_trig_dropTable   
ON DATABASE 
FOR DROP_TABLE   
AS   
    
    DECLARE @TABLE_NAME varchar(255) 
    DECLARE @TID int  = 0


	select @TID = dbtableid
	  from cnf_dbtable
	where TableName = EVENTDATA().value('(/EVENT_INSTANCE/ObjectName)[1]','nvarchar(100)')

     if @TID &lt;&gt; 0
     begin
	update cnf_dbtable
	set logged = 0,
	    active = 0
	where DBTableId = @TID
	
	update cnf_dbcolumn
	   set Active = 0
	where DBTableId = @TID
     end



</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>--IF EXISTS (SELECT *
--			FROM   sys.objects
--			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_HIL_CreateHILTrigger]')
--				AND type IN ( N'P'))
--  DROP Procedure [dbo].otn_sp_HIL_CreateHILTrigg</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>--CREATE Procedure dbo.otn_sp_HIL_CreateHILTrigger
--	@TABLE_NAME sysname
--AS 
--BEGIN
--	DECLARE @Logged int
--	set @Logged = 0

--	IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME= 'DATA_HL_Master')
--	BEGIN

		
--		INSERT INTO dbo.cnf_dbtable
--			   (TABLENAME,
--				Active,
--				Logged,
--				Last_UserId_Log,
--				Last_WorkstationId_Log,
--				Last_DateTime_Log)
--		SELECT @TABLE_NAME, 
--				0,
--				0,  
--				1,
--				1,
--				GetDate()
--		FROM sys.tables AS t WITH(NOLOCK)
--		where t.name = @TABLE_NAME
--		  and t.name not in (select tablename from cnf_dbtable WITH(NOLOCK))	
		  	 
--		INSERT INTO dbo.cnf_dbcolumn
--			   (DBTableId,
--				ColumnName,
--				Active,
--				Last_UserId_Log,
--				Last_WorkstationId_Log,
--				Last_DateTime_Log)
--		SELECT distinct HT.dbtableid AS tablesID, 
--				c.name,
--				0,
--				1,
--				1,  
--				GetDate()
--		FROM sys.tables AS t WITH(NOLOCK)
--			INNER JOIN sys.columns c WITH(NOLOCK)				ON t.OBJECT_ID = c.OBJECT_ID 
--			INNER JOIN cnf_dbtable HT WITH(NOLOCK)              ON HT.TableName = t.name	

--		WHERE SCHEMA_NAME(schema_id) = 'dbo'
--			and t.name = @TABLE_NAME
--			AND (cast(HT.dbTableID as Varchar(5000)) + c.Name) not in (select (cast(DBTableID as Varchar(5000)) + ColumnName) from cnf_dbcolumn WITH(NOLOCK))


----ACtivate logged and active
--	Update cnf_dbtable
--	   set Logged = 1,
--	       Active = 1
--	WHERE  TableName = @TABLE_NAME
--	    AND TableName in (
--	  						SELECT distinct t.name AS table_name
--								FROM sys.tables AS t WITH(NOLOCK)
--									INNER JOIN sys.columns c WITH(NOLOCK)				ON t.OBJECT_ID = c.OBJECT_ID 	
--								WHERE c.name LIKE '%LAST%LOG'
--									and SCHEMA_NAME(schema_id) = 'dbo'
--						)
--		AND TableName in (
--							SELECT distinct t.name AS table_name
--								FROM sys.tables AS t WITH(NOLOCK)
--									INNER JOIN sys.columns c WITH(NOLOCK)				ON t.OBJECT_ID = c.OBJECT_ID 	
--								WHERE c.name LIKE '%LAST%LOG'
--									and SCHEMA_NAME(schema_id) = 'dbo'
--									and ((T.name like '%ADM_%') or (t.name like '%CNF_%') or
--											(t.name in ('DATA_Account', 'DATA_AccountFinancial', 'DATA_AccountRelationship', 'DATA_DmgData',
--														'DATA_DmgData_Translate', 'DATA_Right')))
--							)
--		AND TableName NOT IN (SELECT table_name
--							FROM information_schema.columns WITH(NOLOCK)
--							where data_type in ('NTEXT', 'TEXT')
--								AND TABLE_NAME in (
--	  												SELECT distinct t.name AS table_name
--														FROM sys.tables AS t WITH(NOLOCK)
--															INNER JOIN sys.columns c WITH(NOLOCK)				ON t.OBJECT_ID = c.OBJECT_ID 	
--														WHERE c.name LIKE '%LAST%LOG'
--															and SCHEMA_NAME(schema_id) = 'dbo'
--												))

--	Update cnf_dbcolumn
--	  set Active = 1
--	where DBTableid in (select dbtableid from cnf_dbtable WITH(NOLOCK) where active = 1 and logged = 1 and tablename = @TABLE_NAME)
--	  and ColumnName not in ('Last_UserID_log', 'Last_WorkstationID_LOG', 'Last_DateTime_Log')


--	select @Logged = Logged from cnf_dbtable WITH(NOLOCK) where tablename = @TABLE_NAME
--	if @Logged = 1 
--	BEGIN
--		DECLARE @sql NVARCHAR(max),
--				@SQL1 NVARCHAR(MAX)

--		SET NOCOUNT ON  

--		EXEC('IF OBJECT_ID (''' + @TABLE_NAME + '_CT'', ''TR'') IS NOT NULL DROP TRIGGER ' + @TABLE_NAME + '_CT')
--		SELECT @sql = 
--		'create trigger ' + @TABLE_NAME + '_CT on ' + @TABLE_NAME + ' FOR insert, update, delete
--		as
--		declare @TName varchar(128),
--		        @TID nvarchar(max),
--				@TLog int,  
--				@PKC varchar(max),
--				@PKV varchar(max),  
--				@sql nvarchar(max), 
--				@Type nvarchar(1),
--				@MId nvarchar(max) = ''0'', 
--				@ColumnID nvarchar(max) = ''0'',
--				@CName varchar(128),
--				@CValue1 nvarchar(max),
--				@CValue2 nvarchar(max) 


--		if exists(select top 1 1 from cnf_system where BOSHistoryLogEnabled = 1)
--		BEGIN
--			select @TName = ''' + @TABLE_NAME + ''', @TID=dbtableid, @TLog = (case when Active = 1 and Logged = 1 then 1 else 0 end) from cnf_dbtable WITH(NOLOCK) where TableName=''' + @TABLE_NAME + '''

--			if @TLog = 1
--			begin
--				if exists (select * from inserted)
--				if exists (select * from deleted)
--				select @Type = ''2''
--				else
--				select @Type = ''3''
--				else
--				select @Type = ''1''

--				select * into #ins from inserted
--				select * into #del from deleted

--				select @PKC = coalesce(@PKC + '' and'', '' on'') + '' i.'' + c.COLUMN_NAME + '' = d.'' + c.COLUMN_NAME, @PKV = coalesce(@PKV+''+'','''') + ''convert(varchar(100), coalesce(i.'' + COLUMN_NAME + '',d.'' + COLUMN_NAME + ''))''
--				  from INFORMATION_SCHEMA.TABLE_CONSTRAINTS p WITH(NOLOCK)
--					   INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE c WITH(NOLOCK) on c.CONSTRAINT_NAME = p.CONSTRAINT_NAME and c.TABLE_NAME = p.TABLE_NAME
--				 where p.TABLE_NAME=@TName and CONSTRAINT_TYPE=''PRIMARY KEY''

--				DECLARE TCursor CURSOR LOCAL FOR
--					select CNF_DBColumn.ColumnName,
--						   CNF_DBColumn.DBColumnId
--					  from CNF_DBColumn WITH(NOLOCK)	
--					 where CNF_DBColumn.dbtableid = @TID
--					   and CNF_DBColumn.Active = 1

--				OPEN TCursor

--				FETCH NEXT FROM TCursor INTO
--					@CName, @ColumnID
--					'
--			SELECT @sql1 = '
--				WHILE @@FETCH_STATUS = 0
--				BEGIN

--					set @sql =''Select @CValue1 = '' + @CName +'' from #ins ''
--					EXEC sp_executesql @sql, N''@CValue1 nvarchar(max) OUTPUT'', @CValue1 OUTPUT

--					set @sql =''Select @CValue2 = '' + @CName +'' from #del ''
--					EXEC sp_executesql @sql, N''@CValue2 nvarchar(max) OUTPUT'', @CValue2 OUTPUT

--					if ISNULL(@CValue1, ''&amp;*()_2'') &lt;&gt; ISNULL(@CValue2, ''&amp;*()_2'')
--					begin
--						if @MId = 0
--						begin
--							set @sql = ''insert DATA_HL_Master (OperationType, dbtableid, ReferenceId, UserId, WorkstationId, InsDateTime)''
--							set @sql = @sql + '' select '''''' + @Type + ''''''''												
--							set @sql = @sql + '', '''''' + @TID + ''''''''		
--							set @sql = @sql + '','' + @PKV		
--							set @sql = @sql + '',convert(varchar(1000),i.Last_UserId_Log), convert(varchar(1000), i.Last_WorkstationId_Log), convert(varchar(1000),i.Last_DateTime_Log)''
--							set @sql = @sql + '' from #ins i full outer join #del d ''
--							set @sql = @sql + @PKC 
--							set @sql = @sql + '' SELECT @MId = SCOPE_IDENTITY()''
--							EXEC sp_executesql @sql, N''@MId nvarchar(max) OUTPUT'', @MId OUTPUT
--						end
--						if @Type &lt;&gt; ''1''
--						BEGIN
--							set @sql = ''insert data_HL_Detail (MasterId, OriginalValue, ModifiedValue, DBColumnID)''						
--							set @sql = @sql + '' select convert(varchar(1000),'' + @MId + ''), convert(varchar(1000),d.'' + @CName + ''), convert(varchar(1000),i.'' + @CName + '')''				
--							set @sql = @sql + '', convert(varchar(1000),'' + @ColumnID + '')  ''
--							set @sql = @sql + '' from #ins i full outer join #del d '' + @PKC				
--							EXEC sp_executesql @sql 																	
--						END		
						
--					END
--					FETCH NEXT FROM TCursor INTO
--					   @CName, @ColumnID
--				END  --While loop
--				CLOSE TCursor;
--				DEALLOCATE TCursor; 
--			END    --Table Check
--		END	-- System Check
--		'

--	EXEC(@sql + @sql1)
--	END	
--  END
--END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>--declare @TABLE_NAME sysname

--SELECT @TABLE_NAME = MIN(Table_Name)
--  FROM INFORMATION_SCHEMA.Tables 
-- WHERE TABLE_TYPE = 'BASE TABLE' 
--	AND TABLE_NAME != 'sysdiagrams'
--	AND TABLE_SCHEMA = 'dbo'


--WHILE @TABLE_NAME IS NOT NULL
--BEGIN
--	Exec otn_sp_HIL_CreateHILTrigger @TABLE_NAME

--	SELECT @TABLE_NAME = MIN(Table_Name)
--	  FROM INFORMATION_SCHEMA.Tables 
--     WHERE TABLE_NAME &gt; @TABLE_NAME
--	   AND TABLE_TYPE = 'BASE TABLE' 
--	   AND TABLE_NAME != 'sysdiagrams'
--	   AND TABLE_SCHEMA = 'dbo'

--END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>2609</SQLVERSION><RMTRACKLINK>72604</RMTRACKLINK><REASON>New column in CNF_Sytem: 'BOSHistoryLogEnabled'</REASON><TABLENAMES>CNF_System=SystemId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'BOSHistoryLogEnabled' AND
                Object_ID  = Object_ID(N'CNF_System'))
BEGIN
  Alter Table CNF_System
  Add BOSHistoryLogEnabled Smallint NOT NULL Default(1)
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>marosio</ADDEDBY><SQLVERSION>2608</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>Populate correctly existing AK values on CNF_Location and ADM_Gate, and insert the pertinen record on DATA_Counter</REASON><TABLENAMES>CNF_Location=LocationId
ADM_Gate=GateId
DATA_Counter=CounterId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>Update L set L.LocationAK = (Select S.SiteCode from CNF_Site S where S.SiteId = L.SiteId) + '.' + L.LocationCode
from CNF_Location L                                                          </SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>Update G set G.GateAK = ( (Select L.LocationAK from CNF_Location L where L.LocationId = G.LocationId) + '.' + CAST(G.GateId as varchar(32)))
from ADM_Gate G</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>Insert into DATA_Counter (CounterType,IdentifierAK,ReferenceTime,Counter,LastUpdateGuid) 
Select 42, L.LocationAK, 'NEVER', Max(G.GateId), Null from CNF_Location L inner join ADM_Gate G on L.LocationId = G.LocationId group by L.LocationAK</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>2607</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>History Log triggers</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>  --IF EXISTS (SELECT *
		--	FROM   sys.objects
		--	WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_HIL_CreateHILTrigger]')
		--		AND type IN ( N'P'))
  --  DROP Procedure [dbo].otn_sp_HIL_CreateHILTrigger
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>--CREATE Procedure dbo.otn_sp_HIL_CreateHILTrigger
--	@TABLE_NAME sysname
--AS 
--BEGIN
--	DECLARE @Logged int
--	set @Logged = 0

--	IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME= 'DATA_HL_Master')
--	BEGIN

--		INSERT INTO dbo.cnf_dbtable
--			   (TABLENAME,
--				Active,
--				Logged,
--				Last_UserId_Log,
--				Last_WorkstationId_Log,
--				Last_DateTime_Log)
--		SELECT @TABLE_NAME, 
--				0,
--				0,  
--				1,
--				1,
--				GetDate()
		 
--		INSERT INTO dbo.cnf_dbcolumn
--			   (DBTableId,
--				ColumnName,
--				Active,
--				Last_UserId_Log,
--				Last_WorkstationId_Log,
--				Last_DateTime_Log)
--		SELECT distinct HT.dbtableid AS tablesID, 
--				c.name,
--				0,
--				1,
--				1,  
--				GetDate()
--		FROM sys.tables AS t 
--			INNER JOIN sys.columns c				ON t.OBJECT_ID = c.OBJECT_ID 
--			INNER JOIN cnf_dbtable HT               ON HT.TableName = t.name	

--		WHERE SCHEMA_NAME(schema_id) = 'dbo'
--			and t.name = @TABLE_NAME
--			AND (cast(HT.dbTableID as Varchar(5000)) + c.Name) not in (select (cast(DBTableID as Varchar(5000)) + ColumnName) from cnf_dbcolumn)


----ACtivate logged and active
--	Update cnf_dbtable
--	   set Logged = 1,
--	       Active = 1
--	WHERE  TableName = @TABLE_NAME
--	    AND TableName in (
--	  						SELECT distinct t.name AS table_name
--								FROM sys.tables AS t 
--									INNER JOIN sys.columns c				ON t.OBJECT_ID = c.OBJECT_ID 	
--								WHERE c.name LIKE '%LAST%LOG'
--									and SCHEMA_NAME(schema_id) = 'dbo'
--						)
--		AND TableName in (
--							SELECT distinct t.name AS table_name
--								FROM sys.tables AS t 
--									INNER JOIN sys.columns c				ON t.OBJECT_ID = c.OBJECT_ID 	
--								WHERE c.name LIKE '%LAST%LOG'
--									and SCHEMA_NAME(schema_id) = 'dbo'
--									and ((T.name like '%ADM_%') or (t.name like '%CNF_%') or
--											(t.name in ('DATA_Account', 'DATA_AccountFinancial', 'DATA_AccountRelationship', 'DATA_DmgData',
--														'DATA_DmgData_Translate', 'DATA_Right')))
--							)
--		AND TableName NOT IN (SELECT table_name
--							FROM information_schema.columns 
--							where data_type in ('NTEXT', 'TEXT')
--								AND TABLE_NAME in (
--	  												SELECT distinct t.name AS table_name
--														FROM sys.tables AS t 
--															INNER JOIN sys.columns c				ON t.OBJECT_ID = c.OBJECT_ID 	
--														WHERE c.name LIKE '%LAST%LOG'
--															and SCHEMA_NAME(schema_id) = 'dbo'
--												))

--	Update cnf_dbcolumn
--	  set Active = 1
--	where DBTableid in (select dbtableid from cnf_dbtable where active = 1 and logged = 1 and tablename = @TABLE_NAME)
--	  and ColumnName not in ('Last_UserID_log', 'Last_WorkstationID_LOG', 'Last_DateTime_Log')


--	select @Logged = Logged from cnf_dbtable where tablename = @TABLE_NAME
--	if @Logged = 1 
--	BEGIN
--		DECLARE @sql nvarchar(max),
--				@SQL1 NVARCHAR(MAX)

--		SET NOCOUNT ON  

--		EXEC('IF OBJECT_ID (''' + @TABLE_NAME + '_CT'', ''TR'') IS NOT NULL DROP TRIGGER ' + @TABLE_NAME + '_CT')
--		SELECT @sql = 
--		'create trigger ' + @TABLE_NAME + '_CT on ' + @TABLE_NAME + ' FOR insert, update, delete
--		as
--		declare @field int, 
--		        @mfield int, 
--				@fname varchar(128), 
--				@TName varchar(128), 
--				@PKC varchar(max), 
--				@sql nvarchar(max), 
--				@Type nvarchar(1),
--		        @PKV varchar(max), 
--				@MId nvarchar(max) = ''0'', 
--				@TID nvarchar(max), 
--				@C nvarchar(max) = ''0'',
--				@ColumnID nvarchar(max) = ''0''

--		select @TName = ''' + @TABLE_NAME + ''', @TID=dbtableid from cnf_dbtable where TableName=''' + @TABLE_NAME + '''
--		if exists(select * from cnf_dbtable where dbtableid=@TID and Active=1 and Logged=1)
--		begin
--			if exists (select * from inserted)
--			if exists (select * from deleted)
--			select @Type = ''2''
--			else
--			select @Type = ''3''
--			else
--			select @Type = ''1''

--			select * into #ins from inserted
--			select * into #del from deleted

--			select @PKC = coalesce(@PKC + '' and'', '' on'') + '' i.'' + c.COLUMN_NAME + '' = d.'' + c.COLUMN_NAME, @PKV = coalesce(@PKV+''+'','''') + ''convert(varchar(100), coalesce(i.'' + COLUMN_NAME + '',d.'' + COLUMN_NAME + ''))''
--			from INFORMATION_SCHEMA.TABLE_CONSTRAINTS p 
--			INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE c on c.CONSTRAINT_NAME = p.CONSTRAINT_NAME and c.TABLE_NAME = p.TABLE_NAME
--			where p.TABLE_NAME=@TName and CONSTRAINT_TYPE=''PRIMARY KEY''

--			select @field=0, @mfield=max(ORDINAL_POSITION) from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME=@TName
--			while  @field &lt; @mfield
--			begin
--				select @field = min(ORDINAL_POSITION) from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME=@TName and ORDINAL_POSITION&gt;@field
--				select @fname = i.COLUMN_NAME, @ColumnID = c.dbcolumnid
--					from INFORMATION_SCHEMA.COLUMNS I
--						INNER JOIN cnf_dbtable T on T.tablename = I.TABLE_NAME
--						INNER JOIN cnf_dbcolumn C on C.dbTableid = T.dbtableid and c.columnname = i.COLUMN_NAME
--					where I.TABLE_NAME=@TName 
--						and ORDINAL_POSITION=@field

--				if exists(select * from cnf_dbcolumn C INNER JOIN cnf_dbtable T ON T.dbTableId = C.dbTableId where T.dbtableid=@TID and C.ColumnName=@fname and C.Active=1)
--				begin
--					select @sql = ''if exists(select * from #ins i full outer join #del d '' + @PKC				
--					select @sql = @sql + '' where i.'' + @fname + '' is not null and i.'' + @fname + '' &lt;&gt; d.'' + @fname + '' or (i.'' + @fname + '' is null and d.'' + @fname + '' is not null) or (i.'' + @fname + '' is not null and d.'' + @fname + '' is null)) set @C=1''
--					EXECUTE sp_executesql @sql, N''@C nvarchar(max) OUTPUT'', @C OUTPUT 
--					if @c=1 break 
--				end
--			end
--			if @c=1
--			begin
--				set @field=0  '

--		SELECT @sql1 ='
--				while @field&lt;@mfield
--				begin
--					select @field=min(ORDINAL_POSITION) from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME=@TName	and ORDINAL_POSITION&gt;@field
--					select @fname = i.COLUMN_NAME, @ColumnID = c.dbcolumnid
--					from INFORMATION_SCHEMA.COLUMNS I
--						INNER JOIN cnf_dbtable T on T.tablename = I.TABLE_NAME
--						INNER JOIN cnf_dbcolumn C on C.dbTableid = T.dbtableid and c.columnname = i.COLUMN_NAME
--					where I.TABLE_NAME=@TName 
--						and ORDINAL_POSITION=@field

--					if exists(select * from cnf_dbcolumn C INNER JOIN cnf_dbtable T ON T.dbTableId = C.dbTableId where T.dbtableid=@TID and C.ColumnName=@fname and C.Active=1)
--					begin	
--						if @MId = 0
--						begin
--							select @sql = ''insert DATA_HL_Master (OperationType, dbtableid, ReferenceId, UserId, WorkstationId, InsDateTime)''
--							select @sql = @sql + '' select '''''' + @Type + ''''''''												
--							select @sql = @sql + '', '''''' + @TID + ''''''''		
--							select @sql = @sql + '','' + @PKV		
--							select @sql = @sql + '',convert(varchar(1000),i.Last_UserId_Log), convert(varchar(1000),i.Last_WorkstationId_Log), convert(varchar(1000),i.Last_DateTime_Log)''
--							select @sql = @sql + '' from #ins i full outer join #del d''
--							select @sql = @sql + @PKC 
--							select @sql = @sql + '' SELECT @MId = SCOPE_IDENTITY()''
--							EXECUTE sp_executesql @sql, N''@MId nvarchar(max) OUTPUT'', @MId OUTPUT
--						end
--						if @Type &lt;&gt; ''1''
--						BEGIN
--							select @sql = ''insert data_HL_Detail (MasterId, OriginalValue, ModifiedValue, DBColumnID)''
--							select @sql = @sql + '' select convert(varchar(1000),'' + @MId + ''), convert(varchar(1000),d.'' + @fname + ''), convert(varchar(1000),i.'' + @fname + '')''
--							select @sql = @sql + '', convert(varchar(1000),'' + @ColumnID + '')  ''
--							select @sql = @sql + '' from #ins i full outer join #del d '' + @PKC				
--							select @sql = @sql + '' where i.'' + @fname + '' is not null and i.'' + @fname + '' &lt;&gt; d.'' + @fname + '' or (i.'' + @fname + '' is null and d.'' + @fname + '' is not null) or (i.'' + @fname + '' is not null and d.'' + @fname + '' is null)''				
--							EXECUTE sp_executesql @sql 
--		 				END		
--					END 
--				END	
--			END 
--		END'

--		EXEC(@sql + @sql1)
--	END	
--  END
--END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>
--declare @TABLE_NAME sysname

--SELECT @TABLE_NAME = MIN(Table_Name)
--  FROM INFORMATION_SCHEMA.Tables 
-- WHERE TABLE_TYPE = 'BASE TABLE' 
--	AND TABLE_NAME != 'sysdiagrams'
--	AND TABLE_SCHEMA = 'dbo'


--WHILE @TABLE_NAME IS NOT NULL
--BEGIN
--	Exec otn_sp_HIL_CreateHILTrigger @TABLE_NAME
--	select @TABLE_NAME

--	SELECT @TABLE_NAME = MIN(Table_Name)
--	  FROM INFORMATION_SCHEMA.Tables 
--     WHERE TABLE_NAME &gt; @TABLE_NAME
--	   AND TABLE_TYPE = 'BASE TABLE' 
--	   AND TABLE_NAME != 'sysdiagrams'
--	   AND TABLE_SCHEMA = 'dbo'

--END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>--if exists(select * from sys.triggers where name = 'ddl_trig_createTable' )
--DROP TRIGGER ddl_trig_createTable ON DATABASE;
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>
		--CREATE TRIGGER ddl_trig_createTable   
		--ON DATABASE 
		--FOR CREATE_TABLE   
		--AS   
    
		--	DECLARE @TABLE_NAME varchar(255) 

		--	SELECT @TABLE_NAME = TABLE_NAME 
		--			FROM INFORMATION_SCHEMA.Tables 
		--		WHERE TABLE_TYPE = 'BASE TABLE' 
		--			AND TABLE_NAME != 'sysdiagrams'
		--			AND TABLE_NAME = EVENTDATA().value('(/EVENT_INSTANCE/ObjectName)[1]','nvarchar(100)')
		--			AND TABLE_SCHEMA = 'dbo'

		--	Exec otn_sp_HIL_CreateHILTrigger @TABLE_NAM</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>--if exists(select * from sys.triggers where name = 'ddl_trig_alterTable' )
--DROP TRIGGER ddl_trig_alterTable ON DATABASE;
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>
--CREATE TRIGGER ddl_trig_alterTable   
--ON DATABASE   
--FOR ALTER_TABLE  
--AS  
--DECLARE @Data XML 
--DECLARE @TableName sysname 

--SET @Data = EventData()
--SET @TableName = @Data.value('(/EVENT_INSTANCE/ObjectName)[1]', 'nvarchar(100)')


--INSERT INTO dbo.cnf_dbcolumn
--		(DBTableId,
--		ColumnName,
--		Active,
--		Last_UserId_Log,
--		Last_WorkstationId_Log,
--		Last_DateTime_Log)  
--SELECT distinct HT.dbtableid AS tablesID, 
--		c.name,
--		HT.Active,
--		1,
--		1,  
--		GetDate()
--FROM sys.tables AS t 
--			INNER JOIN sys.columns c				ON t.OBJECT_ID = c.OBJECT_ID 
--			INNER JOIN cnf_dbtable HT               ON HT.TableName = t.name	
--WHERE SCHEMA_NAME(schema_id) = 'dbo'
--	and t.name = @Data.value('(/EVENT_INSTANCE/ObjectName)[1]', 'nvarchar(100)')
--	AND (cast(HT.dbTableID as Varchar(5000)) + c.Name) not in (select (cast(DBTableID as Varchar(5000)) + ColumnName) from cnf_dbcolumn)

	
	 </SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>2606</SQLVERSION><RMTRACKLINK>72604</RMTRACKLINK><REASON>Renamed TableId and ColumnId Foreign Key references on history tables</REASON><TABLENAMES>CNF_DBColumn=DBColumnId
DATA_HL_Master=MasterId
DATA_HL_Detail=DetailId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DBColumn_TableId')
BEGIN
  ALTER TABLE CNF_DBColumn
  DROP CONSTRAINT FK_CNF_DBColumn_TableId
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'TableId' AND
                Object_ID  = Object_ID(N'CNF_DBColumn'))
BEGIN
  ALTER TABLE CNF_DBColumn
  DROP COLUMN TableId 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_HL_Detail_ColumnId')
BEGIN
  ALTER TABLE DATA_HL_Detail
  DROP CONSTRAINT FK_DATA_HL_Detail_ColumnId
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'ColumnId' AND
                Object_ID  = Object_ID(N'DATA_HL_Detail'))
BEGIN
  ALTER TABLE DATA_HL_Detail
  DROP COLUMN ColumnId 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_HL_Master_TableId')
BEGIN
  ALTER TABLE DATA_HL_Master
  DROP CONSTRAINT FK_DATA_HL_Master_TableId
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'TableId' AND
                Object_ID  = Object_ID(N'DATA_HL_Master'))
BEGIN
  ALTER TABLE DATA_HL_Master
  DROP COLUMN TableId 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'DBTableId' AND
                Object_ID  = Object_ID(N'CNF_DBColumn'))
BEGIN
  ALTER TABLE CNF_DBColumn
  ADD DBTableId Integer null 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DBColumn_DBTableId')
BEGIN
  ALTER TABLE CNF_DBColumn
  ADD CONSTRAINT [FK_CNF_DBColumn_DBTableId] FOREIGN KEY([DBTableId]) 
  REFERENCES [CNF_DBTable] ([DBTableId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'DBColumnId' AND
                Object_ID  = Object_ID(N'DATA_HL_Detail'))
BEGIN
  ALTER TABLE DATA_HL_Detail
  ADD DBColumnId Integer null 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_HL_Detail_DBColumnId')
BEGIN
  ALTER TABLE DATA_HL_Detail
  ADD CONSTRAINT [FK_DATA_HL_Detail_DBColumnId] FOREIGN KEY([DBColumnId]) 
  REFERENCES [CNF_DBColumn] ([DBColumnId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'DBTableId' AND
                Object_ID  = Object_ID(N'DATA_HL_Master'))
BEGIN
  ALTER TABLE DATA_HL_Master
  ADD DBTableId Integer null 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_HL_Master_DBTableId')
BEGIN
  ALTER TABLE DATA_HL_Master
  ADD CONSTRAINT [FK_DATA_HL_Master_DBTableId] FOREIGN KEY([DBTableId]) 
  REFERENCES [CNF_DBTable] ([DBTableId])
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>2605</SQLVERSION><RMTRACKLINK>72604</RMTRACKLINK><REASON>Dropped all triggers added for history log

Dropped CNF_HIL_Tables_CNF_HIL_Columns, DATA_HIL_Master, DATA_HIL_Detail

Renamed and readded: CNF_DBColumn, CNF_DBColumn, DATA_HL_Master, DATA_HL_Detail</REASON><TABLENAMES>CNF_DBTable=DBTableId
CNF_DBColumn=DBColumnId
DATA_HL_Master=MasterId
DATA_HL_Detail=DetailId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME= 'DATA_HIL_Master')
BEGIN


	DECLARE @sql nvarchar(max), 
			@TABLE_NAME sysname

	SET NOCOUNT ON

	SELECT @TABLE_NAME = MIN(TABLE_NAME) 
	 FROM INFORMATION_SCHEMA.Tables 
	WHERE TABLE_TYPE = 'BASE TABLE' 
	  AND TABLE_NAME != 'sysdiagrams'
	  AND TABLE_SCHEMA = 'dbo'


	WHILE @TABLE_NAME IS NOT NULL
	BEGIN
	EXEC('IF OBJECT_ID (''' + @TABLE_NAME + '_CT'', ''TR'') IS NOT NULL DROP TRIGGER ' + @TABLE_NAME + '_CT')
	
	EXEC(@sql)
	SELECT @TABLE_NAME = MIN(TABLE_NAME) 
	 FROM INFORMATION_SCHEMA.Tables 
	WHERE TABLE_NAME&gt; @TABLE_NAME
	  AND TABLE_TYPE = 'BASE TABLE' 
	  AND TABLE_NAME != 'sysdiagrams'
	  AND TABLE_SCHEMA = 'dbo'

	END

END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS ( SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND  TABLE_NAME = 'CNF_HIL_Columns' )

BEGIN
   DROP TABLE CNF_HIL_Columns
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS ( SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND  TABLE_NAME = 'CNF_HIL_Tables' )

BEGIN
   DROP TABLE CNF_HIL_Tables
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS ( SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND  TABLE_NAME = 'DATA_HIL_Detail' )

BEGIN
   DROP TABLE DATA_HIL_Detail
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS ( SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND  TABLE_NAME = 'DATA_HIL_Master' )

BEGIN
   DROP TABLE DATA_HIL_Master
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'CNF_DBTable'))
                    
BEGIN
Create table [CNF_DBTable]
(
	[DBTableId] Integer Identity(1,1) NOT NULL,
	[TableName] Nvarchar(100) NULL,
	[Active] Smallint NULL,
	[Logged] Smallint NULL,
	[Last_UserId_Log] Integer NULL,
	[Last_WorkstationId_Log] Integer NULL,
	[Last_DateTime_Log] Datetime NULL,
Primary Key ([DBTableId])
) 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DBTable_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_DBTable
  ADD CONSTRAINT [FK_CNF_DBTable_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DBTable_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_DBTable
  ADD CONSTRAINT [FK_CNF_DBTable_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'CNF_DBColumn'))
                    
BEGIN
Create table [CNF_DBColumn]
(
	[DBColumnId] Integer Identity(1,1) NOT NULL,
	[TableId] Integer NOT NULL,
	[ColumnName] Nvarchar(100) NULL,
	[Active] Smallint NULL,
	[Last_UserId_Log] Integer NULL,
	[Last_WorkstationId_Log] Integer NULL,
	[Last_DateTime_Log] Datetime NULL,
Primary Key ([DBColumnId])
) 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DBColumn_TableId')
BEGIN
  ALTER TABLE CNF_DBColumn
  ADD CONSTRAINT [FK_CNF_DBColumn_TableId] FOREIGN KEY([TableId]) 
  REFERENCES [CNF_DBTable] ([DBTableId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DBColumn_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_DBColumn
  ADD CONSTRAINT [FK_CNF_DBColumn_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DBColumn_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_DBColumn
  ADD CONSTRAINT [FK_CNF_DBColumn_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'DATA_HL_Master'))
                    
BEGIN
Create table [DATA_HL_Master]
(
	[MasterId] Integer Identity(1,1) NOT NULL,
	[TableId] Integer NOT NULL,
	[ReferenceId] Integer NULL,
	[OperationType] Smallint NULL,
	[UserId] Integer NULL,
	[WorkstationId] Integer NULL,
	[InsDateTime] Datetime NULL,
Primary Key ([MasterId])
) 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_HL_Master_TableId')
BEGIN
  ALTER TABLE DATA_HL_Master
  ADD CONSTRAINT [FK_DATA_HL_Master_TableId] FOREIGN KEY([TableId]) 
  REFERENCES [CNF_DBTable] ([DBTableId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'DATA_HL_Detail'))
                    
BEGIN
Create table [DATA_HL_Detail]
(
	[DetailId] Integer Identity(1,1) NOT NULL,
	[MasterId] Integer NOT NULL,
	[ColumnId] Integer NOT NULL,
	[OriginalValue] Nvarchar(max) NULL,
	[ModifiedValue] Nvarchar(max) NULL,
Primary Key ([DetailId])
) 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_HL_Detail_MasterId')
BEGIN
  ALTER TABLE DATA_HL_Detail
  ADD CONSTRAINT [FK_DATA_HL_Detail_MasterId] FOREIGN KEY([MasterId]) 
  REFERENCES [DATA_HL_Master] ([MasterId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_HL_Detail_ColumnId')
BEGIN
  ALTER TABLE DATA_HL_Detail
  ADD CONSTRAINT [FK_DATA_HL_Detail_ColumnId] FOREIGN KEY([ColumnId]) 
  REFERENCES [CNF_DBColumn] ([DBColumnId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>CREATE UNIQUE NONCLUSTERED INDEX [IDX_CNF_DBTable_TableName] ON [dbo].[CNF_DBTable]

(

    [TableName] ASC

)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>scoluccia</ADDEDBY><SQLVERSION>2604</SQLVERSION><RMTRACKLINK>83005</RMTRACKLINK><REASON>0)ADD OptionalItemsRequired to CNF_Promotion
1)ADD OptionalItemsRequired to DATA_SaleItemRule</REASON><TABLENAMES>CNF_Promotion=PromotionId
DATA_SaleItemRule=SaleItemRuleId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'OptionalItemsRequired' AND
                Object_ID  = Object_ID(N'CNF_Promotion'))
BEGIN
  ALTER TABLE CNF_Promotion 
  ADD [OptionalItemsRequired] [smallint] NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'OptionalItemsRequired' AND
                Object_ID  = Object_ID(N'DATA_SaleItemRule'))
BEGIN
  ALTER TABLE DATA_SaleItemRule 
  ADD [OptionalItemsRequired] [smallint] NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>2603</SQLVERSION><RMTRACKLINK>83034</RMTRACKLINK><REASON>3 history fields removed from DATA_AptRotationCount</REASON><TABLENAMES>DATA_AptRotationCount=AptRotationCountId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_AptRotationCount_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_AptRotationCount
  DROP CONSTRAINT FK_DATA_AptRotationCount_Last_UserId_Log
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_AptRotationCount_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_AptRotationCount
  DROP CONSTRAINT FK_DATA_AptRotationCount_Last_WorkstationId_Log
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_AptRotationCount'))
BEGIN
  ALTER TABLE DATA_AptRotationCount
  DROP COLUMN Last_UserId_Log, Last_WorkstationId_Log, Last_DateTime_Log
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>marosio</ADDEDBY><SQLVERSION>2602</SQLVERSION><RMTRACKLINK>79923</RMTRACKLINK><REASON>Create new table: CNF_LocationRoute
 append FK to CNF_Location
Create new table: CNF_LocationRoute2Gate
 append FK to CNF_LocationRoute
 append FK to ADM_Gate</REASON><TABLENAMES>CNF_LocationRoute=LocationRouteId
CNF_LocationRoute2Gate=LocationRoute2GateId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>if exists(select * from sys.triggers where name = 'ddl_trig_createTable' )
   DISABLE TRIGGER ddl_trig_createTable ON DATABASE;

IF NOT (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'CNF_LocationRoute'))
                    
BEGIN
Create table [CNF_LocationRoute]
(
	[LocationRouteId] Integer Identity(1,1) NOT NULL,
	[LocationId] Integer NULL,
	[Name] Nvarchar(30) NULL,
	[LocationRouteAK] [varchar](32) NOT NULL,
	[LocationRouteDescription] Nvarchar(100) NULL,
	[CompleteStageRoute] Smallint NULL, 
	[Last_UserId_Log] [int] NULL,
	[Last_WorkstationId_Log] [int] NULL,
	[Last_DateTime_Log] [datetime] NULL,
Primary Key ([LocationRouteId])
) 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_LocationRoute_LocationId')
BEGIN
  ALTER TABLE CNF_LocationRoute
  ADD CONSTRAINT [FK_CNF_LocationRoute_LocationId] FOREIGN KEY([LocationId]) 
  REFERENCES [CNF_Location] ([LocationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                 WHERE TABLE_SCHEMA = 'dbo' 
                   AND  TABLE_NAME = 'CNF_LocationRoute2Gate'))
                    
BEGIN
Create table [CNF_LocationRoute2Gate]
(
	[LocationRoute2GateId] Integer Identity(1,1) NOT NULL,
	[LocationRouteId] Integer NULL,
	[GateId] Integer NULL, 
	[GateOrder] Integer NULL,
	[Last_UserId_Log] [int] NULL,
	[Last_WorkstationId_Log] [int] NULL,
	[Last_DateTime_Log] [datetime] NULL,
Primary Key ([LocationRoute2GateId])
) 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_LocationRoute2Gate_LocationRouteId')
BEGIN
  ALTER TABLE CNF_LocationRoute2Gate
  ADD CONSTRAINT [FK_CNF_LocationRoute2Gate_LocationRouteId] FOREIGN KEY([LocationRouteId]) 
  REFERENCES [CNF_LocationRoute] ([LocationRouteId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_LocationRoute2Gate_GateId')
BEGIN
  ALTER TABLE CNF_LocationRoute2Gate
  ADD CONSTRAINT [FK_CNF_LocationRoute2Gate_GateId] FOREIGN KEY([GateId]) 
  REFERENCES [ADM_Gate] ([GateId])
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>2601</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_HIL_CreateHILTrigger]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_HIL_CreateHILTrigger</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>CREATE Procedure dbo.otn_sp_HIL_CreateHILTrigger
	@TABLE_NAME sysname
AS 
BEGIN
	IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME= 'DATA_HIL_Master')
	BEGIN

		INSERT INTO dbo.cnf_HIL_Tables
			   (referencetable,
				Active,
				Last_UserId_Log,
				Last_WorkstationId_Log,
				Last_DateTime_Log)
		SELECT distinct cnf_lookup.itemid AS table_name, 
						1,  
						1,
						1,
						GetDate()
				FROM sys.tables AS t 
					INNER JOIN sys.columns c				ON t.OBJECT_ID = c.OBJECT_ID
					INNER JOIN cnf_lookup                   on cnf_lookup.description = t.name and cnf_lookup.lookuptableid = 35  	
				WHERE c.name LIKE '%LAST%LOG'
				  and SCHEMA_NAME(schema_id) = 'dbo'
				  and t.name = @TABLE_NAME
				  and cnf_lookup.itemid not in (select referencetable from cnf_hil_Tables);

		INSERT INTO dbo.CNF_HIL_Columns
			   (TablesId,
				ColumnName,
				Active,
				Last_UserId_Log,
				Last_WorkstationId_Log,
				Last_DateTime_Log)
		SELECT distinct HT.TablesID AS tablesID, 
						c.name,
						1,
						1,
						1,  
						GetDate()
		FROM sys.tables AS t 
			INNER JOIN sys.columns c				ON t.OBJECT_ID = c.OBJECT_ID 
			INNER JOIN cnf_lookup                   on cnf_lookup.description = t.name and cnf_lookup.lookuptableid = 35  
			INNER JOIN cnf_HIL_Tables HT            ON HT.ReferenceTable = cnf_lookup.itemid		
		WHERE SCHEMA_NAME(schema_id) = 'dbo'
		  and t.name = @TABLE_NAME
		  AND (cast(HT.TablesID as Varchar(5000)) + c.Name) not in (select (cast(TablesID as Varchar(5000)) + ColumnName) from CNF_HIL_Columns)
		  AND c.Name not in ('Last_UserID_log', 'Last_WorkstationID_LOG', 'Last_DateTime_Log')

		DECLARE @sql nvarchar(max),
				@SQL1 NVARCHAR(MAX)

		SET NOCOUNT ON  

		EXEC('IF OBJECT_ID (''' + @TABLE_NAME + '_CT'', ''TR'') IS NOT NULL DROP TRIGGER ' + @TABLE_NAME + '_CT')
		SELECT @sql = 
		'create trigger ' + @TABLE_NAME + '_CT on ' + @TABLE_NAME + ' FOR insert, update, delete
		as
		declare @field int, @mfield int, @fname varchar(128), @TName varchar(128), @PKC varchar(max), @sql nvarchar(max), @Type nvarchar(1),
		@PKV varchar(max), @MId nvarchar(max) = ''0'', @TID nvarchar(max), @C nvarchar(max) = ''0''

		select @TName = ''' + @TABLE_NAME + ''', @TID=itemid from cnf_lookup where lookuptableid=35 and description=''' + @TABLE_NAME + '''
		if exists(select * from CNF_HIL_Tables where referencetable=@TID and Active=1)
		begin
			if exists (select * from inserted)
			if exists (select * from deleted)
			select @Type = ''2''
			else
			select @Type = ''3''
			else
			select @Type = ''1''

			select * into #ins from inserted
			select * into #del from deleted

			select @PKC = coalesce(@PKC + '' and'', '' on'') + '' i.'' + c.COLUMN_NAME + '' = d.'' + c.COLUMN_NAME, @PKV = coalesce(@PKV+''+'','''') + ''convert(varchar(100), coalesce(i.'' + COLUMN_NAME + '',d.'' + COLUMN_NAME + ''))''
			from INFORMATION_SCHEMA.TABLE_CONSTRAINTS p 
			INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE c on c.CONSTRAINT_NAME = p.CONSTRAINT_NAME and c.TABLE_NAME = p.TABLE_NAME
			where p.TABLE_NAME=@TName and CONSTRAINT_TYPE=''PRIMARY KEY''

			select @field=0, @mfield=max(ORDINAL_POSITION) from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME=@TName
			while  @field &lt; @mfield
			begin
				select @field = min(ORDINAL_POSITION) from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME=@TName and ORDINAL_POSITION&gt;@field
				select @fname = COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME=@TName and ORDINAL_POSITION=@field
				if exists(select * from CNF_Hil_Columns C INNER JOIN CNF_HIL_Tables T ON T.TablesId = C.TablesId where T.referencetable=@TID and C.ColumnName=@fname and C.Active=1)
				begin
					select @sql = ''if exists(select * from #ins i full outer join #del d '' + @PKC				
					select @sql = @sql + '' where i.'' + @fname + '' is not null and i.'' + @fname + '' &lt;&gt; d.'' + @fname + '' or (i.'' + @fname + '' is null and d.'' + @fname + '' is not null) or (i.'' + @fname + '' is not null and d.'' + @fname + '' is null)) set @C=1''
					EXECUTE sp_executesql @sql, N''@C nvarchar(max) OUTPUT'', @C OUTPUT 
					if @c=1 break 
				end
			end
			if @c=1
			begin
				set @field=0  '

		SELECT @sql1 ='
				while @field&lt;@mfield
				begin
					select @field=min(ORDINAL_POSITION) from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME=@TName	and ORDINAL_POSITION&gt;@field
					select @fname=COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME=@TName and ORDINAL_POSITION=@field
					if exists(select * from CNF_Hil_Columns C INNER JOIN CNF_HIL_Tables T ON T.TablesId = C.TablesId where T.referencetable=@TID and C.ColumnName=@fname and C.Active=1)
					begin	
						if @MId = 0
						begin
							select @sql = ''insert DATA_HIL_Master (OperationType, ReferenceTable, ReferenceId, UserId, WorkstationId, InsDateTime)''
							select @sql = @sql + '' select '''''' + @Type + ''''''''												
							select @sql = @sql + '', '''''' + @TID + ''''''''		
							select @sql = @sql + '','' + @PKV		
							select @sql = @sql + '',convert(varchar(1000),i.Last_UserId_Log), convert(varchar(1000),i.Last_WorkstationId_Log), convert(varchar(1000),i.Last_DateTime_Log)''
							select @sql = @sql + '' from #ins i full outer join #del d''
							select @sql = @sql + @PKC 
							select @sql = @sql + '' SELECT @MId = SCOPE_IDENTITY()''
							EXECUTE sp_executesql @sql, N''@MId nvarchar(max) OUTPUT'', @MId OUTPUT
						end
						if @Type &lt;&gt; ''1''
						BEGIN
							select @sql = ''insert data_HIL_Detail (MasterId, OriginalValue, ModifiedValue, ColumnName)''
							select @sql = @sql + '' select convert(varchar(1000),'' + @MId + ''), convert(varchar(1000),d.'' + @fname + ''), convert(varchar(1000),i.'' + @fname + '')''
							select @sql = @sql + '','''''' + @fname + ''''''''
							select @sql = @sql + '' from #ins i full outer join #del d '' + @PKC				
							select @sql = @sql + '' where i.'' + @fname + '' is not null and i.'' + @fname + '' &lt;&gt; d.'' + @fname + '' or (i.'' + @fname + '' is null and d.'' + @fname + '' is not null) or (i.'' + @fname + '' is not null and d.'' + @fname + '' is null)''				
							EXECUTE sp_executesql @sql 
		 				END		
					END 
				END	
			END 
		END'

		EXEC(@sql + @sql1)
		
	END
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>declare @TABLE_NAME sysname

SELECT @TABLE_NAME = MIN(TABLE_NAME) 
			FROM INFORMATION_SCHEMA.Tables 
		WHERE TABLE_TYPE = 'BASE TABLE' 
			AND TABLE_NAME != 'sysdiagrams'
			AND TABLE_SCHEMA = 'dbo'
			AND TABLE_NAME in (
	  							SELECT distinct t.name AS table_name
									FROM sys.tables AS t 
										INNER JOIN sys.columns c				ON t.OBJECT_ID = c.OBJECT_ID 	
									WHERE c.name LIKE '%LAST%LOG'
										and SCHEMA_NAME(schema_id) = 'dbo'
							)
			AND TABLE_NAME in (select Description
								from cnf_lookup
								where lookuptableid = 35)
			AND TABLE_NAME in (
								SELECT distinct t.name AS table_name
									FROM sys.tables AS t 
										INNER JOIN sys.columns c				ON t.OBJECT_ID = c.OBJECT_ID 	
									WHERE c.name LIKE '%LAST%LOG'
										and SCHEMA_NAME(schema_id) = 'dbo'
										and ((T.name like '%ADM_%') or (t.name like '%CNF_%') or
												(t.name in ('DATA_Account', 'DATA_AccountFinancial', 'DATA_AccountRelationship', 'DATA_DmgData',
															'DATA_DmgData_Translate', 'DATA_Right')))
								)
			AND TABLE_NAME NOT IN (SELECT table_name
								FROM information_schema.columns 
								where data_type in ('NTEXT', 'TEXT')
									AND TABLE_NAME in (
	  													SELECT distinct t.name AS table_name
															FROM sys.tables AS t 
																INNER JOIN sys.columns c				ON t.OBJECT_ID = c.OBJECT_ID 	
															WHERE c.name LIKE '%LAST%LOG'
																and SCHEMA_NAME(schema_id) = 'dbo'
													))


WHILE @TABLE_NAME IS NOT NULL
BEGIN
	Exec otn_sp_HIL_CreateHILTrigger @TABLE_NAME

	SELECT @TABLE_NAME = MIN(TABLE_NAME)
				FROM INFORMATION_SCHEMA.Tables 
			WHERE TABLE_NAME &gt; @TABLE_NAME
				AND TABLE_TYPE = 'BASE TABLE' 
				AND TABLE_NAME != 'sysdiagrams'
				AND TABLE_SCHEMA = 'dbo'
				AND TABLE_NAME in (
	  								SELECT distinct t.name AS table_name
										FROM sys.tables AS t 
											INNER JOIN sys.columns c				ON t.OBJECT_ID = c.OBJECT_ID 	
										WHERE c.name LIKE '%LAST%LOG'
											and SCHEMA_NAME(schema_id) = 'dbo'
								)
				AND TABLE_NAME in (select Description
								from cnf_lookup
								where lookuptableid = 35)
				AND TABLE_NAME in (
								SELECT distinct t.name AS table_name
									FROM sys.tables AS t 
										INNER JOIN sys.columns c				ON t.OBJECT_ID = c.OBJECT_ID 	
									WHERE c.name LIKE '%LAST%LOG'
										and SCHEMA_NAME(schema_id) = 'dbo'
										and ((T.name like '%ADM_%') or (t.name like '%CNF_%') or
												(t.name in ('DATA_Account', 'DATA_AccountFinancial', 'DATA_AccountRelationship', 'DATA_DmgData',
															'DATA_DmgData_Translate', 'DATA_Right')))
								)
				AND TABLE_NAME NOT IN (SELECT table_name
									FROM information_schema.columns 
									where data_type in ('NTEXT', 'TEXT')
										AND TABLE_NAME in (
	  														SELECT distinct t.name AS table_name
																FROM sys.tables AS t 
																	INNER JOIN sys.columns c				ON t.OBJECT_ID = c.OBJECT_ID 	
																WHERE c.name LIKE '%LAST%LOG'
																	and SCHEMA_NAME(schema_id) = 'dbo'
														))

END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>if exists(select * from sys.triggers where name = 'ddl_trig_createTable' )
   DROP TRIGGER ddl_trig_createTable ON DATABASE;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>CREATE TRIGGER ddl_trig_createTable   
ON DATABASE 
FOR CREATE_TABLE   
AS   
    
    DECLARE @TABLE_NAME varchar(255) 

	SELECT @TABLE_NAME = TABLE_NAME 
			FROM INFORMATION_SCHEMA.Tables 
		WHERE TABLE_TYPE = 'BASE TABLE' 
			AND TABLE_NAME != 'sysdiagrams'
			AND TABLE_NAME = EVENTDATA().value('(/EVENT_INSTANCE/ObjectName)[1]','nvarchar(100)')
			AND TABLE_SCHEMA = 'dbo'
			AND TABLE_NAME in (
	  							SELECT distinct t.name AS table_name
									FROM sys.tables AS t 
										INNER JOIN sys.columns c				ON t.OBJECT_ID = c.OBJECT_ID 	
									WHERE c.name LIKE '%LAST%LOG'
										and SCHEMA_NAME(schema_id) = 'dbo'
							)
			AND TABLE_NAME in (select Description
								from cnf_lookup
								where lookuptableid = 35)
			AND TABLE_NAME in (
								SELECT distinct t.name AS table_name
									FROM sys.tables AS t 
										INNER JOIN sys.columns c				ON t.OBJECT_ID = c.OBJECT_ID 	
									WHERE c.name LIKE '%LAST%LOG'
										and SCHEMA_NAME(schema_id) = 'dbo'
										and ((T.name like '%ADM_%') or (t.name like '%CNF_%') or
												(t.name in ('DATA_Account', 'DATA_AccountFinancial', 'DATA_AccountRelationship', 'DATA_DmgData',
															'DATA_DmgData_Translate', 'DATA_Right')))
								)
			AND TABLE_NAME NOT IN (SELECT table_name
								FROM information_schema.columns 
								where data_type in ('NTEXT', 'TEXT')
									AND TABLE_NAME in (
	  													SELECT distinct t.name AS table_name
															FROM sys.tables AS t 
																INNER JOIN sys.columns c				ON t.OBJECT_ID = c.OBJECT_ID 	
															WHERE c.name LIKE '%LAST%LOG'
																and SCHEMA_NAME(schema_id) = 'dbo'
													))


	Exec otn_sp_HIL_CreateHILTrigger @TABLE_NAME 
</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>pchen</ADDEDBY><SQLVERSION>2600</SQLVERSION><RMTRACKLINK>79136</RMTRACKLINK><REASON>1. Drop field QuestionList
2. append 3 standard fields: Last_UserId_Log, Last_WorkstationId_Log, Last_DateTime_Log
and QuestionList
3. Rename field DocTermsAndConditions to DocTermsAndConditionsId</REASON><TABLENAMES>CNF_DocTermsAndConditions=DocTermsAndConditionsId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'QuestionsList' AND
                Object_ID  = Object_ID(N'CNF_DocTermsAndConditions'))
BEGIN
  ALTER TABLE CNF_DocTermsAndConditions
  DROP COLUMN QuestionsList 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_DocTermsAndConditions'))
BEGIN
  ALTER TABLE CNF_DocTermsAndConditions
  ADD Last_UserId_Log Integer null 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_WorkstationId_Log' AND
                Object_ID  = Object_ID(N'CNF_DocTermsAndConditions'))
BEGIN
  ALTER TABLE CNF_DocTermsAndConditions
  ADD Last_WorkstationId_Log Integer null 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_DateTime_Log' AND
                Object_ID  = Object_ID(N'CNF_DocTermsAndConditions'))
BEGIN
  ALTER TABLE CNF_DocTermsAndConditions
  ADD Last_DateTime_Log DateTime null 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'QuestionsList' AND
                Object_ID  = Object_ID(N'CNF_DocTermsAndConditions'))
BEGIN
  ALTER TABLE CNF_DocTermsAndConditions
  ADD QuestionsList Nvarchar(max) null 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
           WHERE Name = N'DocTermsAndConditions' AND
           Object_ID  = Object_ID(N'CNF_DocTermsAndConditions'))
BEGIN
  EXEC sp_rename 'CNF_DocTermsAndConditions.[DocTermsAndConditions]', 'DocTermsAndConditionsId', 'COLUMN';
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>pchen</ADDEDBY><SQLVERSION>2599</SQLVERSION><RMTRACKLINK>79137</RMTRACKLINK><REASON>append 3 standard fields: Last_UserId_Log, Last_WorkstationId_Log, Last_DateTime_Log</REASON><TABLENAMES>CNF_ProductLinker=ProductLinkerId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_ProductLinker'))
BEGIN
  ALTER TABLE CNF_ProductLinker
  ADD Last_UserId_Log Integer null 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_WorkstationId_Log' AND
                Object_ID  = Object_ID(N'CNF_ProductLinker'))
BEGIN
  ALTER TABLE CNF_ProductLinker
  ADD Last_WorkstationId_Log Integer null 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_DateTime_Log' AND
                Object_ID  = Object_ID(N'CNF_ProductLinker'))
BEGIN
  ALTER TABLE CNF_ProductLinker
  ADD Last_DateTime_Log DateTime null 
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>pchen</ADDEDBY><SQLVERSION>2598</SQLVERSION><RMTRACKLINK>79137</RMTRACKLINK><REASON>create a new table : CNF_ProductLinker
append foreign key  : MatrixCellId
append foreign key  : MatrixSheetId
append foreign key  : AttributeId</REASON><TABLENAMES>CNF_ProductLinker=ProductLinkerId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'CNF_ProductLinker'))
                    
BEGIN
Create table [CNF_ProductLinker]
(
	[ProductLinkerId] Integer Identity(1,1) NOT NULL,
	[EntityType] Smallint NULL, 
	[EntityId] Integer NULL, 
	[MatrixCellId] Integer NULL, 
        [MatrixSheetId] Integer NULL,
        [AttributeId] Integer NULL,      
Primary Key ([ProductLinkerId])
) 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_ProductLinker_MatrixCellId')
BEGIN
  ALTER TABLE CNF_ProductLinker
  ADD CONSTRAINT [FK_CNF_ProductLinker_MatrixCellId] FOREIGN KEY([MatrixCellId]) 
  REFERENCES [CNF_MatrixCell] ([MatrixCellId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_ProductLinker_MatrixSheetId')
BEGIN
  ALTER TABLE CNF_ProductLinker
  ADD CONSTRAINT [FK_CNF_ProductLinker_MatrixSheetId] FOREIGN KEY([MatrixSheetId]) 
  REFERENCES [CNF_MatrixSheet] ([MatrixSheetId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_ProductLinker_AttributeId')
BEGIN
  ALTER TABLE CNF_ProductLinker
  ADD CONSTRAINT [FK_CNF_ProductLinker_AttributeId] FOREIGN KEY([AttributeId]) 
  REFERENCES [CNF_Attribute] ([AttributeId])
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fesposito</ADDEDBY><SQLVERSION>2597</SQLVERSION><RMTRACKLINK>78692</RMTRACKLINK><REASON>fixing patch 2596</REASON><TABLENAMES>DATA_Account=AccountId
DATA_AccountFinancial=AccountId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'TaxExemptFrom' AND
                Object_ID  = Object_ID(N'DATA_AccountFinancial'))
BEGIN
  ALTER TABLE DATA_AccountFinancial
  DROP COLUMN TaxExemptFrom, TaxExemptTo, TaxFileName  
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'TaxExemptFrom' AND
                Object_ID  = Object_ID(N'DATA_AccountFinancial'))
BEGIN
 alter table DATA_AccountFinancial
 add TaxExemptFrom DateTime null, 
     TaxExemptTo DateTime null, 
     TaxFileName NVarChar(255) null
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>mevans</ADDEDBY><SQLVERSION>2596</SQLVERSION><RMTRACKLINK>78692</RMTRACKLINK><REASON>moved Tax Exemptablility from DATA_Account to DATA_AccountFinancial</REASON><TABLENAMES>DATA_Account=AccountId
DATA_AccountFinancial=AccountId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>DECLARE @ConstraintName nvarchar(100);
SELECT @ConstraintName = c.name FROM sys.default_constraints c 
INNER JOIN sys.columns col ON col.default_object_id = c.object_id 
WHERE c.parent_object_id = OBJECT_ID('dbo.DATA_Account') AND col.name = 'TaxExemptable';
IF @ConstraintName IS NOT NULL 
BEGIN
	EXEC('ALTER TABLE [dbo].[DATA_Account] DROP CONSTRAINT ' + @ConstraintName)
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'TaxExemptable' AND
                Object_ID  = Object_ID(N'DATA_Account'))
BEGIN
  ALTER TABLE DATA_Account
  DROP COLUMN TaxExemptable 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'ValidThruDate' AND
                Object_ID  = Object_ID(N'DATA_Account'))
BEGIN
  ALTER TABLE DATA_Account
  DROP COLUMN ValidThruDate 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'ValidFromDate' AND
                Object_ID  = Object_ID(N'DATA_Account'))
BEGIN
  ALTER TABLE DATA_Account
  DROP COLUMN ValidFromDate 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'TaxExemptable' AND
                Object_ID  = Object_ID(N'DATA_AccountFinancial'))
BEGIN
 alter table DATA_AccountFinancial
 add TaxExemptable smallint null
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'TaxExemptTo' AND
                Object_ID  = Object_ID(N'DATA_AccountFinancial'))
BEGIN
 alter table DATA_AccountFinancial
 add TaxExemptTo Date null
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'TaxExemptFrom' AND
                Object_ID  = Object_ID(N'DATA_AccountFinancial'))
BEGIN
 alter table DATA_AccountFinancial
 add TaxExemptFrom Date null
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'TaxFileName' AND
                Object_ID  = Object_ID(N'DATA_AccountFinancial'))
BEGIN
 alter table DATA_AccountFinancial
 add TaxFileName Date null
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>2595</SQLVERSION><RMTRACKLINK>82983 </RMTRACKLINK><REASON>SQL Server will be removing Ntext and Text datatypes in the near future.</REASON><TABLENAMES>CNF_BoardFav=BoardFavId
CNF_DataMask=DataMaskId
CNF_Event=EventId
CNF_FlexContract=FlexContractId
CNF_FlexPlanTemplate=FlexPlanTemplateId
CNF_ImportMatch=ImportMatchId
CNF_Invoice=InvoiceId
CNF_LedgerAccount=LedgerAccountId
CNF_Location=LocationId
CNF_MapView=MapId
CNF_Producer=ProducerID
CNF_Product=ProductId
CNF_ProductValidity=ProductValidityId
CNF_Promotion=PromotionId
CNF_PromotionItem=PromotionItemId
CNF_PswDictionary=DictionaryId
CNF_Scheduler=SchedulerID
CNF_SeasonalRule=SeasonalRuleId
CNF_Subscription=SubscriptionId
CNF_TicketPackageGroup=TicketPackageGroupId
CNF_TravelMatrix=TravelMatrixId
CNF_UpSale=UpSaleId
CNF_User=UserId
CNF_UserGroup=UserGroupId
CNF_VenueMap=VenueMapId
CNF_VenueMapItem=VenueMapItemId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'FieldDescription' AND
                Object_ID  = Object_ID(N'CNF_DataMask'))
BEGIN
  ALTER TABLE CNF_DataMask
  ADD FieldDescription_Convert nvarchar(max)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'FieldDescription_Convert' AND
                Object_ID  = Object_ID(N'CNF_DataMask'))
BEGIN
	Update CNF_DataMask
	   Set FieldDescription_Convert = FieldDescription
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'FieldDescription' AND
                Object_ID  = Object_ID(N'CNF_DataMask'))
BEGIN
  ALTER TABLE CNF_DataMask
  Drop Column FieldDescription
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'FieldDescription_Convert' AND
                Object_ID  = Object_ID(N'CNF_DataMask'))
BEGIN 
	EXEC sp_rename 'CNF_DataMask.FieldDescription_Convert', 'FieldDescription', 'COLUMN'
END </SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Button' AND
                Object_ID  = Object_ID(N'CNF_BoardFav'))
BEGIN
  ALTER TABLE CNF_BoardFav
  ADD Button_Convert nvarchar(max)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Button_Convert' AND
                Object_ID  = Object_ID(N'CNF_BoardFav'))
BEGIN
	Update CNF_BoardFav
	   Set Button_Convert = Button
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Button' AND
                Object_ID  = Object_ID(N'CNF_BoardFav'))
BEGIN
  ALTER TABLE CNF_BoardFav
  Drop Column Button
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Button_Convert' AND
                Object_ID  = Object_ID(N'CNF_BoardFav'))
BEGIN 
	EXEC sp_rename 'CNF_BoardFav.Button_Convert', 'Button', 'COLUMN'
END </SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Note' AND
                Object_ID  = Object_ID(N'CNF_Event'))
BEGIN
  ALTER TABLE CNF_Event
  ADD Note_Convert nvarchar(max)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Note_Convert' AND
                Object_ID  = Object_ID(N'CNF_Event'))
BEGIN
	Update CNF_Event
	   Set Note_Convert = Note
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Note' AND
                Object_ID  = Object_ID(N'CNF_Event'))
BEGIN
  ALTER TABLE CNF_Event
  Drop Column Note
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Note_Convert' AND
                Object_ID  = Object_ID(N'CNF_Event'))
BEGIN 
	EXEC sp_rename 'CNF_Event.Note_Convert', 'Note', 'COLUMN'
END </SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Description' AND
                Object_ID  = Object_ID(N'CNF_FlexContract'))
BEGIN
  ALTER TABLE CNF_FlexContract
  ADD Description_Convert nvarchar(max)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Description_Convert' AND
                Object_ID  = Object_ID(N'CNF_FlexContract'))
BEGIN
	Update CNF_FlexContract
	   Set Description_Convert = Description
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Description' AND
                Object_ID  = Object_ID(N'CNF_FlexContract'))
BEGIN
  ALTER TABLE CNF_FlexContract
  Drop Column Description
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Description_Convert' AND
                Object_ID  = Object_ID(N'CNF_FlexContract'))
BEGIN 
	EXEC sp_rename 'CNF_FlexContract.Description_Convert', 'Description', 'COLUMN'
END </SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'TermsAndConditions' AND
                Object_ID  = Object_ID(N'CNF_FlexContract'))
BEGIN
  ALTER TABLE CNF_FlexContract
  ADD TermsAndConditions_Convert nvarchar(max)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'TermsAndConditions_Convert' AND
                Object_ID  = Object_ID(N'CNF_FlexContract'))
BEGIN
	Update CNF_FlexContract
	   Set TermsAndConditions_Convert = TermsAndConditions
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'TermsAndConditions' AND
                Object_ID  = Object_ID(N'CNF_FlexContract'))
BEGIN
  ALTER TABLE CNF_FlexContract
  Drop Column TermsAndConditions
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'TermsAndConditions_Convert' AND
                Object_ID  = Object_ID(N'CNF_FlexContract'))
BEGIN 
	EXEC sp_rename 'CNF_FlexContract.TermsAndConditions_Convert', 'TermsAndConditions', 'COLUMN'
END </SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'FlexPlanXML' AND
                Object_ID  = Object_ID(N'CNF_FlexPlanTemplate'))
BEGIN
  ALTER TABLE CNF_FlexPlanTemplate
  ADD FlexPlanXML_Convert nvarchar(max)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'FlexPlanXML_Convert' AND
                Object_ID  = Object_ID(N'CNF_FlexPlanTemplate'))
BEGIN
	Update CNF_FlexPlanTemplate
	   Set FlexPlanXML_Convert = FlexPlanXML
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'FlexPlanXML' AND
                Object_ID  = Object_ID(N'CNF_FlexPlanTemplate'))
BEGIN
  ALTER TABLE CNF_FlexPlanTemplate
  Drop Column FlexPlanXML
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'FlexPlanXML_Convert' AND
                Object_ID  = Object_ID(N'CNF_FlexPlanTemplate'))
BEGIN 
	EXEC sp_rename 'CNF_FlexPlanTemplate.FlexPlanXML_Convert', 'FlexPlanXML', 'COLUMN'
END </SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Options' AND
                Object_ID  = Object_ID(N'CNF_ImportMatch'))
BEGIN
  ALTER TABLE CNF_ImportMatch
  ADD Options_Convert nvarchar(max)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Options_Convert' AND
                Object_ID  = Object_ID(N'CNF_ImportMatch'))
BEGIN
	Update CNF_ImportMatch
	   Set Options_Convert = Options
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Options' AND
                Object_ID  = Object_ID(N'CNF_ImportMatch'))
BEGIN
  ALTER TABLE CNF_ImportMatch
  Drop Column Options
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Options_Convert' AND
                Object_ID  = Object_ID(N'CNF_ImportMatch'))
BEGIN 
	EXEC sp_rename 'CNF_ImportMatch.Options_Convert', 'Options', 'COLUMN'
END </SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Description' AND
                Object_ID  = Object_ID(N'CNF_Invoice'))
BEGIN
  ALTER TABLE CNF_Invoice
  ADD Description_Convert nvarchar(max)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Description_Convert' AND
                Object_ID  = Object_ID(N'CNF_Invoice'))
BEGIN
	Update CNF_Invoice
	   Set Description_Convert = Description
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Description' AND
                Object_ID  = Object_ID(N'CNF_Invoice'))
BEGIN
  ALTER TABLE CNF_Invoice
  Drop Column Description
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Description_Convert' AND
                Object_ID  = Object_ID(N'CNF_Invoice'))
BEGIN 
	EXEC sp_rename 'CNF_Invoice.Description_Convert', 'Description', 'COLUMN'
END </SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'AccountNotes' AND
                Object_ID  = Object_ID(N'CNF_LedgerAccount'))
BEGIN
  ALTER TABLE CNF_LedgerAccount
  ADD AccountNotes_Convert nvarchar(max)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'AccountNotes_Convert' AND
                Object_ID  = Object_ID(N'CNF_LedgerAccount'))
BEGIN
	Update CNF_LedgerAccount
	   Set AccountNotes_Convert = AccountNotes
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'AccountNotes' AND
                Object_ID  = Object_ID(N'CNF_LedgerAccount'))
BEGIN
  ALTER TABLE CNF_LedgerAccount
  Drop Column AccountNotes
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'AccountNotes_Convert' AND
                Object_ID  = Object_ID(N'CNF_LedgerAccount'))
BEGIN 
	EXEC sp_rename 'CNF_LedgerAccount.AccountNotes_Convert', 'AccountNotes', 'COLUMN'
END </SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Description' AND
                Object_ID  = Object_ID(N'CNF_Location'))
BEGIN
  ALTER TABLE CNF_Location
  ADD Description_Convert nvarchar(max)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Description_Convert' AND
                Object_ID  = Object_ID(N'CNF_Location'))
BEGIN
	Update CNF_Location
	   Set Description_Convert = Description
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Description' AND
                Object_ID  = Object_ID(N'CNF_Location'))
BEGIN
  ALTER TABLE CNF_Location
  Drop Column Description
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Description_Convert' AND
                Object_ID  = Object_ID(N'CNF_Location'))
BEGIN 
	EXEC sp_rename 'CNF_Location.Description_Convert', 'Description', 'COLUMN'
END </SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Attributes' AND
                Object_ID  = Object_ID(N'CNF_MapView'))
BEGIN
  ALTER TABLE CNF_MapView
  ADD Attributes_Convert nvarchar(max)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Attributes_Convert' AND
                Object_ID  = Object_ID(N'CNF_MapView'))
BEGIN
	Update CNF_MapView
	   Set Attributes_Convert = Attributes
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Attributes' AND
                Object_ID  = Object_ID(N'CNF_MapView'))
BEGIN
  ALTER TABLE CNF_MapView
  Drop Column Attributes
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Attributes_Convert' AND
                Object_ID  = Object_ID(N'CNF_MapView'))
BEGIN 
	EXEC sp_rename 'CNF_MapView.Attributes_Convert', 'Attributes', 'COLUMN'
END </SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Note' AND
                Object_ID  = Object_ID(N'CNF_Producer'))
BEGIN
  ALTER TABLE CNF_Producer
  ADD Note_Convert nvarchar(max)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Note_Convert' AND
                Object_ID  = Object_ID(N'CNF_Producer'))
BEGIN
	Update CNF_Producer
	   Set Note_Convert = Note
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Note' AND
                Object_ID  = Object_ID(N'CNF_Producer'))
BEGIN
  ALTER TABLE CNF_Producer
  Drop Column Note
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Note_Convert' AND
                Object_ID  = Object_ID(N'CNF_Producer'))
BEGIN 
	EXEC sp_rename 'CNF_Producer.Note_Convert', 'Note', 'COLUMN'
END </SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'ProductDescription' AND
                Object_ID  = Object_ID(N'CNF_Product'))
BEGIN
  ALTER TABLE CNF_Product
  ADD ProductDescription_Convert nvarchar(max)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'ProductDescription_Convert' AND
                Object_ID  = Object_ID(N'CNF_Product'))
BEGIN
	Update CNF_Product
	   Set ProductDescription_Convert = ProductDescription
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'ProductDescription' AND
                Object_ID  = Object_ID(N'CNF_Product'))
BEGIN
  ALTER TABLE CNF_Product
  Drop Column ProductDescription
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'ProductDescription_Convert' AND
                Object_ID  = Object_ID(N'CNF_Product'))
BEGIN 
	EXEC sp_rename 'CNF_Product.ProductDescription_Convert', 'ProductDescription', 'COLUMN'
END </SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'notes' AND
                Object_ID  = Object_ID(N'CNF_Promotion'))
BEGIN
  ALTER TABLE CNF_Promotion
  ADD notes_Convert nvarchar(max)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'notes_Convert' AND
                Object_ID  = Object_ID(N'CNF_Promotion'))
BEGIN
	Update CNF_Promotion
	   Set notes_Convert = notes
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'notes' AND
                Object_ID  = Object_ID(N'CNF_Promotion'))
BEGIN
  ALTER TABLE CNF_Promotion
  Drop Column notes
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'notes_Convert' AND
                Object_ID  = Object_ID(N'CNF_Promotion'))
BEGIN 
	EXEC sp_rename 'CNF_Promotion.notes_Convert', 'notes', 'COLUMN'
END </SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'notes' AND
                Object_ID  = Object_ID(N'CNF_PromotionItem'))
BEGIN
  ALTER TABLE CNF_PromotionItem
  ADD notes_Convert nvarchar(max)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'notes_Convert' AND
                Object_ID  = Object_ID(N'CNF_PromotionItem'))
BEGIN
	Update CNF_PromotionItem
	   Set notes_Convert = notes
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'notes' AND
                Object_ID  = Object_ID(N'CNF_PromotionItem'))
BEGIN
  ALTER TABLE CNF_PromotionItem
  Drop Column notes
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'notes_Convert' AND
                Object_ID  = Object_ID(N'CNF_PromotionItem'))
BEGIN 
	EXEC sp_rename 'CNF_PromotionItem.notes_Convert', 'notes', 'COLUMN'
END </SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'DictionaryText' AND
                Object_ID  = Object_ID(N'CNF_PswDictionary'))
BEGIN
  ALTER TABLE CNF_PswDictionary
  ADD DictionaryText_Convert nvarchar(max)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'DictionaryText_Convert' AND
                Object_ID  = Object_ID(N'CNF_PswDictionary'))
BEGIN
	Update CNF_PswDictionary
	   Set DictionaryText_Convert = DictionaryText
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'DictionaryText' AND
                Object_ID  = Object_ID(N'CNF_PswDictionary'))
BEGIN
  ALTER TABLE CNF_PswDictionary
  Drop Column DictionaryText
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'DictionaryText_Convert' AND
                Object_ID  = Object_ID(N'CNF_PswDictionary'))
BEGIN 
	EXEC sp_rename 'CNF_PswDictionary.DictionaryText_Convert', 'DictionaryText', 'COLUMN'
END </SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Configuration' AND
                Object_ID  = Object_ID(N'CNF_Scheduler'))
BEGIN
  ALTER TABLE CNF_Scheduler
  ADD Configuration_Convert nvarchar(max)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Configuration_Convert' AND
                Object_ID  = Object_ID(N'CNF_Scheduler'))
BEGIN
	Update CNF_Scheduler
	   Set Configuration_Convert = Configuration
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Configuration' AND
                Object_ID  = Object_ID(N'CNF_Scheduler'))
BEGIN
  ALTER TABLE CNF_Scheduler
  Drop Column Configuration
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Configuration_Convert' AND
                Object_ID  = Object_ID(N'CNF_Scheduler'))
BEGIN 
	EXEC sp_rename 'CNF_Scheduler.Configuration_Convert', 'Configuration', 'COLUMN'
END </SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'LastReference' AND
                Object_ID  = Object_ID(N'CNF_Scheduler'))
BEGIN
  ALTER TABLE CNF_Scheduler
  ADD LastReference_Convert nvarchar(max)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'LastReference_Convert' AND
                Object_ID  = Object_ID(N'CNF_Scheduler'))
BEGIN
	Update CNF_Scheduler
	   Set LastReference_Convert = LastReference
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'LastReference' AND
                Object_ID  = Object_ID(N'CNF_Scheduler'))
BEGIN
  ALTER TABLE CNF_Scheduler
  Drop Column LastReference
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'LastReference_Convert' AND
                Object_ID  = Object_ID(N'CNF_Scheduler'))
BEGIN 
	EXEC sp_rename 'CNF_Scheduler.LastReference_Convert', 'LastReference', 'COLUMN'
END </SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Description' AND
                Object_ID  = Object_ID(N'CNF_SeasonalRule'))
BEGIN
  ALTER TABLE CNF_SeasonalRule
  ADD Description_Convert nvarchar(max)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Description_Convert' AND
                Object_ID  = Object_ID(N'CNF_SeasonalRule'))
BEGIN
	Update CNF_SeasonalRule
	   Set Description_Convert = Description
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Description' AND
                Object_ID  = Object_ID(N'CNF_SeasonalRule'))
BEGIN
  ALTER TABLE CNF_SeasonalRule
  Drop Column Description
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Description_Convert' AND
                Object_ID  = Object_ID(N'CNF_SeasonalRule'))
BEGIN 
	EXEC sp_rename 'CNF_SeasonalRule.Description_Convert', 'Description', 'COLUMN'
END </SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Note' AND
                Object_ID  = Object_ID(N'CNF_Subscription'))
BEGIN
  ALTER TABLE CNF_Subscription
  ADD Note_Convert nvarchar(max)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Note_Convert' AND
                Object_ID  = Object_ID(N'CNF_Subscription'))
BEGIN
	Update CNF_Subscription
	   Set Note_Convert = Note
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Note' AND
                Object_ID  = Object_ID(N'CNF_Subscription'))
BEGIN
  ALTER TABLE CNF_Subscription
  Drop Column Note
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Note_Convert' AND
                Object_ID  = Object_ID(N'CNF_Subscription'))
BEGIN 
	EXEC sp_rename 'CNF_Subscription.Note_Convert', 'Note', 'COLUMN'
END </SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Note' AND
                Object_ID  = Object_ID(N'CNF_TicketPackageGroup'))
BEGIN
  ALTER TABLE CNF_TicketPackageGroup
  ADD Note_Convert nvarchar(max)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Note_Convert' AND
                Object_ID  = Object_ID(N'CNF_TicketPackageGroup'))
BEGIN
	Update CNF_TicketPackageGroup
	   Set Note_Convert = Note
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Note' AND
                Object_ID  = Object_ID(N'CNF_TicketPackageGroup'))
BEGIN
  ALTER TABLE CNF_TicketPackageGroup
  Drop Column Note
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Note_Convert' AND
                Object_ID  = Object_ID(N'CNF_TicketPackageGroup'))
BEGIN 
	EXEC sp_rename 'CNF_TicketPackageGroup.Note_Convert', 'Note', 'COLUMN'
END </SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Description' AND
                Object_ID  = Object_ID(N'CNF_TravelMatrix'))
BEGIN
  ALTER TABLE CNF_TravelMatrix
  ADD Description_Convert nvarchar(max)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Description_Convert' AND
                Object_ID  = Object_ID(N'CNF_TravelMatrix'))
BEGIN
	Update CNF_TravelMatrix
	   Set Description_Convert = Description
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Description' AND
                Object_ID  = Object_ID(N'CNF_TravelMatrix'))
BEGIN
  ALTER TABLE CNF_TravelMatrix
  Drop Column Description
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Description_Convert' AND
                Object_ID  = Object_ID(N'CNF_TravelMatrix'))
BEGIN 
	EXEC sp_rename 'CNF_TravelMatrix.Description_Convert', 'Description', 'COLUMN'
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'note' AND
                Object_ID  = Object_ID(N'CNF_User'))
BEGIN
  ALTER TABLE CNF_User
  ADD note_Convert nvarchar(max)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'note_Convert' AND
                Object_ID  = Object_ID(N'CNF_User'))
BEGIN
	Update CNF_User
	   Set note_Convert = note
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'note' AND
                Object_ID  = Object_ID(N'CNF_User'))
BEGIN
  ALTER TABLE CNF_User
  Drop Column note
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'note_Convert' AND
                Object_ID  = Object_ID(N'CNF_User'))
BEGIN 
	EXEC sp_rename 'CNF_User.note_Convert', 'note', 'COLUMN'
END </SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'HystoricalPsw' AND
                Object_ID  = Object_ID(N'cnf_user'))
BEGIN
  ALTER TABLE cnf_user
  ADD HystoricalPsw_Convert varchar(max)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'HystoricalPsw_Convert' AND
                Object_ID  = Object_ID(N'cnf_user'))
BEGIN
	Update cnf_user
	   Set HystoricalPsw_Convert = HystoricalPsw
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'HystoricalPsw' AND
                Object_ID  = Object_ID(N'cnf_user'))
BEGIN
  ALTER TABLE cnf_user
  Drop Column HystoricalPsw
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'HystoricalPsw_Convert' AND
                Object_ID  = Object_ID(N'cnf_user'))
BEGIN 
	EXEC sp_rename 'cnf_user.HystoricalPsw_Convert', 'HystoricalPsw', 'COLUMN'
END </SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Note' AND
                Object_ID  = Object_ID(N'CNF_UserGroup'))
BEGIN
  ALTER TABLE CNF_UserGroup
  ADD Note_Convert nvarchar(max)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Note_Convert' AND
                Object_ID  = Object_ID(N'CNF_UserGroup'))
BEGIN
	Update CNF_UserGroup
	   Set Note_Convert = Note
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Note' AND
                Object_ID  = Object_ID(N'CNF_UserGroup'))
BEGIN
  ALTER TABLE CNF_UserGroup
  Drop Column Note
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Note_Convert' AND
                Object_ID  = Object_ID(N'CNF_UserGroup'))
BEGIN 
	EXEC sp_rename 'CNF_UserGroup.Note_Convert', 'Note', 'COLUMN'
END </SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'MapDescription' AND
                Object_ID  = Object_ID(N'CNF_VenueMap'))
BEGIN
  ALTER TABLE CNF_VenueMap
  ADD MapDescription_Convert nvarchar(max)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'MapDescription_Convert' AND
                Object_ID  = Object_ID(N'CNF_VenueMap'))
BEGIN
	Update CNF_VenueMap
	   Set MapDescription_Convert = MapDescription
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'MapDescription' AND
                Object_ID  = Object_ID(N'CNF_VenueMap'))
BEGIN
  ALTER TABLE CNF_VenueMap
  Drop Column MapDescription
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'MapDescription_Convert' AND
                Object_ID  = Object_ID(N'CNF_VenueMap'))
BEGIN 
	EXEC sp_rename 'CNF_VenueMap.MapDescription_Convert', 'MapDescription', 'COLUMN'
END </SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'DetailXML' AND
                Object_ID  = Object_ID(N'CNF_VenueMapItem'))
BEGIN
  ALTER TABLE CNF_VenueMapItem
  ADD DetailXML_Convert nvarchar(max)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'DetailXML_Convert' AND
                Object_ID  = Object_ID(N'CNF_VenueMapItem'))
BEGIN
	Update CNF_VenueMapItem
	   Set DetailXML_Convert = DetailXML
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'DetailXML' AND
                Object_ID  = Object_ID(N'CNF_VenueMapItem'))
BEGIN
  ALTER TABLE CNF_VenueMapItem
  Drop Column DetailXML
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'DetailXML_Convert' AND
                Object_ID  = Object_ID(N'CNF_VenueMapItem'))
BEGIN 
	EXEC sp_rename 'CNF_VenueMapItem.DetailXML_Convert', 'DetailXML', 'COLUMN'
END </SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'FieldRulesXML' AND
                Object_ID  = Object_ID(N'CNF_DataMask'))
BEGIN
  ALTER TABLE CNF_DataMask
  ADD FieldRulesXML_Convert nvarchar(max)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'FieldRulesXML_Convert' AND
                Object_ID  = Object_ID(N'CNF_DataMask'))
BEGIN
	Update CNF_DataMask
	   Set FieldRulesXML_Convert = FieldRulesXML
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'FieldRulesXML' AND
                Object_ID  = Object_ID(N'CNF_DataMask'))
BEGIN
  ALTER TABLE CNF_DataMask
  Drop Column FieldRulesXML
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'FieldRulesXML_Convert' AND
                Object_ID  = Object_ID(N'CNF_DataMask'))
BEGIN 
	EXEC sp_rename 'CNF_DataMask.FieldRulesXML_Convert', 'FieldRulesXML', 'COLUMN'
END </SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'ValidityXML' AND
                Object_ID  = Object_ID(N'CNF_ProductValidity'))
BEGIN
  ALTER TABLE CNF_ProductValidity
  ADD ValidityXML_Convert nvarchar(max)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'ValidityXML_Convert' AND
                Object_ID  = Object_ID(N'CNF_ProductValidity'))
BEGIN
	Update CNF_ProductValidity
	   Set ValidityXML_Convert = ValidityXML
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'ValidityXML' AND
                Object_ID  = Object_ID(N'CNF_ProductValidity'))
BEGIN
  ALTER TABLE CNF_ProductValidity
  Drop Column ValidityXML
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'ValidityXML_Convert' AND
                Object_ID  = Object_ID(N'CNF_ProductValidity'))
BEGIN 
	EXEC sp_rename 'CNF_ProductValidity.ValidityXML_Convert', 'ValidityXML', 'COLUMN'
END </SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT> IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Note' AND
                Object_ID  = Object_ID(N'CNF_UpSale'))
BEGIN
  ALTER TABLE CNF_UpSale
  ADD Note_Convert nvarchar(max)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Note_Convert' AND
                Object_ID  = Object_ID(N'CNF_UpSale'))
BEGIN
	Update CNF_UpSale
	   Set Note_Convert = Note
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Note' AND
                Object_ID  = Object_ID(N'CNF_UpSale'))
BEGIN
  ALTER TABLE CNF_UpSale
  Drop Column Note
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Note_Convert' AND
                Object_ID  = Object_ID(N'CNF_UpSale'))
BEGIN 
	EXEC sp_rename 'CNF_UpSale.Note_Convert', 'Note', 'COLUMN'
END </SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>aeaton</ADDEDBY><SQLVERSION>2594</SQLVERSION><RMTRACKLINK>78915</RMTRACKLINK><REASON>Need a new promotion rule option to calculate the minimum amount based on the Net Price (without Tax)
</REASON><TABLENAMES>CNF_PromotionItemRule=PromotionItemRuleId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'UseNetRevenue' AND
                Object_ID  = Object_ID(N'CNF_PromotionItemRule'))
BEGIN
 alter table CNF_PromotionItemRule
 add UseNetRevenue smallint null
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>pchen</ADDEDBY><SQLVERSION>2593</SQLVERSION><RMTRACKLINK>79134</RMTRACKLINK><REASON>create a new table : CNF_DocTermsAndConditions
append foreign key  : DocTemplateId
</REASON><TABLENAMES>CNF_DocTermsAndConditions=DocTermsAndConditions</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'CNF_DocTermsAndConditions'))
                    
BEGIN
Create table [CNF_DocTermsAndConditions]
(
	[DocTermsAndConditions] Integer Identity(1,1) NOT NULL,
 	[QuestionsList] NText NULL,
	[Mandatory] Smallint NULL, 
	[DocTemplateId] Integer NULL,       
Primary Key ([DocTermsAndConditions])
) 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DocTermsAndConditions_DocTemplateId')
BEGIN
  ALTER TABLE CNF_DocTermsAndConditions
  ADD CONSTRAINT [FK_CNF_DocTermsAndConditions_DocTemplateId] FOREIGN KEY([DocTemplateId]) 
  REFERENCES [CNF_DocTemplate] ([DocTemplateId])
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>ecandido</ADDEDBY><SQLVERSION>2592</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>Create Column AK for UserGroup Table</REASON><TABLENAMES>CNF_UserGroup=UserGroupId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'UserGroupAK' AND
                Object_ID  = Object_ID(N'CNF_UserGroup'))
BEGIN
 alter table CNF_UserGroup
 add UserGroupAK nvarchar(32) null
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>update CNF_UserGroup set UserGroupAK =(
select 
  'ROLE' + Cast (UG.UserGroupId as varchar)
from CNF_UserGroup as UG
WHERE CNF_UserGroup.UserGroupId = UG.UserGroupId
)</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>alter table CNF_UserGroup
alter column UserGroupAk nvarchar(32) not null</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>insert into DATA_Counter (CounterType, IdentifierAK, ReferenceTime, Counter) 
(
select 
  40,
  'ROLE',
  'NEVER',
  IsNull(MAX(UG.UserGroupId), 0)

from CNF_UserGroup as UG
)</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>2591</SQLVERSION><RMTRACKLINK>82883</RMTRACKLINK><REASON>Need an Account Summary table for Chart of Accounts</REASON><TABLENAMES>RR_Data_Revenue_Totals=DataRevenueTotalsId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'RR_Data_Revenue_Totals'))
                    
BEGIN
	Create table [RR_Data_Revenue_Totals]
	(
		[DataRevenueTotalsId] Integer Identity(1,1) NOT NULL,
		[SiteId] Integer NOT NULL,
		[COAAccountId] Integer NOT NULL,
		[FCalcDate] Datetime NOT NULL,
		[Debit] Float NOT NULL,
		[Credit] Float NOT NULL,
	Primary Key ([DataRevenueTotalsId])
	) 

END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS 
  (SELECT * FROM sys.indexes WHERE name = 'IDX_DATA_Sale_Paid' AND 
   object_id = OBJECT_ID('[dbo].[DATA_Sale]'))
begin
	CREATE NONCLUSTERED INDEX [IDX_DATA_Sale_Paid]
	ON [dbo].[DATA_Sale] ([Paid])
	INCLUDE ([SaleId],[StatusCode],[PaidTransactionId],[VoidTransactionId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS 
  (SELECT * FROM sys.indexes WHERE name = 'IDX_Data_Transaction_TranasctionType' AND 
   object_id = OBJECT_ID('[dbo].[DATA_Transaction]'))
begin
	CREATE NONCLUSTERED INDEX [IDX_Data_Transaction_TranasctionType]
	ON [dbo].[DATA_Transaction] ([TransactionType])
	INCLUDE ([TransactionId],[SiteId],[SaleId],[TransactionDate],[FTransactionDate],[WorkstationId],[OperatingAreaId],[UserId],[TotalAmount],[TotalTaxes],[Revenue],[UserGroupId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS 
  (SELECT * FROM sys.indexes WHERE name = 'IDX_RR_DATA_Revenue_TransactionID_Trigger' AND 
   object_id = OBJECT_ID('[dbo].[RR_DATA_Revenue]'))
begin
	CREATE NONCLUSTERED INDEX [IDX_RR_DATA_Revenue_TransactionID_Trigger] ON [dbo].[RR_DATA_Revenue]
	(
		[RRCalcTypeTrigger] ASC,
		[TransactionId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS 
  (SELECT * FROM sys.indexes WHERE name = 'IDX_RR_DATA_Revenue_SaleItemId_Trigger' AND 
   object_id = OBJECT_ID('[dbo].[RR_DATA_Revenue]'))
begin
	CREATE NONCLUSTERED INDEX [IDX_RR_DATA_Revenue_SaleItemId_Trigger] ON [dbo].[RR_DATA_Revenue]
	(
		[SaleItemId] ASC,
		[RRCalcTypeTrigger] ASC
	)
	INCLUDE ( 	[COAAccountId]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS 
  (SELECT * FROM sys.indexes WHERE name = 'RR_DATA_Revenue_Ticketid_AccountingType' AND 
   object_id = OBJECT_ID('[dbo].[RR_DATA_Revenue]'))
begin
	CREATE NONCLUSTERED INDEX [RR_DATA_Revenue_Ticketid_AccountingType]
	ON [dbo].[RR_DATA_Revenue] ([TicketId],[AccountingType])
	INCLUDE ([COAAccountId],[RevenueAmount])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS 
  (SELECT * FROM sys.indexes WHERE name = 'CNF_AttributeSetDetail_AttributeId' AND 
   object_id = OBJECT_ID('[dbo].[CNF_AttributeSetDetail]'))
begin
	CREATE NONCLUSTERED INDEX [CNF_AttributeSetDetail_AttributeId]
	ON [dbo].[CNF_AttributeSetDetail] ([AttributeId])
	INCLUDE ([AttributeSetId])
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>mevans</ADDEDBY><SQLVERSION>2590</SQLVERSION><RMTRACKLINK>78691</RMTRACKLINK><REASON></REASON><TABLENAMES>CNF_Tax=TaxId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>DECLARE @ConstraintName nvarchar(100);
SELECT @ConstraintName = c.name FROM sys.default_constraints c 
INNER JOIN sys.columns col ON col.default_object_id = c.object_id 
WHERE c.parent_object_id = OBJECT_ID('dbo.CNF_Tax') AND col.name = 'ExemptableByAccount';
IF @ConstraintName IS NOT NULL 
BEGIN
	EXEC('ALTER TABLE [dbo].[CNF_Tax] DROP CONSTRAINT ' + @ConstraintName)
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'ExemptableByAccount' AND
                Object_ID  = Object_ID(N'CNF_Tax'))
BEGIN
  ALTER TABLE CNF_Tax
  DROP COLUMN ExemptableByAccount 
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>mevans</ADDEDBY><SQLVERSION>2589</SQLVERSION><RMTRACKLINK>78690</RMTRACKLINK><REASON></REASON><TABLENAMES>DATA_SaleTax=SaleTaxId
DATA_TransactionTax=TransactionTaxId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'TaxPercentage' AND
                Object_ID  = Object_ID(N'DATA_SaleTax'))
BEGIN
  ALTER TABLE DATA_SaleTax
  DROP COLUMN TaxPercentage 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'ProductPercentage' AND
                Object_ID  = Object_ID(N'DATA_SaleTax'))
BEGIN
  ALTER TABLE DATA_SaleTax
  DROP COLUMN ProductPercentage 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'TaxPercentage' AND
                Object_ID  = Object_ID(N'DATA_TransactionTax'))
BEGIN
  ALTER TABLE DATA_TransactionTax
  DROP COLUMN TaxPercentage 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'ProductPercentage' AND
                Object_ID  = Object_ID(N'DATA_TransactionTax'))
BEGIN
  ALTER TABLE DATA_TransactionTax
  DROP COLUMN ProductPercentage 
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>mevans</ADDEDBY><SQLVERSION>2588</SQLVERSION><RMTRACKLINK>78692</RMTRACKLINK><REASON></REASON><TABLENAMES>DATA_Account=AccountId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'TaxExemptable' AND
                Object_ID  = Object_ID(N'DATA_Account'))
BEGIN
  ALTER TABLE DATA_Account
  ADD TaxExemptable smallInt NOT NULL DEFAULT '0'
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'ValidThruDate' AND
                Object_ID  = Object_ID(N'DATA_Account'))
BEGIN
  ALTER TABLE DATA_Account 
  ADD ValidThruDate DateTime
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>mevans</ADDEDBY><SQLVERSION>2587</SQLVERSION><RMTRACKLINK>78691</RMTRACKLINK><REASON></REASON><TABLENAMES>CNF_Tax=TaxId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'ExemptableByAccount' AND
                Object_ID  = Object_ID(N'CNF_Tax'))
BEGIN
	ALTER TABLE CNF_Tax
	ADD ExemptableByAccount Smallint NOT NULL DEFAULT '0'
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>2586</SQLVERSION><RMTRACKLINK>7260</RMTRACKLINK><REASON></REASON><TABLENAMES>CNF_HIL_Tables=TablesId
DATA_HIL_Master=MasterId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'TableName' AND
                Object_ID  = Object_ID(N'CNF_HIL_Tables'))
BEGIN
	ALTER TABLE CNF_HIL_Tables
	DROP COLUMN TableName;
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'ReferenceTable' AND
                Object_ID  = Object_ID(N'CNF_HIL_Tables'))
BEGIN
	ALTER TABLE CNF_HIL_Tables
	ADD ReferenceTable Smallint;
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'ReferenceTable' AND
                Object_ID  = Object_ID(N'DATA_HIL_Master'))
BEGIN
	ALTER TABLE DATA_HIL_Master
	DROP COLUMN ReferenceTable;
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'ReferenceTable' AND
                Object_ID  = Object_ID(N'DATA_HIL_Master'))
BEGIN
	ALTER TABLE DATA_HIL_Master
	ADD ReferenceTable Smallint;
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>2585</SQLVERSION><RMTRACKLINK>72604</RMTRACKLINK><REASON>Renamed 3 history columns on DATA_HIL_Master</REASON><TABLENAMES>DATA_HIL_Master=MasterId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_HIL_Master_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_HIL_Master
  DROP CONSTRAINT FK_DATA_HIL_Master_Last_UserId_Log
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_HIL_Master_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_HIL_Master
  DROP CONSTRAINT FK_DATA_HIL_Master_Last_WorkstationId_Log
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_HIL_Master'))
BEGIN
  ALTER TABLE DATA_HIL_Master
  DROP COLUMN Last_UserId_Log, Last_WorkstationId_Log, Last_DateTime_Log
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'UserId' AND
                Object_ID  = Object_ID(N'DATA_HIL_Master'))
BEGIN
  Alter Table DATA_HIL_Master
  Add UserId Integer NULL,
      WorkstationId Integer NULL,
      InsDateTime Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_HIL_Master_UserId')
BEGIN
  ALTER TABLE DATA_HIL_Master
  ADD CONSTRAINT [FK_DATA_HIL_Master_UserId] FOREIGN KEY([UserId]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_HIL_Master_WorkstationId')
BEGIN
  ALTER TABLE DATA_HIL_Master
  ADD CONSTRAINT [FK_DATA_HIL_Master_WorkstationId] FOREIGN KEY([WorkstationId]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>pchen</ADDEDBY><SQLVERSION>2584</SQLVERSION><RMTRACKLINK>79134</RMTRACKLINK><REASON>create a new table : DATA_Ticket2Document
append foreign key  : TicketId
append foreign key  : DocumentId</REASON><TABLENAMES>DATA_Ticket2Document=Ticket2DocumentId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'DATA_Ticket2Document'))
                    
BEGIN
Create table [DATA_Ticket2Document]
(
	[Ticket2DocumentId] Integer Identity(1,1) NOT NULL,
 	[TicketId] Integer NULL,
	[DocumentId] Integer NULL, 
        [Filename] Nvarchar(100) NULL,
	[Signed] Smallint NULL,
 	[LastPage] Integer NULL,        
Primary Key ([Ticket2DocumentId])
) 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_Ticket2Document_TicketId')
BEGIN
  ALTER TABLE DATA_Ticket2Document
  ADD CONSTRAINT [FK_DATA_Ticket2Document_TicketId] FOREIGN KEY([TicketId]) 
  REFERENCES [DATA_Ticket] ([TicketId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_Ticket2Document_DocumentId')
BEGIN
  ALTER TABLE DATA_Ticket2Document
  ADD CONSTRAINT [FK_DATA_Ticket2Document_DocumentId] FOREIGN KEY([DocumentId]) 
  REFERENCES [ARC_Document] ([DocumentId])
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>mevans</ADDEDBY><SQLVERSION>2583</SQLVERSION><RMTRACKLINK>78690</RMTRACKLINK><REASON>Adding field 
DATA_SaleItemTax.TaxPercentage float
DATA_SaleTax.TaxPercentage float
DATA_TransactionTax.TaxPercentage float
DATA_SaleItemTax.ProductPercentage money
DATA_SaleTax.ProductPercentage money
DATA_TransactionTax.ProductPercentage money
</REASON><TABLENAMES>DATA_SaleItemTax=SaleItemTaxId
DATA_SaleTax=SaleTaxId
DATA_TransactionTax=TransactionTaxId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'TaxPercentage' AND
                Object_ID  = Object_ID(N'DATA_SaleItemTax'))
BEGIN
  ALTER TABLE DATA_SaleItemTax
  ADD TaxPercentage Float
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'ProductPercentage' AND
                Object_ID  = Object_ID(N'DATA_SaleItemTax'))
BEGIN
  ALTER TABLE DATA_SaleItemTax
  ADD ProductPercentage Money
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'TaxPercentage' AND
                Object_ID  = Object_ID(N'DATA_SaleTax'))
BEGIN
  ALTER TABLE DATA_SaleTax 
  ADD TaxPercentage Float
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'ProductPercentage' AND
                Object_ID  = Object_ID(N'DATA_SaleTax'))
BEGIN
  ALTER TABLE DATA_SaleTax 
  ADD ProductPercentage Money
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'TaxPercentage' AND
                Object_ID  = Object_ID(N'DATA_TransactionTax'))
BEGIN
  ALTER TABLE DATA_TransactionTax
  ADD TaxPercentage Float
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'ProductPercentage' AND
                Object_ID  = Object_ID(N'DATA_TransactionTax'))
BEGIN
  ALTER TABLE DATA_TransactionTax
  ADD ProductPercentage Money
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fdipalma</ADDEDBY><SQLVERSION>2582</SQLVERSION><RMTRACKLINK>79706</RMTRACKLINK><REASON>Adding table DATA_SaleLimit2MatrixCell
Drop Column DATA_SaleLimit.MatrixCellIds</REASON><TABLENAMES>DATA_SaleLimit2MatrixCell=SaleLimit2MatrixCellId
DATA_SaleLimit=SaleLimitId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES
           WHERE TABLE_NAME = N'DATA_SaleLimit2MatrixCell')
BEGIN
Create table [DATA_SaleLimit2MatrixCell]
(
	[SaleLimit2MatrixCellId] Integer Identity(1,1) NOT NULL, UNIQUE ([SaleLimit2MatrixCellId]),
	[SaleLimitId] Integer NOT NULL,
	[MatrixCellId] Integer NOT NULL,
	[Last_UserId_Log] Integer NULL,
	[Last_WorkstationId_Log] Integer NULL,
	[Last_DateTime_Log] Datetime NULL,
CONSTRAINT PK__DATA_SaleLimit2MatrixCell Primary Key ([SaleLimit2MatrixCellId]),
CONSTRAINT FK_DATA_SaleLimit2MatrixCell_SaleLimitId FOREIGN KEY ([SaleLimitId]) REFERENCES DATA_SaleLimit([SaleLimitId]),
CONSTRAINT FK_DATA_SaleLimit2MatrixCell_MatrixCellId FOREIGN KEY ([MatrixCellId]) REFERENCES CNF_MatrixCell([MatrixCellId]),
CONSTRAINT FK_DATA_SaleLimit2MatrixCell_Last_UserId_Log FOREIGN KEY ([Last_UserId_Log]) REFERENCES CNF_User([UserId]),
CONSTRAINT FK_DATA_SaleLimit2MatrixCell_Last_WorkstationId_Log FOREIGN KEY ([Last_WorkstationId_Log]) REFERENCES CNF_Workstation([WorkstationId])
)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
           WHERE Name = N'MatrixCellIds' AND
           Object_ID  = Object_ID(N'DATA_SaleLimit'))
BEGIN
DECLARE @SQLString nvarchar(1000);  
SET @SQLString = N'INSERT INTO DATA_SaleLimit2MatrixCell([SaleLimitId], [MatrixCellId])
SELECT
  DATA_SaleLimit.SaleLimitId,
  MC.MatrixCellId
FROM DATA_SaleLimit
outer apply Split(DATA_SaleLimit.MatrixCellIds, '','') as MCID
inner join CNF_MatrixCell as MC on (MCID.Value = MC.MatrixCellId)
WHERE MC.MatrixCellId IS NOT NULL';
exec sp_executesql @SQLString;
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
           WHERE Name = N'MatrixCellIds' AND
           Object_ID  = Object_ID(N'DATA_SaleLimit'))
BEGIN
  UPDATE DATA_SaleLimit SET MatrixCellIds = null  
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
           WHERE Name = N'MatrixCellIds' AND
           Object_ID  = Object_ID(N'DATA_SaleLimit'))
BEGIN
  ALTER TABLE DATA_SaleLimit 
  DROP COLUMN MatrixCellIds
END;</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>2581</SQLVERSION><RMTRACKLINK>82740</RMTRACKLINK><REASON>3 history fields removed from ADM_AccessPoint</REASON><TABLENAMES>ADM_AccessPoint=WorkstationId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_ADM_AccessPoint_Last_UserId_Log')
BEGIN
  ALTER TABLE ADM_AccessPoint
  DROP CONSTRAINT FK_ADM_AccessPoint_Last_UserId_Log
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_ADM_AccessPoint_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE ADM_AccessPoint
  DROP CONSTRAINT FK_ADM_AccessPoint_Last_WorkstationId_Log
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'ADM_AccessPoint'))
BEGIN
  ALTER TABLE ADM_AccessPoint
  DROP COLUMN Last_UserId_Log, Last_WorkstationId_Log, Last_DateTime_Log
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fdipalma</ADDEDBY><SQLVERSION>2580</SQLVERSION><RMTRACKLINK>79706</RMTRACKLINK><REASON>Adding table CNF_SaleRestriction2MatrixCell
Drop Column CNF_SaleRestriction.MatrixCellIds</REASON><TABLENAMES>CNF_SaleRestriction2MatrixCell=SaleRestriction2MatrixCellId
CNF_SaleRestriction=SaleRestrictionId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES
           WHERE TABLE_NAME = N'CNF_SaleRestriction2MatrixCell')
BEGIN
Create table [CNF_SaleRestriction2MatrixCell]
(
	[SaleRestriction2MatrixCellId] Integer Identity(1,1) NOT NULL, UNIQUE ([SaleRestriction2MatrixCellId]),
	[SaleRestrictionId] Integer NOT NULL,
	[MatrixCellId] Integer NOT NULL,
	[Last_UserId_Log] Integer NULL,
	[Last_WorkstationId_Log] Integer NULL,
	[Last_DateTime_Log] Datetime NULL,
CONSTRAINT PK__CNF_SaleRestriction2MatrixCell Primary Key ([SaleRestriction2MatrixCellId]),
CONSTRAINT FK_CNF_SaleRestriction2MatrixCell_SaleRestrictionId FOREIGN KEY ([SaleRestrictionId]) REFERENCES CNF_SaleRestriction([SaleRestrictionId]),
CONSTRAINT FK_CNF_SaleRestriction2MatrixCell_MatrixCellId FOREIGN KEY ([MatrixCellId]) REFERENCES CNF_MatrixCell([MatrixCellId]),
CONSTRAINT FK_CNF_SaleRestriction2MatrixCell_Last_UserId_Log FOREIGN KEY ([Last_UserId_Log]) REFERENCES CNF_User([UserId]),
CONSTRAINT FK_CNF_SaleRestriction2MatrixCell_Last_WorkstationId_Log FOREIGN KEY ([Last_WorkstationId_Log]) REFERENCES CNF_Workstation([WorkstationId])
)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
           WHERE Name = N'MatrixCellIds' AND
           Object_ID  = Object_ID(N'CNF_SaleRestriction'))
BEGIN
DECLARE @SQLString nvarchar(1000);
SET @SQLString = N'INSERT INTO CNF_SaleRestriction2MatrixCell([SaleRestrictionId], [MatrixCellId])
SELECT
  CNF_SaleRestriction.SaleRestrictionId,
  MC.MatrixCellId
FROM CNF_SaleRestriction
outer apply  Split(CNF_SaleRestriction.MatrixCellIds, '','') as MCID
inner join CNF_MatrixCell as MC on (MCID.Value = MC.MatrixCellId)
WHERE MC.MatrixCellId IS NOT NULL';
exec sp_executesql @SQLString;
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
           WHERE Name = N'MatrixCellIds' AND
           Object_ID  = Object_ID(N'CNF_SaleRestriction'))
BEGIN
  ALTER TABLE CNF_SaleRestriction 
  DROP COLUMN MatrixCellIds
END;
</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fdipalma</ADDEDBY><SQLVERSION>2579</SQLVERSION><RMTRACKLINK>79706</RMTRACKLINK><REASON>Adding field 
CNF_SaleRestriction.MaxAllowedPerTckAccount integer
DATA_SaleLimit.MaxAllowedPerTckAccount integer
DATA_SaleLimit.UsedPerTckAccount integer
Drop field 
CNF_SaleRestrictionValidity.MaxAllowedPerTckAccount integer
CNF_SaleRestrictionValidity.MaxAllowedPerTckAccountPerPeriod integer
DATA_SaleLimitRestriction.MaxAllowedPerTckAccount integer
DATA_SaleLimitRestriction.UsedPerTckAccount integer</REASON><TABLENAMES>CNF_SaleRestriction=SaleRestrictionId
DATA_SaleLimit=SaleLimitId
DATA_SaleLimitRestriction=SaleLimitRestrictionId
CNF_SaleRestrictionValidity=SaleRestrictionValidityId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'MaxAllowedPerTckAccount' AND
                Object_ID  = Object_ID(N'CNF_SaleRestriction'))
BEGIN
  ALTER TABLE CNF_SaleRestriction 
  ADD MaxAllowedPerTckAccount integer
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'MaxAllowedPerTckAccount' AND
                Object_ID  = Object_ID(N'DATA_SaleLimit'))
BEGIN
  ALTER TABLE DATA_SaleLimit 
  ADD MaxAllowedPerTckAccount integer
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'UsedPerTckAccount' AND
                Object_ID  = Object_ID(N'DATA_SaleLimit'))
BEGIN
  ALTER TABLE DATA_SaleLimit 
  ADD UsedPerTckAccount integer
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF OBJECT_ID ( 'otn_sp_ui_CNF_SaleLimit_delete', 'P' ) IS NOT NULL   
    DROP PROCEDURE otn_sp_ui_CNF_SaleLimit_delete;

IF OBJECT_ID ( 'otn_sp_ui_CNF_SaleLimit_insert', 'P' ) IS NOT NULL   
    DROP PROCEDURE otn_sp_ui_CNF_SaleLimit_insert;

IF OBJECT_ID ( 'otn_sp_ui_CNF_SaleLimit_update', 'P' ) IS NOT NULL   
    DROP PROCEDURE otn_sp_ui_CNF_SaleLimit_update;

IF OBJECT_ID ( 'otn_sp_ui_CNF_SaleLimitRestriction_delete', 'P' ) IS NOT NULL   
    DROP PROCEDURE otn_sp_ui_CNF_SaleLimitRestriction_delete;

IF OBJECT_ID ( 'otn_sp_ui_CNF_SaleLimitRestriction_insert', 'P' ) IS NOT NULL   
    DROP PROCEDURE otn_sp_ui_CNF_SaleLimitRestriction_insert;

IF OBJECT_ID ( 'otn_sp_ui_CNF_SaleLimitRestriction_update', 'P' ) IS NOT NULL   
    DROP PROCEDURE otn_sp_ui_CNF_SaleLimitRestriction_update;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
           WHERE Name = N'MaxAllowedPerTckAccount' AND
           Object_ID  = Object_ID(N'DATA_SaleLimitRestriction'))
BEGIN
  ALTER TABLE DATA_SaleLimitRestriction 
  DROP COLUMN MaxAllowedPerTckAccount
END;

IF EXISTS (SELECT * FROM sys.columns
           WHERE Name = N'UsedPerTckAccount' AND
           Object_ID  = Object_ID(N'DATA_SaleLimitRestriction'))
BEGIN
  ALTER TABLE DATA_SaleLimitRestriction 
  DROP COLUMN UsedPerTckAccount
END;

IF EXISTS (SELECT * FROM sys.columns
           WHERE Name = N'MaxAllowedPerTckAccount' AND
           Object_ID  = Object_ID(N'CNF_SaleRestrictionValidity'))
BEGIN
  ALTER TABLE CNF_SaleRestrictionValidity 
  DROP COLUMN MaxAllowedPerTckAccount
END;

IF EXISTS (SELECT * FROM sys.columns
           WHERE Name = N'MaxAllowedPerTckAccountPerPeriod' AND
           Object_ID  = Object_ID(N'CNF_SaleRestrictionValidity'))
BEGIN
  ALTER TABLE CNF_SaleRestrictionValidity 
  DROP COLUMN MaxAllowedPerTckAccountPerPeriod
END;</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>2578</SQLVERSION><RMTRACKLINK>78731 </RMTRACKLINK><REASON>Need the ability to define if monies collected on upgrades will remain in the original ticket's chart of account</REASON><TABLENAMES>RR_CNF_RevenueRecognitionRule=RevenueRecognitionRuleId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>DECLARE @sql NVARCHAR(MAX)
WHILE 1=1
BEGIN
    SELECT TOP 1 @sql = N'alter table RR_CNF_RevenueRecognitionRule drop constraint ['+dc.NAME+N']'
    from sys.default_constraints dc
    JOIN sys.columns c
        ON c.default_object_id = dc.object_id
    WHERE 
        dc.parent_object_id = OBJECT_ID('RR_CNF_RevenueRecognitionRule')
    AND c.name = N'UpgradeLeaveMoneyInOriginalAccount'
    IF @@ROWCOUNT = 0 BREAK
    EXEC (@sql)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>DECLARE @sql NVARCHAR(MAX)
WHILE 1=1
BEGIN
    SELECT TOP 1 @sql = N'alter table RR_CNF_RevenueRecognitionRule drop constraint ['+dc.NAME+N']'
    from sys.default_constraints dc
    JOIN sys.columns c
        ON c.default_object_id = dc.object_id
    WHERE 
        dc.parent_object_id = OBJECT_ID('RR_CNF_RevenueRecognitionRule')
    AND c.name = N'DownGradeLeaveMoneyInOriginalAccount'
    IF @@ROWCOUNT = 0 BREAK
    EXEC (@sql)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'UpgradeLeaveMoneyInOriginalAccount' AND
                Object_ID  = Object_ID(N'RR_CNF_RevenueRecognitionRule'))
BEGIN
	ALTER TABLE RR_CNF_RevenueRecognitionRule
	DROP COLUMN UpgradeLeaveMoneyInOriginalAccount;
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'DownGradeLeaveMoneyInOriginalAccount' AND
                Object_ID  = Object_ID(N'RR_CNF_RevenueRecognitionRule'))
BEGIN
	ALTER TABLE RR_CNF_RevenueRecognitionRule
	DROP COLUMN DownGradeLeaveMoneyInOriginalAccount;
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'UpgradeType' AND
                Object_ID  = Object_ID(N'RR_CNF_RevenueRecognitionRule'))
BEGIN
  Alter Table RR_CNF_RevenueRecognitionRule
  Add UpgradeType smallint not null default 0
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>mevans</ADDEDBY><SQLVERSION>2577</SQLVERSION><RMTRACKLINK>78690</RMTRACKLINK><REASON>change CNF_Tax2Package.TaxPercentage from bcd to float</REASON><TABLENAMES>CNF_Tax2Package=Tax2PackageId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'TaxPercentage' AND
                Object_ID  = Object_ID(N'CNF_Tax2Package'))
BEGIN
	ALTER TABLE CNF_Tax2Package
	DROP COLUMN TaxPercentage;
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF not EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'TaxPercentage' AND
                Object_ID  = Object_ID(N'CNF_Tax2Package'))
BEGIN
	ALTER TABLE CNF_Tax2Package
	ADD TaxPercentage FLOAT;
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>pchen</ADDEDBY><SQLVERSION>2576</SQLVERSION><RMTRACKLINK>79134</RMTRACKLINK><REASON>create a new table : CNF_MatrixCellDocument</REASON><TABLENAMES>CNF_MatrixCellDocument=MatrixCellDocumentId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'CNF_MatrixCellDocument'))
                    
BEGIN
Create table [CNF_MatrixCellDocument]
(
	[MatrixCellDocumentId] Integer Identity(1,1) NOT NULL,
	[Code] Nvarchar(10) NULL,
        [Name] Nvarchar(30) NULL,
	[QuestionsList] NText NULL,
	[Enabled] Smallint NULL,
	[Mandatory] Smallint NULL,
	[Signature] Smallint NULL,
 	[MatrixCellId] Integer NULL,
	[DocTemplateId] Integer NULL, 
Primary Key ([MatrixCellDocumentId])
) 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_MatrixCellDocument_MatrixCellId')
BEGIN
  ALTER TABLE CNF_MatrixCellDocument
  ADD CONSTRAINT [FK_CNF_MatrixCellDocument_MatrixCellId] FOREIGN KEY([MatrixCellId]) 
  REFERENCES [CNF_MatrixCell] ([MatrixCellId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_MatrixCellDocument_DocTemplateId')
BEGIN
  ALTER TABLE CNF_MatrixCellDocument
  ADD CONSTRAINT [FK_CNF_MatrixCellDocument_DocTemplateId] FOREIGN KEY([DocTemplateId]) 
  REFERENCES [CNF_DocTemplate] ([DocTemplateId])
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>2575</SQLVERSION><RMTRACKLINK>72604</RMTRACKLINK><REASON>4 new tables: 
CNF_HIL_Tables,
CNF_HIL_Columns,
DATA_HIL_Master,
DATA_HIL_Detail</REASON><TABLENAMES>DATA_HIL_Master=MasterId
DATA_HIL_Detail=DetailId
CNF_HIL_Tables=TablesId
CNF_HIL_Columns=ColumnsId
</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'DATA_HIL_Master'))
                    
BEGIN
Create table [DATA_HIL_Master]
(
	[MasterId] Integer Identity(1,1) NOT NULL,
	[ReferenceTable] Nvarchar(100) NULL,
	[ReferenceId] Integer NULL,
	[OperationType] Smallint NULL,
	[Last_UserId_Log] Integer NULL,
	[Last_WorkstationId_Log] Integer NULL,
	[Last_DateTime_Log] Datetime NULL,
Primary Key ([MasterId])
) 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_HIL_Master_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_HIL_Master
  ADD CONSTRAINT [FK_DATA_HIL_Master_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_HIL_Master_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_HIL_Master
  ADD CONSTRAINT [FK_DATA_HIL_Master_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'DATA_HIL_Detail'))
                    
BEGIN
Create table [DATA_HIL_Detail]
(
	[DetailId] Integer Identity(1,1) NOT NULL,
	[MasterId] Integer NOT NULL,
	[ColumnName] Nvarchar(100) NULL,
	[OriginalValue] Nvarchar(max) NULL,
	[ModifiedValue] Nvarchar(max) NULL,
Primary Key ([DetailId])
) 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_HIL_Detail_MasterId')
BEGIN
  ALTER TABLE DATA_HIL_Detail
  ADD CONSTRAINT [FK_DATA_HIL_Detail_MasterId] FOREIGN KEY([MasterId]) 
  REFERENCES [DATA_HIL_Master] ([MasterId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'CNF_HIL_Tables'))
                    
BEGIN
Create table [CNF_HIL_Tables]
(
	[TablesId] Integer Identity(1,1) NOT NULL,
	[TableName] Nvarchar(100) NULL,
	[Active] Smallint NULL,
	[Last_UserId_Log] Integer NULL,
	[Last_WorkstationId_Log] Integer NULL,
	[Last_DateTime_Log] Datetime NULL,
Primary Key ([TablesId])
) 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_HIL_Tables_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_HIL_Tables
  ADD CONSTRAINT [FK_CNF_HIL_Tables_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_HIL_Tables_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_HIL_Tables
  ADD CONSTRAINT [FK_CNF_HIL_Tables_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'CNF_HIL_Columns'))
                    
BEGIN
Create table [CNF_HIL_Columns]
(
	[ColumnsId] Integer Identity(1,1) NOT NULL,
	[TablesId] Integer NOT NULL,
	[ColumnName] Nvarchar(100) NULL,
	[Active] Smallint NULL,
	[Last_UserId_Log] Integer NULL,
	[Last_WorkstationId_Log] Integer NULL,
	[Last_DateTime_Log] Datetime NULL,
Primary Key ([ColumnsId])
) 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_HIL_Columns_TablesId')
BEGIN
  ALTER TABLE CNF_HIL_Columns
  ADD CONSTRAINT [FK_CNF_HIL_Columns_TablesId] FOREIGN KEY([TablesId]) 
  REFERENCES [CNF_HIL_Tables] ([TablesId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_HIL_Columns_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_HIL_Columns
  ADD CONSTRAINT [FK_CNF_HIL_Columns_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_HIL_Columns_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_HIL_Columns
  ADD CONSTRAINT [FK_CNF_HIL_Columns_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>2574</SQLVERSION><RMTRACKLINK>78731 </RMTRACKLINK><REASON>Need the ability to define if monies collected on upgrades will remain in the original ticket's chart of account</REASON><TABLENAMES>RR_CNF_RevenueRecognitionRule=RevenueRecognitionRuleId
COA_CNF_AccountConfig=COAAccountConfigId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'UpgradeLeaveMoneyInOriginalAccount' AND
                Object_ID  = Object_ID(N'RR_CNF_RevenueRecognitionRule'))
BEGIN
  Alter Table RR_CNF_RevenueRecognitionRule
  Add UpgradeLeaveMoneyInOriginalAccount smallint not null default 0
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'DownGradeLeaveMoneyInOriginalAccount' AND
                Object_ID  = Object_ID(N'RR_CNF_RevenueRecognitionRule'))
BEGIN
  Alter Table RR_CNF_RevenueRecognitionRule
 Add DownGradeLeaveMoneyInOriginalAccount smallint not null default 0
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'DebitOriginalAccount' AND
                Object_ID  = Object_ID(N'COA_CNF_AccountConfig'))
BEGIN
	ALTER TABLE COA_CNF_AccountConfig
	DROP COLUMN DebitOriginalAccount;
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fesposito</ADDEDBY><SQLVERSION>2573</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>Added field Redeemed to DATA_SaleItemRedeem</REASON><TABLENAMES>DATA_SaleItemRedeem=SaleItemRedeemId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Redeemed' AND
                Object_ID  = Object_ID(N'DATA_SaleItemRedeem'))
BEGIN
  ALTER TABLE DATA_SaleItemRedeem 
  ADD Redeemed smallint not null default 1
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fdipalma</ADDEDBY><SQLVERSION>2572</SQLVERSION><RMTRACKLINK>79706</RMTRACKLINK><REASON>Adding field CNF_SaleRestrictionValidity.MaxAllowedPerTckAccountPerPeriod integer</REASON><TABLENAMES>CNF_SaleRestrictionValidity=SaleRestrictionValidityId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'MaxAllowedPerTckAccountPerPeriod' AND
                Object_ID  = Object_ID(N'CNF_SaleRestrictionValidity'))
BEGIN
  ALTER TABLE CNF_SaleRestrictionValidity 
  ADD MaxAllowedPerTckAccountPerPeriod integer
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fdipalma</ADDEDBY><SQLVERSION>2571</SQLVERSION><RMTRACKLINK>79706</RMTRACKLINK><REASON>0 Rename CNF_SaleLimit in DATA_SaleLimit with all PK and FK
1 Rename CNF_SaleLimitRestriction in DATA_SaleLimitRestriction with all PK and FK</REASON><TABLENAMES>DATA_SaleLimit=SaleLimitId
DATA_SaleLimitRestriction=SaleLimitRestrictionId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES
           WHERE TABLE_NAME = N'CNF_SaleLimit')
BEGIN  
  EXEC sp_rename CNF_SaleLimit, DATA_SaleLimit;
  DECLARE @Old_PK_1 NVARCHAR(30)= (SELECT KU.CONSTRAINT_NAME
	FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS TC
	INNER JOIN
		INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KU
			  ON TC.CONSTRAINT_TYPE = 'PRIMARY KEY' AND
				 TC.CONSTRAINT_NAME = KU.CONSTRAINT_NAME AND 
				 KU.table_name='DATA_SaleLimit');
  EXEC sp_rename @Old_PK_1, PK__DATA_SaleLimit;
  DECLARE @Old_FK_1 NVARCHAR(30)= (SELECT  
		fk.name
	FROM 
		sys.foreign_keys fk
	INNER JOIN 
		sys.foreign_key_columns fkc ON fkc.constraint_object_id = fk.object_id
	INNER JOIN
		sys.columns c1 ON fkc.parent_column_id = c1.column_id AND fkc.parent_object_id = c1.object_id
	INNER JOIN
		sys.columns c2 ON fkc.referenced_column_id = c2.column_id AND fkc.referenced_object_id = c2.object_id
	WHERE
	  OBJECT_NAME(fk.parent_object_id) = 'DATA_SaleLimit' and
	  OBJECT_NAME(fk.referenced_object_id) = 'DATA_Account');
  EXEC sp_rename @Old_FK_1, fk_DATA_SaleLimit_DATA_Account;
  EXEC sp_rename fk_CNF_SaleLimit_CNF_Performance, fk_DATA_SaleLimit_CNF_Performance;
  EXEC sp_rename FK_CNF_SaleLimit_Last_UserId_Log, FK_DATA_SaleLimit_Last_UserId_Log;
  EXEC sp_rename FK_CNF_SaleLimit_Last_WorkstationId_Log, FK_DATA_SaleLimit_Last_WorkstationId_Log;
  EXEC sp_rename fk_DATA_Sale_CNF_SaleLimit, fk_DATA_Sale_DATA_SaleLimit;
END

</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES
           WHERE TABLE_NAME = N'CNF_SaleLimitRestriction')
BEGIN  
  EXEC sp_rename CNF_SaleLimitRestriction, DATA_SaleLimitRestriction;
  DECLARE @Old_PK NVARCHAR(30)= (SELECT KU.CONSTRAINT_NAME
	FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS TC
	INNER JOIN
		INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KU
			  ON TC.CONSTRAINT_TYPE = 'PRIMARY KEY' AND
				 TC.CONSTRAINT_NAME = KU.CONSTRAINT_NAME AND 
				 KU.table_name='DATA_SaleLimitRestriction');
  EXEC sp_rename @Old_PK, PK__DATA_SaleLimitRestriction;
  EXEC sp_rename FK_CNF_SaleLimitRestriction_Last_UserId_Log, FK_DATA_SaleLimitRestriction_Last_UserId_Log;
  EXEC sp_rename FK_CNF_SaleLimitRestriction_Last_WorkstationId_Log, FK_DATA_SaleLimitRestriction_Last_WorkstationId_Log;
  EXEC sp_rename fk_CNF_SaleLimitRestriction_SaleLimitId, fk_DATA_SaleLimitRestriction_SaleLimitId;
  EXEC sp_rename fk_CNF_SaleLimitRestriction_SaleRestrictionId, fk_DATA_SaleLimitRestriction_SaleRestrictionId;
  EXEC sp_rename fk_CNF_SaleLimitRestriction_SaleRestrictionValidityId, fk_DATA_SaleLimitRestriction_SaleRestrictionValidityId;
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2570</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>0 ADD RollingType
1 ADD RollingValueFrom
2 ADD RollingValueTo 
3 UPDATE RollingValueTo = PerfNumDays
4 DROP PerfNumDays
</REASON><TABLENAMES>CNF_Attribute=AttributeId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'RollingType' AND
                Object_ID  = Object_ID(N'cnf_attribute'))
BEGIN
  ALTER TABLE cnf_attribute
  ADD RollingType smallint
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'RollingValueFrom' AND
                Object_ID  = Object_ID(N'cnf_attribute'))
BEGIN
   ALTER TABLE cnf_attribute
   ADD RollingValueFrom int
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'RollingValueTo' AND
                Object_ID  = Object_ID(N'cnf_attribute'))
BEGIN
  ALTER TABLE cnf_attribute
  ADD RollingValueTo int
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'PerfNumDays' AND
                Object_ID  = Object_ID(N'cnf_attribute'))
BEGIN
  ALTER TABLE cnf_attribute
  DROP COLUMN PerfNumDays
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>scoluccia</ADDEDBY><SQLVERSION>2569</SQLVERSION><RMTRACKLINK>78855</RMTRACKLINK><REASON>Force MaxForTransaction = null  for the itemsrule of a promotiontype = Lk_Promotiontype_Coupon</REASON><TABLENAMES>CNF_PromotionItemRule=PromotionItemRuleId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>Update CNF_PromotionItemRule set MaxForTransaction = Null where CNF_PromotionItemRule.PromotionItemId in
  	(SELECT PI.PromotionItemId from CNF_PromotionItem as PI with(nolock)
       cross apply(
                    SELECT PromotionId from CNF_Promotion with(nolock) where PromotionType = 2) as PR
       where PI.PromotionId = PR.PromotionId)</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>mevans</ADDEDBY><SQLVERSION>2568</SQLVERSION><RMTRACKLINK>78690</RMTRACKLINK><REASON>new field TaxPercentage</REASON><TABLENAMES>CNF_Tax2Package=Tax2PackageId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'TaxPercentage' AND
                Object_ID  = Object_ID(N'CNF_Tax2Package'))

BEGIN                
   alter table CNF_Tax2Package 
   add TaxPercentage DECIMAL(9, 6) NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>scoluccia</ADDEDBY><SQLVERSION>2567</SQLVERSION><RMTRACKLINK>79536</RMTRACKLINK><REASON>ADD IsHTMLabel to CNF_DataMask</REASON><TABLENAMES>CNF_DataMask=DataMaskId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'IsHTMLabel' AND
                Object_ID  = Object_ID(N'CNF_DATAMask'))
BEGIN
  ALTER TABLE CNF_DATAMask 
  ADD IsHTMLabel smallint NOT NULL DEFAULT(0)
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>2566</SQLVERSION><RMTRACKLINK>81061 </RMTRACKLINK><REASON>Searching the Ticket List is slow</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>if not exists(SELECT * 
FROM sys.indexes 
WHERE name='IDX_DATA_Ticket_FEncodeDate_ProductType' AND object_id = OBJECT_ID('dbo.DATA_Ticket'))
begin
	CREATE NONCLUSTERED INDEX [IDX_DATA_Ticket_FEncodeDate_ProductType] ON [dbo].[DATA_Ticket]
	(
		[FEncodeDate] ASC
	)
	INCLUDE ( 	[TicketId],
		[WorkstationId],
		[AccountId],
		[Serial],
		[VoidType],
		[PrintDateTime],
		[CurrencyId],
		[Price],
		[PrintedPrice],
		[ActiveTo],
		[MatrixCellId],
		[SaleItemId],
		[ProductType],
		[ReprintCounter]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>2565</SQLVERSION><RMTRACKLINK>81096 </RMTRACKLINK><REASON>Searching the Reservation List is slow</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>if not exists(SELECT * 
FROM sys.indexes 
WHERE name='IDX_DATA_Sale_SaleID_StatusCode' AND object_id = OBJECT_ID('dbo.DATA_Sale'))
begin
	CREATE NONCLUSTERED INDEX [IDX_DATA_Sale_SaleID_StatusCode] ON [dbo].[DATA_Sale]
	(
		[SaleId] ASC
	)
	INCLUDE ( 	
		[SaleType],
		[SaleAK],
		[SaleDate],
		[StatusCode],
		[Paid],
		[Approved],
		[Validated],
		[Encoded],
		[Completed],
		[Quantity],
		[TotalAmount],
		[Revenue],
		[PerformanceId],
		[PerformanceCount]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>if not exists(SELECT * 
FROM sys.indexes 
WHERE name='IDX_DATA_Account_AccountID_Display_Name' AND object_id = OBJECT_ID('dbo.DATA_Account'))
begin
	CREATE NONCLUSTERED INDEX [IDX_DATA_Account_AccountID_Display_Name] ON [dbo].[DATA_Account]
	(
		[AccountId] ASC
	)
	INCLUDE ( 	[AccountAK],
		[DisplayName],
		[EmailAddress1]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>2564</SQLVERSION><RMTRACKLINK>81060 </RMTRACKLINK><REASON>Remove initial query when clicking on Account List tile</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>if not exists(SELECT * 
FROM sys.indexes 
WHERE name='IDX_DATA_Account_AccountType_Enabled' AND object_id = OBJECT_ID('dbo.DATA_Account'))
begin
	CREATE NONCLUSTERED INDEX [IDX_DATA_Account_AccountType_Enabled] ON [dbo].[DATA_Account]
	(
		[AccountType] ASC,
		[Enabled] ASC
	)
	INCLUDE ( 	[AccountId],
		[AccountAK],
		[DmgCategoryId],
		[DisplayName],
		[Address1],
		[ZipCode],
		[City],
		[State],
		[Country],
		[HomePhone],
		[BusinessPhone],
		[MobilePhone],
		[EmailAddress1],
		[InsDateTime],
		[UpdDateTime],
		[ExternalCode1],
		[DisplayField2],
		[DisplayField1],
		[Membership],
		[ExpirationDate],
		[CompanyName]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
end</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>2563</SQLVERSION><RMTRACKLINK>79251</RMTRACKLINK><REASON>Added new field to DATA_Transaction: FlexContractStatus</REASON><TABLENAMES>DATA_Transaction=TransactionId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'FlexContractStatus' AND
                Object_ID  = Object_ID(N'DATA_Transaction'))
BEGIN
  ALTER TABLE DATA_Transaction 
  ADD FlexContractStatus SmallInt NULL
END
</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fesposito</ADDEDBY><SQLVERSION>2562</SQLVERSION><RMTRACKLINK>78951</RMTRACKLINK><REASON></REASON><TABLENAMES>DATA_SaleItem=SaleItemId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'ShareableEntitlements' AND
                Object_ID  = Object_ID(N'DATA_SaleItem'))
BEGIN
  ALTER TABLE DATA_SaleItem 
  ADD ShareableEntitlements SmallInt NULL
END
</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dchen</ADDEDBY><SQLVERSION>2561</SQLVERSION><RMTRACKLINK>79534</RMTRACKLINK><REASON>Script to populate the CNF_MatrixCell_Renew by breaking the CNF_MatrixCellInfo.QuickRenewIds information.</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES 
            WHERE TABLE_SCHEMA = 'dbo' 
                  AND  TABLE_NAME = 'CNF_MatrixCell_Renew'))
BEGIN
	declare @Results table(ordinal int, id int, value varchar(max))

	declare @id int,
			@String varchar(max),
			@Delimiter varchar(1)

	IF EXISTS(	SELECT * FROM INFORMATION_SCHEMA.TABLES 
				WHERE TABLE_SCHEMA = 'dbo' 
                 AND  TABLE_NAME = '#TMP_MATRIXCELLINFO') 
		DROP TABLE #TMP_MATRIXCELLINFO

	set rowcount 0
	select MatrixCellId, QuickRenewIds into #TMP_MATRIXCELLINFO from CNF_MatrixCellInfo where QuickRenewIds &lt;&gt; ''

	set rowcount 1
	select @id = MatrixCellId from #TMP_MATRIXCELLINFO

	while @@rowcount &lt;&gt; 0
	begin
		set rowcount 0
		set @String = (select QuickRenewIds from #TMP_MATRIXCELLINFO where MatrixCellId = @id)
		set @Delimiter = ','

		declare
			@TempString varchar(max) = @String,
			@CharIndex int = 0,
			@RowCount int = 0

			set @CharIndex = charindex(@Delimiter, @TempString)
			while @CharIndex != 0 begin
				if not exists (Select 1 from CNF_MatrixCell_Renew where MatrixCellId = @Id and RenewMatrixCellId = substring(@TempString, 0, @CharIndex))
				begin
					insert CNF_MatrixCell_Renew(MatrixCellId, RenewMatrixCellId, FlexAutoRenew) values (@Id, substring(@TempString, 0, @CharIndex), 0)
				end
				set @TempString = substring(@TempString, @CharIndex + 1, len(@TempString) - @CharIndex)
				set @CharIndex = charindex(@Delimiter, @TempString)
			end

			if @TempString != '' begin
				if not exists (Select 1 from CNF_MatrixCell_Renew where MatrixCellId = @Id and RenewMatrixCellId = @TempString)
				begin
	    			insert CNF_MatrixCell_Renew(MatrixCellId, RenewMatrixCellId, FlexAutoRenew) values (@Id, @TempString, 0)
				end
			end

		delete #TMP_MATRIXCELLINFO where MatrixCellId = @id

		set rowcount 1
		select @id = MatrixCellid from #TMP_MATRIXCELLINFO
	end
	set rowcount 0
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fesposito</ADDEDBY><SQLVERSION>2560</SQLVERSION><RMTRACKLINK>78951 </RMTRACKLINK><REASON>New table SaleItemRedeem</REASON><TABLENAMES>DATA_SaleItemRedeem=SaleItemRedeemId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'DATA_SaleItemRedeem'))
                    
BEGIN
Create table [DATA_SaleItemRedeem]
(
	[SaleItemRedeemId] Integer Identity(1,1) NOT NULL,
	[SaleItemId] Integer NOT NULL,
	[FromMediaId] Integer NOT NULL,
	[FromTicketId] Integer NOT NULL,
	[AttributesGUID] NVarchar(38) NOT NULL,
Primary Key ([SaleItemRedeemId])
) 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_SaleItemRedeem_SaleItemId')
BEGIN
  ALTER TABLE DATA_SaleItemRedeem
  ADD
  CONSTRAINT [FK_DATA_SaleItemRedeem_SaleItemId] FOREIGN KEY([SaleItemId]) REFERENCES [DATA_SaleItem] ([SaleItemId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_SaleItemRedeem_MediaId')
BEGIN
  ALTER TABLE DATA_SaleItemRedeem
  ADD
  CONSTRAINT [FK_DATA_SaleItemRedeem_MediaId] FOREIGN KEY([FromMediaId]) REFERENCES [DATA_Media] ([MediaId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_SaleItemRedeem_TicketId')
BEGIN
  ALTER TABLE DATA_SaleItemRedeem
  ADD
  CONSTRAINT [FK_DATA_SaleItemRedeem_TicketId] FOREIGN KEY([FromTicketId]) REFERENCES [DATA_Ticket] ([TicketId])
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dchen</ADDEDBY><SQLVERSION>2559</SQLVERSION><RMTRACKLINK>79869</RMTRACKLINK><REASON>Creating system promotion FLAT UPGRADE.
This promotion withhold the discount conceded in NO CHARGE UPGRADE and FLAT UPGRADE.
Needed to track in Chart Of Accounts.</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF not EXISTS (SELECT * FROM CNF_Promotion WHERE PromotionType = 101)
BEGIN
  INSERT INTO CNF_Promotion (Description ,Active, Code, PromotionType, CreatableOnPos, SupervisorOverride)
         VALUES ('Flat Upgrade Discount', 1, 'FLATUPGDISC', 101, 0, 0)

  INSERT INTO CNF_PromotionItem (PromotionId, Description, RuleType)
         VALUES (@@Identity, 'Flat Upgrade Discount', 'Advanced')

  INSERT INTO CNF_PromotionItemRule (PromotionItemId, AnyProduct, ApplyDiscountToAllItem)
         VALUES (@@Identity, 0, 0)
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>2558</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>3 history fields removed from ARC_Document</REASON><TABLENAMES>ARC_Document=DocumentId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_ARC_Document_Last_UserId_Log')
BEGIN
  ALTER TABLE ARC_Document
  DROP CONSTRAINT FK_ARC_Document_Last_UserId_Log
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_ARC_Document_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE ARC_Document
  DROP CONSTRAINT FK_ARC_Document_Last_WorkstationId_Log
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'ARC_Document'))
BEGIN
  ALTER TABLE ARC_Document
  DROP COLUMN Last_UserId_Log, Last_WorkstationId_Log, Last_DateTime_Log
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2557</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.21.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2556</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2555</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2554</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2553</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2552</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2551</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2550</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2549</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2548</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2547</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2546</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2545</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2544</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2543</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2542</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2541</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2540</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2539</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2538</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2537</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2536</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2535</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2534</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2533</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2532</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2531</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2530</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2529</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2528</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2527</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2526</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2525</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2524</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2523</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2522</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2521</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2520</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2519</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2518</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2517</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2516</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2515</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2514</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2513</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2512</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2511</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2510</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2509</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2508</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2507</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2506</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2505</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2504</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2503</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2502</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2501</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2500</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2499</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2498</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2497</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2496</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2495</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2494</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2493</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2492</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2491</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2490</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2489</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2488</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2487</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2486</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.21.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2485</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2484</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2483</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2482</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2481</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2480</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2479</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2478</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2477</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2476</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2475</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2474</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2473</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2472</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2471</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2470</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2469</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2468</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2467</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2466</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2465</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2464</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2463</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2462</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2461</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2460</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2459</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2458</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>adavanzo</ADDEDBY><SQLVERSION>2457</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.21.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>2456</SQLVERSION><RMTRACKLINK>79275</RMTRACKLINK><REASON>3 new fields added to DATA_Right:
1) Last_UserId_Log
2)Last_WorkstationId_Log
3)Last_DateTime_Log</REASON><TABLENAMES>DATA_Right=DataRightId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_Right'))
BEGIN
  Alter Table DATA_Right
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_Right_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_Right
  ADD CONSTRAINT [FK_DATA_Right_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_Right_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_Right 
  ADD CONSTRAINT [FK_DATA_Right_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>2455</SQLVERSION><RMTRACKLINK>72604</RMTRACKLINK><REASON>New column in CNF_Sytem: 'XMLHistoryLogEnabled'
Dropped 3 new history fields from CNF_DBInfo</REASON><TABLENAMES>CNF_System=SystemId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'XMLHistoryLogEnabled' AND
                Object_ID  = Object_ID(N'CNF_System'))
BEGIN
  Alter Table CNF_System
  Add XMLHistoryLogEnabled Smallint NOT NULL Default(1)
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DBInfo_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_DBInfo
  DROP CONSTRAINT FK_CNF_DBInfo_Last_UserId_Log
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DBInfo_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_DBInfo
  DROP CONSTRAINT FK_CNF_DBInfo_Last_WorkstationId_Log
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_DBInfo'))
BEGIN
  ALTER TABLE CNF_DBInfo
  DROP COLUMN Last_UserId_Log, Last_WorkstationId_Log, Last_DateTime_Log
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fdipalma</ADDEDBY><SQLVERSION>2454</SQLVERSION><RMTRACKLINK>76282</RMTRACKLINK><REASON>Added DeviceFamilyType on DATA_PaymentHotel</REASON><TABLENAMES>DATA_PaymentHotel=PaymentHotelId</TABLENAMES><SQLSCRIPTLIST><SCRIPT> IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'DeviceFamilyType' AND
                Object_ID  = Object_ID(N'DATA_PaymentHotel'))
BEGIN
  Alter Table DATA_PaymentHotel
  Add DeviceFamilyType SmallInt NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>2453</SQLVERSION><RMTRACKLINK>78925</RMTRACKLINK><REASON>Added nonclustered index for TransactionId in DATA_History_Override</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name='IDX_DATA_History_Override_TransactionId' AND object_id = OBJECT_ID('DATA_History_Override'))
begin
	CREATE NONCLUSTERED INDEX [IDX_DATA_History_Override_TransactionId] ON [dbo].[DATA_History_Override]
	(
		[TransactionId] ASC
	)
	WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
end</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>2452</SQLVERSION><RMTRACKLINK>79422</RMTRACKLINK><REASON>To improve performance Add the following indexes</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name='IDX_DATA_Sale_StatusCode_SaleAK' AND object_id = OBJECT_ID('DATA_Sale'))
begin
	CREATE NONCLUSTERED INDEX [IDX_DATA_Sale_StatusCode_SaleAK] ON [dbo].[DATA_Sale]
	(
		[StatusCode] ASC,
		[SaleAK] ASC
	)
	WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
end</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name='IDX_DATA_MediaIdentifier_AccountID' AND object_id = OBJECT_ID('DATA_MediaIdentifier'))
begin
	CREATE NONCLUSTERED INDEX [IDX_DATA_MediaIdentifier_AccountID] ON [dbo].[DATA_MediaIdentifier]
	(
		[AccountId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>pchen</ADDEDBY><SQLVERSION>2451</SQLVERSION><RMTRACKLINK>72822</RMTRACKLINK><REASON>Append a new field into DATA_PaymentCard.</REASON><TABLENAMES>DATA_PaymentCard=PaymentId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'MetaToken' AND
                Object_ID  = Object_ID(N'DATA_PaymentCard'))
BEGIN
  Alter Table DATA_PaymentCard
  Add MetaToken Nvarchar(30) NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fulviodipalma</ADDEDBY><SQLVERSION>2450</SQLVERSION><RMTRACKLINK>79345</RMTRACKLINK><REASON>The payment code max length is 10, we need it to be longer</REASON><TABLENAMES>CNF_PaymentMethod=PaymentMethodId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
               WHERE Name = N'Code' AND
                     Object_ID  = Object_ID(N'CNF_PaymentMethod'))
BEGIN
  ALTER TABLE CNF_PaymentMethod ALTER COLUMN Code NVARCHAR (20) NULL;
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>2449</SQLVERSION><RMTRACKLINK>78927</RMTRACKLINK><REASON>Dropped and re-added DATA_History_Override table with new column: InsDateTime</REASON><TABLENAMES>DATA_History_Override=HistoryOverrideId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS ( SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND  TABLE_NAME = 'DATA_History_Override' )

BEGIN
   DROP TABLE DATA_History_Override
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'DATA_History_Override'))
                    
BEGIN
Create table [DATA_History_Override]
(
	[HistoryOverrideId] Integer Identity(1,1) NOT NULL,
	[WorkstationId] Integer NOT NULL,
	[UserId] Integer NOT NULL,
	[SupervisorUserId] Integer NOT NULL,
	[OverrideType] Smallint NOT NULL,
	[TransactionId] Integer NULL,
        [InsDateTime] Datetime NOT NULL,
Primary Key ([HistoryOverrideId])
) 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_History_Override_WorkstationId')
BEGIN
  ALTER TABLE DATA_History_Override
  ADD
  CONSTRAINT [FK_DATA_History_Override_WorkstationId] FOREIGN KEY([WorkstationId]) REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_History_Override_UserId')
BEGIN
  ALTER TABLE DATA_History_Override
  ADD
  CONSTRAINT [FK_DATA_History_Override_UserId] FOREIGN KEY([UserId]) REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_History_Override_SupervisorUserId')
BEGIN
  ALTER TABLE DATA_History_Override
  ADD
  CONSTRAINT [FK_DATA_History_Override_SupervisorUserId] FOREIGN KEY([SupervisorUserId]) REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_History_Override_TransactionId')
BEGIN
  ALTER TABLE DATA_History_Override
  ADD
  CONSTRAINT [FK_DATA_History_Override_TransactionId] FOREIGN KEY([TransactionId]) REFERENCES [DATA_Transaction] ([TransactionId])
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>2448</SQLVERSION><RMTRACKLINK>79275</RMTRACKLINK><REASON>3 new fields added:
1) Last_UserId_Log
2)Last_WorkstationId_Log
3)Last_DateTime_Log</REASON><TABLENAMES>DATA_Sale=SaleId
DATA_Transaction=TransactionId
INV_ALU=ProductId
INV_Department=DepartmentId
INV_Item=ProductId
INV_ItemStock=StockDetailId
INV_Movement=MovementId
INV_PODetail=PODetailId
INV_PurchaseOrder=PurchaseOrderId
INV_Supplier=SupplierId
INV_Transfer=TransferId
INV_UnitOfMeasure=UnitOfMeasureId
INV_WareHouse=WareHouseId
RES_CNF_Event=EventId
RES_CNF_MatrixCell=MatrixCellId
RES_CNF_Performance=PerformanceId
RES_CNF_Requirement=RequirementId
RES_CNF_RequirementGroup=RequirementGroupId
RES_CNF_RequirementTemplate=RequirementTemplateId
RES_CNF_RequirementTemplateItem=RequirementTemplateItemId
RES_CNF_RequirementTemplateSet=RequirementTemplateSetId
RES_CNF_RequirementType=RequirementTypeId
RES_CNF_Resource=ResourceId
RES_CNF_ResourceContract=ContractId
RES_CNF_ResourcePriority=ResourcePriorityId
RES_CNF_ResourceRequirement=ResourceRequirementId
RES_CNF_ResourceRequirementAllowed=ResourceRequirementAllowedId
RES_CNF_ResourceType=ResourceTypeId
RES_CNF_ResourceType_Requirement=ResourceTypeRequirementId
RES_CNF_ScheduleTypeAllowed=ScheduleTypeAllowedId
RR_CNF_Product=RevenueRecognitionProductId
RR_CNF_RevenueRecognitionRule=RevenueRecognitionRuleId
RR_CNF_RevenueRecognitionRuleSchedule=RevenueRecognitionRuleScheduleId
SEAT_CNF_SpaceStructureSeat=SpaceStructureSeatId
STOCK_CNF_Product=MatrixCellId
STOCK_CNF_ProductBarcodes=ProductBarcodeIf
STOCK_CNF_ProductCategory=CategoryId
STOCK_CNF_ProductCombo=ComboId
STOCK_CNF_ProductComboChoice=ComboChoiceId
STOCK_CNF_ProductUm=ProductUmId
STOCK_CNF_Um=UmId
STOCK_CNF_Warehouse=WarehouseId
STOCK_CNF_WarehouseAssign=WarehouseAssignId
RES_Data_Transaction=ResDataTransactionId
RES_ResourceCalendar=ResourceCalendarId
RES_ResourceCalendar_TimeFrame=ResourceCalendarTimeFrameId
RES_Schedule=ScheduleId
RES_ScheduleDetail=ScheduleDetailId
RES_ScheduleType=ScheduleTypeId
</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_Sale'))
BEGIN
  Alter Table DATA_Sale
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_Sale_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_Sale
  ADD CONSTRAINT [FK_DATA_Sale_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_Sale_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_Sale 
  ADD CONSTRAINT [FK_DATA_Sale_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_Transaction'))
BEGIN
  Alter Table DATA_Transaction
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_Transaction_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_Transaction
  ADD CONSTRAINT [FK_DATA_Transaction_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_Transaction_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_Transaction 
  ADD CONSTRAINT [FK_DATA_Transaction_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'INV_ALU'))
BEGIN
  Alter Table INV_ALU
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_INV_ALU_Last_UserId_Log')
BEGIN
  ALTER TABLE INV_ALU
  ADD CONSTRAINT [FK_INV_ALU_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_INV_ALU_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE INV_ALU 
  ADD CONSTRAINT [FK_INV_ALU_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'INV_Department'))
BEGIN
  Alter Table INV_Department
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_INV_Department_Last_UserId_Log')
BEGIN
  ALTER TABLE INV_Department
  ADD CONSTRAINT [FK_INV_Department_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_INV_Department_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE INV_Department 
  ADD CONSTRAINT [FK_INV_Department_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'INV_Item'))
BEGIN
  Alter Table INV_Item
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_INV_Item_Last_UserId_Log')
BEGIN
  ALTER TABLE INV_Item
  ADD CONSTRAINT [FK_INV_Item_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_INV_Item_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE INV_Item 
  ADD CONSTRAINT [FK_INV_Item_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'INV_ItemStock'))
BEGIN
  Alter Table INV_ItemStock
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_INV_ItemStock_Last_UserId_Log')
BEGIN
  ALTER TABLE INV_ItemStock
  ADD CONSTRAINT [FK_INV_ItemStock_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_INV_ItemStock_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE INV_ItemStock 
  ADD CONSTRAINT [FK_INV_ItemStock_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'INV_Movement'))
BEGIN
  Alter Table INV_Movement
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_INV_Movement_Last_UserId_Log')
BEGIN
  ALTER TABLE INV_Movement
  ADD CONSTRAINT [FK_INV_Movement_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_INV_Movement_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE INV_Movement 
  ADD CONSTRAINT [FK_INV_Movement_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'INV_PODetail'))
BEGIN
  Alter Table INV_PODetail
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_INV_PODetail_Last_UserId_Log')
BEGIN
  ALTER TABLE INV_PODetail
  ADD CONSTRAINT [FK_INV_PODetail_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_INV_PODetail_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE INV_PODetail 
  ADD CONSTRAINT [FK_INV_PODetail_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'INV_PurchaseOrder'))
BEGIN
  Alter Table INV_PurchaseOrder
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_INV_PurchaseOrder_Last_UserId_Log')
BEGIN
  ALTER TABLE INV_PurchaseOrder
  ADD CONSTRAINT [FK_INV_PurchaseOrder_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_INV_PurchaseOrder_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE INV_PurchaseOrder 
  ADD CONSTRAINT [FK_INV_PurchaseOrder_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'INV_Supplier'))
BEGIN
  Alter Table INV_Supplier
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_INV_Supplier_Last_UserId_Log')
BEGIN
  ALTER TABLE INV_Supplier
  ADD CONSTRAINT [FK_INV_Supplier_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_INV_Supplier_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE INV_Supplier 
  ADD CONSTRAINT [FK_INV_Supplier_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'INV_Transfer'))
BEGIN
  Alter Table INV_Transfer
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_INV_Transfer_Last_UserId_Log')
BEGIN
  ALTER TABLE INV_Transfer
  ADD CONSTRAINT [FK_INV_Transfer_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_INV_Transfer_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE INV_Transfer 
  ADD CONSTRAINT [FK_INV_Transfer_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'INV_UnitOfMeasure'))
BEGIN
  Alter Table INV_UnitOfMeasure
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_INV_UnitOfMeasure_Last_UserId_Log')
BEGIN
  ALTER TABLE INV_UnitOfMeasure
  ADD CONSTRAINT [FK_INV_UnitOfMeasure_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_INV_UnitOfMeasure_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE INV_UnitOfMeasure 
  ADD CONSTRAINT [FK_INV_UnitOfMeasure_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'INV_WareHouse'))
BEGIN
  Alter Table INV_WareHouse
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_INV_WareHouse_Last_UserId_Log')
BEGIN
  ALTER TABLE INV_WareHouse
  ADD CONSTRAINT [FK_INV_WareHouse_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_INV_WareHouse_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE INV_WareHouse 
  ADD CONSTRAINT [FK_INV_WareHouse_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'RES_CNF_Event'))
BEGIN
  Alter Table RES_CNF_Event
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_RES_CNF_Event_Last_UserId_Log')
BEGIN
  ALTER TABLE RES_CNF_Event
  ADD CONSTRAINT [FK_RES_CNF_Event_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_RES_CNF_Event_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE RES_CNF_Event 
  ADD CONSTRAINT [FK_RES_CNF_Event_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'RES_CNF_MatrixCell'))
BEGIN
  Alter Table RES_CNF_MatrixCell
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_RES_CNF_MatrixCell_Last_UserId_Log')
BEGIN
  ALTER TABLE RES_CNF_MatrixCell
  ADD CONSTRAINT [FK_RES_CNF_MatrixCell_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_RES_CNF_MatrixCell_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE RES_CNF_MatrixCell 
  ADD CONSTRAINT [FK_RES_CNF_MatrixCell_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'RES_CNF_Performance'))
BEGIN
  Alter Table RES_CNF_Performance
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_RES_CNF_Performance_Last_UserId_Log')
BEGIN
  ALTER TABLE RES_CNF_Performance
  ADD CONSTRAINT [FK_RES_CNF_Performance_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_RES_CNF_Performance_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE RES_CNF_Performance 
  ADD CONSTRAINT [FK_RES_CNF_Performance_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'RES_CNF_Requirement'))
BEGIN
  Alter Table RES_CNF_Requirement
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_RES_CNF_Requirement_Last_UserId_Log')
BEGIN
  ALTER TABLE RES_CNF_Requirement
  ADD CONSTRAINT [FK_RES_CNF_Requirement_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_RES_CNF_Requirement_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE RES_CNF_Requirement 
  ADD CONSTRAINT [FK_RES_CNF_Requirement_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'RES_CNF_RequirementGroup'))
BEGIN
  Alter Table RES_CNF_RequirementGroup
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_RES_CNF_RequirementGroup_Last_UserId_Log')
BEGIN
  ALTER TABLE RES_CNF_RequirementGroup
  ADD CONSTRAINT [FK_RES_CNF_RequirementGroup_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_RES_CNF_RequirementGroup_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE RES_CNF_RequirementGroup 
  ADD CONSTRAINT [FK_RES_CNF_RequirementGroup_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'RES_CNF_RequirementTemplate'))
BEGIN
  Alter Table RES_CNF_RequirementTemplate
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_RES_CNF_RequirementTemplate_Last_UserId_Log')
BEGIN
  ALTER TABLE RES_CNF_RequirementTemplate
  ADD CONSTRAINT [FK_RES_CNF_RequirementTemplate_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_RES_CNF_RequirementTemplate_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE RES_CNF_RequirementTemplate 
  ADD CONSTRAINT [FK_RES_CNF_RequirementTemplate_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'RES_CNF_RequirementTemplateItem'))
BEGIN
  Alter Table RES_CNF_RequirementTemplateItem
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_RES_CNF_RequirementTemplateItem_Last_UserId_Log')
BEGIN
  ALTER TABLE RES_CNF_RequirementTemplateItem
  ADD CONSTRAINT [FK_RES_CNF_RequirementTemplateItem_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_RES_CNF_RequirementTemplateItem_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE RES_CNF_RequirementTemplateItem 
  ADD CONSTRAINT [FK_RES_CNF_RequirementTemplateItem_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'RES_CNF_RequirementTemplateSet'))
BEGIN
  Alter Table RES_CNF_RequirementTemplateSet
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_RES_CNF_RequirementTemplateSet_Last_UserId_Log')
BEGIN
  ALTER TABLE RES_CNF_RequirementTemplateSet
  ADD CONSTRAINT [FK_RES_CNF_RequirementTemplateSet_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_RES_CNF_RequirementTemplateSet_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE RES_CNF_RequirementTemplateSet 
  ADD CONSTRAINT [FK_RES_CNF_RequirementTemplateSet_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'RES_CNF_RequirementType'))
BEGIN
  Alter Table RES_CNF_RequirementType
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_RES_CNF_RequirementType_Last_UserId_Log')
BEGIN
  ALTER TABLE RES_CNF_RequirementType
  ADD CONSTRAINT [FK_RES_CNF_RequirementType_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_RES_CNF_RequirementType_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE RES_CNF_RequirementType 
  ADD CONSTRAINT [FK_RES_CNF_RequirementType_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'RES_CNF_Resource'))
BEGIN
  Alter Table RES_CNF_Resource
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_RES_CNF_Resource_Last_UserId_Log')
BEGIN
  ALTER TABLE RES_CNF_Resource
  ADD CONSTRAINT [FK_RES_CNF_Resource_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_RES_CNF_Resource_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE RES_CNF_Resource 
  ADD CONSTRAINT [FK_RES_CNF_Resource_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'RES_CNF_ResourceContract'))
BEGIN
  Alter Table RES_CNF_ResourceContract
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_RES_CNF_ResourceContract_Last_UserId_Log')
BEGIN
  ALTER TABLE RES_CNF_ResourceContract
  ADD CONSTRAINT [FK_RES_CNF_ResourceContract_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_RES_CNF_ResourceContract_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE RES_CNF_ResourceContract 
  ADD CONSTRAINT [FK_RES_CNF_ResourceContract_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'RES_CNF_ResourcePriority'))
BEGIN
  Alter Table RES_CNF_ResourcePriority
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_RES_CNF_ResourcePriority_Last_UserId_Log')
BEGIN
  ALTER TABLE RES_CNF_ResourcePriority
  ADD CONSTRAINT [FK_RES_CNF_ResourcePriority_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_RES_CNF_ResourcePriority_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE RES_CNF_ResourcePriority 
  ADD CONSTRAINT [FK_RES_CNF_ResourcePriority_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'RES_CNF_ResourceRequirement'))
BEGIN
  Alter Table RES_CNF_ResourceRequirement
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_RES_CNF_ResourceRequirement_Last_UserId_Log')
BEGIN
  ALTER TABLE RES_CNF_ResourceRequirement
  ADD CONSTRAINT [FK_RES_CNF_ResourceRequirement_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_RES_CNF_ResourceRequirement_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE RES_CNF_ResourceRequirement 
  ADD CONSTRAINT [FK_RES_CNF_ResourceRequirement_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'RES_CNF_ResourceRequirementAllowed'))
BEGIN
  Alter Table RES_CNF_ResourceRequirementAllowed
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_RES_CNF_ResourceRequirementAllowed_Last_UserId_Log')
BEGIN
  ALTER TABLE RES_CNF_ResourceRequirementAllowed
  ADD CONSTRAINT [FK_RES_CNF_ResourceRequirementAllowed_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_RES_CNF_ResourceRequirementAllowed_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE RES_CNF_ResourceRequirementAllowed 
  ADD CONSTRAINT [FK_RES_CNF_ResourceRequirementAllowed_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'RES_CNF_ResourceType'))
BEGIN
  Alter Table RES_CNF_ResourceType
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_RES_CNF_ResourceType_Last_UserId_Log')
BEGIN
  ALTER TABLE RES_CNF_ResourceType
  ADD CONSTRAINT [FK_RES_CNF_ResourceType_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_RES_CNF_ResourceType_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE RES_CNF_ResourceType 
  ADD CONSTRAINT [FK_RES_CNF_ResourceType_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'RES_CNF_ResourceType_Requirement'))
BEGIN
  Alter Table RES_CNF_ResourceType_Requirement
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_RES_CNF_ResourceType_Requirement_Last_UserId_Log')
BEGIN
  ALTER TABLE RES_CNF_ResourceType_Requirement
  ADD CONSTRAINT [FK_RES_CNF_ResourceType_Requirement_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_RES_CNF_ResourceType_Requirement_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE RES_CNF_ResourceType_Requirement 
  ADD CONSTRAINT [FK_RES_CNF_ResourceType_Requirement_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'RES_CNF_ScheduleTypeAllowed'))
BEGIN
  Alter Table RES_CNF_ScheduleTypeAllowed
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_RES_CNF_ScheduleTypeAllowed_Last_UserId_Log')
BEGIN
  ALTER TABLE RES_CNF_ScheduleTypeAllowed
  ADD CONSTRAINT [FK_RES_CNF_ScheduleTypeAllowed_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_RES_CNF_ScheduleTypeAllowed_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE RES_CNF_ScheduleTypeAllowed 
  ADD CONSTRAINT [FK_RES_CNF_ScheduleTypeAllowed_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'RR_CNF_Product'))
BEGIN
  Alter Table RR_CNF_Product
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_RR_CNF_Product_Last_UserId_Log')
BEGIN
  ALTER TABLE RR_CNF_Product
  ADD CONSTRAINT [FK_RR_CNF_Product_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_RR_CNF_Product_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE RR_CNF_Product 
  ADD CONSTRAINT [FK_RR_CNF_Product_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'RR_CNF_RevenueRecognitionRule'))
BEGIN
  Alter Table RR_CNF_RevenueRecognitionRule
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_RR_CNF_RevenueRecognitionRule_Last_UserId_Log')
BEGIN
  ALTER TABLE RR_CNF_RevenueRecognitionRule
  ADD CONSTRAINT [FK_RR_CNF_RevenueRecognitionRule_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_RR_CNF_RevenueRecognitionRule_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE RR_CNF_RevenueRecognitionRule 
  ADD CONSTRAINT [FK_RR_CNF_RevenueRecognitionRule_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'RR_CNF_RevenueRecognitionRuleSchedule'))
BEGIN
  Alter Table RR_CNF_RevenueRecognitionRuleSchedule
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_RR_CNF_RevenueRecognitionRuleSchedule_Last_UserId_Log')
BEGIN
  ALTER TABLE RR_CNF_RevenueRecognitionRuleSchedule
  ADD CONSTRAINT [FK_RR_CNF_RevenueRecognitionRuleSchedule_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_RR_CNF_RevenueRecognitionRuleSchedule_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE RR_CNF_RevenueRecognitionRuleSchedule 
  ADD CONSTRAINT [FK_RR_CNF_RevenueRecognitionRuleSchedule_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'SEAT_CNF_SpaceStructureSeat'))
BEGIN
  Alter Table SEAT_CNF_SpaceStructureSeat
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_SEAT_CNF_SpaceStructureSeat_Last_UserId_Log')
BEGIN
  ALTER TABLE SEAT_CNF_SpaceStructureSeat
  ADD CONSTRAINT [FK_SEAT_CNF_SpaceStructureSeat_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_SEAT_CNF_SpaceStructureSeat_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE SEAT_CNF_SpaceStructureSeat 
  ADD CONSTRAINT [FK_SEAT_CNF_SpaceStructureSeat_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'STOCK_CNF_Product'))
BEGIN
  Alter Table STOCK_CNF_Product
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_STOCK_CNF_Product_Last_UserId_Log')
BEGIN
  ALTER TABLE STOCK_CNF_Product
  ADD CONSTRAINT [FK_STOCK_CNF_Product_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_STOCK_CNF_Product_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE STOCK_CNF_Product 
  ADD CONSTRAINT [FK_STOCK_CNF_Product_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'STOCK_CNF_ProductBarcodes'))
BEGIN
  Alter Table STOCK_CNF_ProductBarcodes
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_STOCK_CNF_ProductBarcodes_Last_UserId_Log')
BEGIN
  ALTER TABLE STOCK_CNF_ProductBarcodes
  ADD CONSTRAINT [FK_STOCK_CNF_ProductBarcodes_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_STOCK_CNF_ProductBarcodes_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE STOCK_CNF_ProductBarcodes 
  ADD CONSTRAINT [FK_STOCK_CNF_ProductBarcodes_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'STOCK_CNF_ProductCategory'))
BEGIN
  Alter Table STOCK_CNF_ProductCategory
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_STOCK_CNF_ProductCategory_Last_UserId_Log')
BEGIN
  ALTER TABLE STOCK_CNF_ProductCategory
  ADD CONSTRAINT [FK_STOCK_CNF_ProductCategory_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_STOCK_CNF_ProductCategory_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE STOCK_CNF_ProductCategory 
  ADD CONSTRAINT [FK_STOCK_CNF_ProductCategory_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'STOCK_CNF_ProductCombo'))
BEGIN
  Alter Table STOCK_CNF_ProductCombo
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_STOCK_CNF_ProductCombo_Last_UserId_Log')
BEGIN
  ALTER TABLE STOCK_CNF_ProductCombo
  ADD CONSTRAINT [FK_STOCK_CNF_ProductCombo_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_STOCK_CNF_ProductCombo_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE STOCK_CNF_ProductCombo 
  ADD CONSTRAINT [FK_STOCK_CNF_ProductCombo_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'STOCK_CNF_ProductComboChoice'))
BEGIN
  Alter Table STOCK_CNF_ProductComboChoice
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_STOCK_CNF_ProductComboChoice_Last_UserId_Log')
BEGIN
  ALTER TABLE STOCK_CNF_ProductComboChoice
  ADD CONSTRAINT [FK_STOCK_CNF_ProductComboChoice_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_STOCK_CNF_ProductComboChoice_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE STOCK_CNF_ProductComboChoice 
  ADD CONSTRAINT [FK_STOCK_CNF_ProductComboChoice_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'STOCK_CNF_ProductUm'))
BEGIN
  Alter Table STOCK_CNF_ProductUm
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_STOCK_CNF_ProductUm_Last_UserId_Log')
BEGIN
  ALTER TABLE STOCK_CNF_ProductUm
  ADD CONSTRAINT [FK_STOCK_CNF_ProductUm_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_STOCK_CNF_ProductUm_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE STOCK_CNF_ProductUm 
  ADD CONSTRAINT [FK_STOCK_CNF_ProductUm_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'STOCK_CNF_Um'))
BEGIN
  Alter Table STOCK_CNF_Um
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_STOCK_CNF_Um_Last_UserId_Log')
BEGIN
  ALTER TABLE STOCK_CNF_Um
  ADD CONSTRAINT [FK_STOCK_CNF_Um_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_STOCK_CNF_Um_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE STOCK_CNF_Um 
  ADD CONSTRAINT [FK_STOCK_CNF_Um_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'STOCK_CNF_Warehouse'))
BEGIN
  Alter Table STOCK_CNF_Warehouse
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_STOCK_CNF_Warehouse_Last_UserId_Log')
BEGIN
  ALTER TABLE STOCK_CNF_Warehouse
  ADD CONSTRAINT [FK_STOCK_CNF_Warehouse_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_STOCK_CNF_Warehouse_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE STOCK_CNF_Warehouse 
  ADD CONSTRAINT [FK_STOCK_CNF_Warehouse_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'STOCK_CNF_WarehouseAssign'))
BEGIN
  Alter Table STOCK_CNF_WarehouseAssign
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_STOCK_CNF_WarehouseAssign_Last_UserId_Log')
BEGIN
  ALTER TABLE STOCK_CNF_WarehouseAssign
  ADD CONSTRAINT [FK_STOCK_CNF_WarehouseAssign_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_STOCK_CNF_WarehouseAssign_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE STOCK_CNF_WarehouseAssign 
  ADD CONSTRAINT [FK_STOCK_CNF_WarehouseAssign_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'RES_Data_Transaction'))
BEGIN
  Alter Table RES_Data_Transaction
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_RES_Data_Transaction_Last_UserId_Log')
BEGIN
  ALTER TABLE RES_Data_Transaction
  ADD CONSTRAINT [FK_RES_Data_Transaction_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_RES_Data_Transaction_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE RES_Data_Transaction 
  ADD CONSTRAINT [FK_RES_Data_Transaction_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'RES_ResourceCalendar'))
BEGIN
  Alter Table RES_ResourceCalendar
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_RES_ResourceCalendar_Last_UserId_Log')
BEGIN
  ALTER TABLE RES_ResourceCalendar
  ADD CONSTRAINT [FK_RES_ResourceCalendar_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_RES_ResourceCalendar_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE RES_ResourceCalendar 
  ADD CONSTRAINT [FK_RES_ResourceCalendar_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'RES_ResourceCalendar_TimeFrame'))
BEGIN
  Alter Table RES_ResourceCalendar_TimeFrame
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_RES_ResourceCalendar_TimeFrame_Last_UserId_Log')
BEGIN
  ALTER TABLE RES_ResourceCalendar_TimeFrame
  ADD CONSTRAINT [FK_RES_ResourceCalendar_TimeFrame_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_RES_ResourceCalendar_TimeFrame_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE RES_ResourceCalendar_TimeFrame 
  ADD CONSTRAINT [FK_RES_ResourceCalendar_TimeFrame_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'RES_Schedule'))
BEGIN
  Alter Table RES_Schedule
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_RES_Schedule_Last_UserId_Log')
BEGIN
  ALTER TABLE RES_Schedule
  ADD CONSTRAINT [FK_RES_Schedule_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_RES_Schedule_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE RES_Schedule 
  ADD CONSTRAINT [FK_RES_Schedule_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'RES_ScheduleDetail'))
BEGIN
  Alter Table RES_ScheduleDetail
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_RES_ScheduleDetail_Last_UserId_Log')
BEGIN
  ALTER TABLE RES_ScheduleDetail
  ADD CONSTRAINT [FK_RES_ScheduleDetail_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_RES_ScheduleDetail_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE RES_ScheduleDetail 
  ADD CONSTRAINT [FK_RES_ScheduleDetail_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'RES_ScheduleType'))
BEGIN
  Alter Table RES_ScheduleType
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_RES_ScheduleType_Last_UserId_Log')
BEGIN
  ALTER TABLE RES_ScheduleType
  ADD CONSTRAINT [FK_RES_ScheduleType_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_RES_ScheduleType_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE RES_ScheduleType 
  ADD CONSTRAINT [FK_RES_ScheduleType_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>2447</SQLVERSION><RMTRACKLINK>79275</RMTRACKLINK><REASON>3 new fields added:
1) Last_UserId_Log
2)Last_WorkstationId_Log
3)Last_DateTime_Log</REASON><TABLENAMES>DATA_NFCIdentifier=IdentifierId
DATA_Notification2Entity=Notification2EntityId
DATA_Payment=PaymentId
DATA_PaymentAccount=PaymentAccountId
DATA_PaymentB2B=PaymentId
DATA_PaymentCard=PaymentId
DATA_PaymentCredit=PaymentId
DATA_PaymentFlex=PaymentId
DATA_PaymentFlex2SaleItem=PaymentFlex2SaleItemId
DATA_PaymentFlexInfo=PaymentFlexInfoId
DATA_PaymentHotel=PaymentHotelId
DATA_PaymentPlan=PaymentPlanId
DATA_PaymentPlan2Transaction=PaymentPlan2TransactionId
DATA_Reservation=SaleId
DATA_SaleCoupon=SaleCouponId
DATA_SaleItem=SaleItemId
DATA_SaleItem_Combo=SaleItemComboId
DATA_SaleItem2Account=SaleItem2AccountId
DATA_SaleItem2CostCenter=SaleItem2CostCenterId
DATA_SaleItem2Dmg=SaleItem2DmgId
DATA_SaleItem2Performance=SaleItem2PerformanceId
DATA_SaleItem2Ticket=SaleItem2TicketId
DATA_SaleItemRule=SaleItemRuleId
DATA_SaleItemTax=SaleItemTaxId
DATA_SalePromotionRule=SalePromotionRuleID
DATA_SaleTax=SaleTaxId
DATA_Seat=SeatId
DATA_Ticket=TicketId
DATA_Ticket2Media=Ticket2MediaId
DATA_Ticket2Performance=Ticket2PerformanceId
DATA_Ticket2TicketPackage=Ticket2TicketPackageId
DATA_TicketPackage=TicketPackageId
DATA_TicketPackage2Group=TicketPackage2GroupId
DATA_TicketUpgrade=TicketId
DATA_Transaction2Media=Transaction2MediaId
DATA_Transaction2Ticket=Transaction2TicketId
DATA_TransactionItem=ItemId
DATA_TransactionItem_Combo=TransactionItemComboId
DATA_TransactionItemRule=TransactionItemRuleId
DATA_TransactionTax=TransactionTaxId
DATA_Voucher=VoucherId
DATA_VoucherItem=VoucherItemId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_NFCIdentifier'))
BEGIN
  Alter Table DATA_NFCIdentifier
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_NFCIdentifier_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_NFCIdentifier
  ADD CONSTRAINT [FK_DATA_NFCIdentifier_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_NFCIdentifier_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_NFCIdentifier 
  ADD CONSTRAINT [FK_DATA_NFCIdentifier_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_Notification2Entity'))
BEGIN
  Alter Table DATA_Notification2Entity
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_Notification2Entity_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_Notification2Entity
  ADD CONSTRAINT [FK_DATA_Notification2Entity_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_Notification2Entity_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_Notification2Entity 
  ADD CONSTRAINT [FK_DATA_Notification2Entity_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_Payment'))
BEGIN
  Alter Table DATA_Payment
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_Payment_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_Payment
  ADD CONSTRAINT [FK_DATA_Payment_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_Payment_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_Payment 
  ADD CONSTRAINT [FK_DATA_Payment_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_PaymentAccount'))
BEGIN
  Alter Table DATA_PaymentAccount
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_PaymentAccount_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_PaymentAccount
  ADD CONSTRAINT [FK_DATA_PaymentAccount_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_PaymentAccount_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_PaymentAccount 
  ADD CONSTRAINT [FK_DATA_PaymentAccount_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_PaymentB2B'))
BEGIN
  Alter Table DATA_PaymentB2B
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_PaymentB2B_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_PaymentB2B
  ADD CONSTRAINT [FK_DATA_PaymentB2B_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_PaymentB2B_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_PaymentB2B 
  ADD CONSTRAINT [FK_DATA_PaymentB2B_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_PaymentCard'))
BEGIN
  Alter Table DATA_PaymentCard
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_PaymentCard_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_PaymentCard
  ADD CONSTRAINT [FK_DATA_PaymentCard_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_PaymentCard_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_PaymentCard 
  ADD CONSTRAINT [FK_DATA_PaymentCard_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_PaymentCredit'))
BEGIN
  Alter Table DATA_PaymentCredit
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_PaymentCredit_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_PaymentCredit
  ADD CONSTRAINT [FK_DATA_PaymentCredit_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_PaymentCredit_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_PaymentCredit 
  ADD CONSTRAINT [FK_DATA_PaymentCredit_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_PaymentFlex'))
BEGIN
  Alter Table DATA_PaymentFlex
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_PaymentFlex_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_PaymentFlex
  ADD CONSTRAINT [FK_DATA_PaymentFlex_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_PaymentFlex_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_PaymentFlex 
  ADD CONSTRAINT [FK_DATA_PaymentFlex_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_PaymentFlex2SaleItem'))
BEGIN
  Alter Table DATA_PaymentFlex2SaleItem
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_PaymentFlex2SaleItem_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_PaymentFlex2SaleItem
  ADD CONSTRAINT [FK_DATA_PaymentFlex2SaleItem_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_PaymentFlex2SaleItem_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_PaymentFlex2SaleItem 
  ADD CONSTRAINT [FK_DATA_PaymentFlex2SaleItem_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_PaymentFlexInfo'))
BEGIN
  Alter Table DATA_PaymentFlexInfo
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_PaymentFlexInfo_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_PaymentFlexInfo
  ADD CONSTRAINT [FK_DATA_PaymentFlexInfo_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_PaymentFlexInfo_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_PaymentFlexInfo 
  ADD CONSTRAINT [FK_DATA_PaymentFlexInfo_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_PaymentHotel'))
BEGIN
  Alter Table DATA_PaymentHotel
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_PaymentHotel_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_PaymentHotel
  ADD CONSTRAINT [FK_DATA_PaymentHotel_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_PaymentHotel_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_PaymentHotel 
  ADD CONSTRAINT [FK_DATA_PaymentHotel_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_PaymentPlan'))
BEGIN
  Alter Table DATA_PaymentPlan
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_PaymentPlan_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_PaymentPlan
  ADD CONSTRAINT [FK_DATA_PaymentPlan_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_PaymentPlan_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_PaymentPlan 
  ADD CONSTRAINT [FK_DATA_PaymentPlan_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_PaymentPlan2Transaction'))
BEGIN
  Alter Table DATA_PaymentPlan2Transaction
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_PaymentPlan2Transaction_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_PaymentPlan2Transaction
  ADD CONSTRAINT [FK_DATA_PaymentPlan2Transaction_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_PaymentPlan2Transaction_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_PaymentPlan2Transaction 
  ADD CONSTRAINT [FK_DATA_PaymentPlan2Transaction_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_Reservation'))
BEGIN
  Alter Table DATA_Reservation
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_Reservation_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_Reservation
  ADD CONSTRAINT [FK_DATA_Reservation_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_Reservation_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_Reservation 
  ADD CONSTRAINT [FK_DATA_Reservation_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_SaleCoupon'))
BEGIN
  Alter Table DATA_SaleCoupon
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_SaleCoupon_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_SaleCoupon
  ADD CONSTRAINT [FK_DATA_SaleCoupon_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_SaleCoupon_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_SaleCoupon 
  ADD CONSTRAINT [FK_DATA_SaleCoupon_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_SaleItem'))
BEGIN
  Alter Table DATA_SaleItem
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_SaleItem_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_SaleItem
  ADD CONSTRAINT [FK_DATA_SaleItem_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_SaleItem_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_SaleItem 
  ADD CONSTRAINT [FK_DATA_SaleItem_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_SaleItem_Combo'))
BEGIN
  Alter Table DATA_SaleItem_Combo
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_SaleItem_Combo_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_SaleItem_Combo
  ADD CONSTRAINT [FK_DATA_SaleItem_Combo_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_SaleItem_Combo_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_SaleItem_Combo 
  ADD CONSTRAINT [FK_DATA_SaleItem_Combo_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_SaleItem2Account'))
BEGIN
  Alter Table DATA_SaleItem2Account
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_SaleItem2Account_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_SaleItem2Account
  ADD CONSTRAINT [FK_DATA_SaleItem2Account_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_SaleItem2Account_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_SaleItem2Account 
  ADD CONSTRAINT [FK_DATA_SaleItem2Account_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_SaleItem2CostCenter'))
BEGIN
  Alter Table DATA_SaleItem2CostCenter
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_SaleItem2CostCenter_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_SaleItem2CostCenter
  ADD CONSTRAINT [FK_DATA_SaleItem2CostCenter_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_SaleItem2CostCenter_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_SaleItem2CostCenter 
  ADD CONSTRAINT [FK_DATA_SaleItem2CostCenter_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_SaleItem2Dmg'))
BEGIN
  Alter Table DATA_SaleItem2Dmg
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_SaleItem2Dmg_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_SaleItem2Dmg
  ADD CONSTRAINT [FK_DATA_SaleItem2Dmg_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_SaleItem2Dmg_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_SaleItem2Dmg 
  ADD CONSTRAINT [FK_DATA_SaleItem2Dmg_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_SaleItem2Performance'))
BEGIN
  Alter Table DATA_SaleItem2Performance
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_SaleItem2Performance_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_SaleItem2Performance
  ADD CONSTRAINT [FK_DATA_SaleItem2Performance_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_SaleItem2Performance_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_SaleItem2Performance 
  ADD CONSTRAINT [FK_DATA_SaleItem2Performance_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_SaleItem2Ticket'))
BEGIN
  Alter Table DATA_SaleItem2Ticket
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_SaleItem2Ticket_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_SaleItem2Ticket
  ADD CONSTRAINT [FK_DATA_SaleItem2Ticket_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_SaleItem2Ticket_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_SaleItem2Ticket 
  ADD CONSTRAINT [FK_DATA_SaleItem2Ticket_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_SaleItemRule'))
BEGIN
  Alter Table DATA_SaleItemRule
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_SaleItemRule_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_SaleItemRule
  ADD CONSTRAINT [FK_DATA_SaleItemRule_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_SaleItemRule_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_SaleItemRule 
  ADD CONSTRAINT [FK_DATA_SaleItemRule_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_SaleItemTax'))
BEGIN
  Alter Table DATA_SaleItemTax
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_SaleItemTax_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_SaleItemTax
  ADD CONSTRAINT [FK_DATA_SaleItemTax_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_SaleItemTax_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_SaleItemTax 
  ADD CONSTRAINT [FK_DATA_SaleItemTax_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_SalePromotionRule'))
BEGIN
  Alter Table DATA_SalePromotionRule
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_SalePromotionRule_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_SalePromotionRule
  ADD CONSTRAINT [FK_DATA_SalePromotionRule_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_SalePromotionRule_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_SalePromotionRule 
  ADD CONSTRAINT [FK_DATA_SalePromotionRule_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_SaleTax'))
BEGIN
  Alter Table DATA_SaleTax
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_SaleTax_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_SaleTax
  ADD CONSTRAINT [FK_DATA_SaleTax_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_SaleTax_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_SaleTax 
  ADD CONSTRAINT [FK_DATA_SaleTax_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_Seat'))
BEGIN
  Alter Table DATA_Seat
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_Seat_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_Seat
  ADD CONSTRAINT [FK_DATA_Seat_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_Seat_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_Seat 
  ADD CONSTRAINT [FK_DATA_Seat_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_Ticket'))
BEGIN
  Alter Table DATA_Ticket
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_Ticket_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_Ticket
  ADD CONSTRAINT [FK_DATA_Ticket_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_Ticket_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_Ticket 
  ADD CONSTRAINT [FK_DATA_Ticket_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_Ticket2Media'))
BEGIN
  Alter Table DATA_Ticket2Media
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_Ticket2Media_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_Ticket2Media
  ADD CONSTRAINT [FK_DATA_Ticket2Media_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_Ticket2Media_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_Ticket2Media 
  ADD CONSTRAINT [FK_DATA_Ticket2Media_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_Ticket2Performance'))
BEGIN
  Alter Table DATA_Ticket2Performance
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_Ticket2Performance_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_Ticket2Performance
  ADD CONSTRAINT [FK_DATA_Ticket2Performance_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_Ticket2Performance_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_Ticket2Performance 
  ADD CONSTRAINT [FK_DATA_Ticket2Performance_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_Ticket2TicketPackage'))
BEGIN
  Alter Table DATA_Ticket2TicketPackage
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_Ticket2TicketPackage_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_Ticket2TicketPackage
  ADD CONSTRAINT [FK_DATA_Ticket2TicketPackage_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_Ticket2TicketPackage_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_Ticket2TicketPackage 
  ADD CONSTRAINT [FK_DATA_Ticket2TicketPackage_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_TicketPackage'))
BEGIN
  Alter Table DATA_TicketPackage
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_TicketPackage_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_TicketPackage
  ADD CONSTRAINT [FK_DATA_TicketPackage_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_TicketPackage_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_TicketPackage 
  ADD CONSTRAINT [FK_DATA_TicketPackage_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_TicketPackage2Group'))
BEGIN
  Alter Table DATA_TicketPackage2Group
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_TicketPackage2Group_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_TicketPackage2Group
  ADD CONSTRAINT [FK_DATA_TicketPackage2Group_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_TicketPackage2Group_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_TicketPackage2Group 
  ADD CONSTRAINT [FK_DATA_TicketPackage2Group_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_TicketUpgrade'))
BEGIN
  Alter Table DATA_TicketUpgrade
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_TicketUpgrade_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_TicketUpgrade
  ADD CONSTRAINT [FK_DATA_TicketUpgrade_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_TicketUpgrade_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_TicketUpgrade 
  ADD CONSTRAINT [FK_DATA_TicketUpgrade_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_Transaction2Media'))
BEGIN
  Alter Table DATA_Transaction2Media
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_Transaction2Media_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_Transaction2Media
  ADD CONSTRAINT [FK_DATA_Transaction2Media_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_Transaction2Media_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_Transaction2Media 
  ADD CONSTRAINT [FK_DATA_Transaction2Media_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_Transaction2Ticket'))
BEGIN
  Alter Table DATA_Transaction2Ticket
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_Transaction2Ticket_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_Transaction2Ticket
  ADD CONSTRAINT [FK_DATA_Transaction2Ticket_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_Transaction2Ticket_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_Transaction2Ticket 
  ADD CONSTRAINT [FK_DATA_Transaction2Ticket_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_TransactionItem'))
BEGIN
  Alter Table DATA_TransactionItem
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_TransactionItem_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_TransactionItem
  ADD CONSTRAINT [FK_DATA_TransactionItem_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_TransactionItem_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_TransactionItem 
  ADD CONSTRAINT [FK_DATA_TransactionItem_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_TransactionItem_Combo'))
BEGIN
  Alter Table DATA_TransactionItem_Combo
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_TransactionItem_Combo_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_TransactionItem_Combo
  ADD CONSTRAINT [FK_DATA_TransactionItem_Combo_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_TransactionItem_Combo_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_TransactionItem_Combo 
  ADD CONSTRAINT [FK_DATA_TransactionItem_Combo_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_TransactionItemRule'))
BEGIN
  Alter Table DATA_TransactionItemRule
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_TransactionItemRule_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_TransactionItemRule
  ADD CONSTRAINT [FK_DATA_TransactionItemRule_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_TransactionItemRule_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_TransactionItemRule 
  ADD CONSTRAINT [FK_DATA_TransactionItemRule_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_TransactionTax'))
BEGIN
  Alter Table DATA_TransactionTax
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_TransactionTax_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_TransactionTax
  ADD CONSTRAINT [FK_DATA_TransactionTax_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_TransactionTax_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_TransactionTax 
  ADD CONSTRAINT [FK_DATA_TransactionTax_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_Voucher'))
BEGIN
  Alter Table DATA_Voucher
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_Voucher_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_Voucher
  ADD CONSTRAINT [FK_DATA_Voucher_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_Voucher_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_Voucher 
  ADD CONSTRAINT [FK_DATA_Voucher_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_VoucherItem'))
BEGIN
  Alter Table DATA_VoucherItem
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_VoucherItem_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_VoucherItem
  ADD CONSTRAINT [FK_DATA_VoucherItem_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_VoucherItem_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_VoucherItem 
  ADD CONSTRAINT [FK_DATA_VoucherItem_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>2446</SQLVERSION><RMTRACKLINK>79275</RMTRACKLINK><REASON>3 new fields added:
1) Last_UserId_Log
2)Last_WorkstationId_Log
3)Last_DateTime_Log</REASON><TABLENAMES>DATA_DmgData=DmgDataId
DATA_DmgData_Translate=DmgDataTranslateId
DATA_ExtendedInfo=ExtendedInfoId
DATA_ExtendedInfo2SaleItem=ExtendedInfo2SaleItemId
DATA_ExtendedInfo2Ticket=ExtendedInfo2TicketId
DATA_InvoiceData=InvoiceDataId
DATA_Ledger=LedgerId
DATA_Media=MediaId
DATA_Media2Performances=Media2PerformancesId
DATA_MediaIdentifier=MediaIdentifierId
DATA_MediaIdentifierBlackList=MediaBlackListId
DATA_MediaStoredValue=MediaStoredValueId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_DmgData'))
BEGIN
  Alter Table DATA_DmgData
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_DmgData_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_DmgData
  ADD CONSTRAINT [FK_DATA_DmgData_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_DmgData_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_DmgData 
  ADD CONSTRAINT [FK_DATA_DmgData_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_DmgData_Translate'))
BEGIN
  Alter Table DATA_DmgData_Translate
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_DmgData_Translate_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_DmgData_Translate
  ADD CONSTRAINT [FK_DATA_DmgData_Translate_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_DmgData_Translate_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_DmgData_Translate 
  ADD CONSTRAINT [FK_DATA_DmgData_Translate_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_ExtendedInfo'))
BEGIN
  Alter Table DATA_ExtendedInfo
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_ExtendedInfo_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_ExtendedInfo
  ADD CONSTRAINT [FK_DATA_ExtendedInfo_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_ExtendedInfo_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_ExtendedInfo 
  ADD CONSTRAINT [FK_DATA_ExtendedInfo_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_ExtendedInfo2SaleItem'))
BEGIN
  Alter Table DATA_ExtendedInfo2SaleItem
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_ExtendedInfo2SaleItem_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_ExtendedInfo2SaleItem
  ADD CONSTRAINT [FK_DATA_ExtendedInfo2SaleItem_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_ExtendedInfo2SaleItem_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_ExtendedInfo2SaleItem 
  ADD CONSTRAINT [FK_DATA_ExtendedInfo2SaleItem_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_ExtendedInfo2Ticket'))
BEGIN
  Alter Table DATA_ExtendedInfo2Ticket
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_ExtendedInfo2Ticket_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_ExtendedInfo2Ticket
  ADD CONSTRAINT [FK_DATA_ExtendedInfo2Ticket_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_ExtendedInfo2Ticket_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_ExtendedInfo2Ticket 
  ADD CONSTRAINT [FK_DATA_ExtendedInfo2Ticket_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_InvoiceData'))
BEGIN
  Alter Table DATA_InvoiceData
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_InvoiceData_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_InvoiceData
  ADD CONSTRAINT [FK_DATA_InvoiceData_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_InvoiceData_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_InvoiceData 
  ADD CONSTRAINT [FK_DATA_InvoiceData_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_Ledger'))
BEGIN
  Alter Table DATA_Ledger
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_Ledger_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_Ledger
  ADD CONSTRAINT [FK_DATA_Ledger_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_Ledger_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_Ledger 
  ADD CONSTRAINT [FK_DATA_Ledger_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_Media'))
BEGIN
  Alter Table DATA_Media
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_Media_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_Media
  ADD CONSTRAINT [FK_DATA_Media_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_Media_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_Media 
  ADD CONSTRAINT [FK_DATA_Media_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_Media2Performances'))
BEGIN
  Alter Table DATA_Media2Performances
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_Media2Performances_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_Media2Performances
  ADD CONSTRAINT [FK_DATA_Media2Performances_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_Media2Performances_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_Media2Performances 
  ADD CONSTRAINT [FK_DATA_Media2Performances_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_MediaIdentifier'))
BEGIN
  Alter Table DATA_MediaIdentifier
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_MediaIdentifier_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_MediaIdentifier
  ADD CONSTRAINT [FK_DATA_MediaIdentifier_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_MediaIdentifier_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_MediaIdentifier 
  ADD CONSTRAINT [FK_DATA_MediaIdentifier_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_MediaIdentifierBlackList'))
BEGIN
  Alter Table DATA_MediaIdentifierBlackList
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_MediaIdentifierBlackList_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_MediaIdentifierBlackList
  ADD CONSTRAINT [FK_DATA_MediaIdentifierBlackList_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_MediaIdentifierBlackList_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_MediaIdentifierBlackList 
  ADD CONSTRAINT [FK_DATA_MediaIdentifierBlackList_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_MediaStoredValue'))
BEGIN
  Alter Table DATA_MediaStoredValue
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_MediaStoredValue_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_MediaStoredValue
  ADD CONSTRAINT [FK_DATA_MediaStoredValue_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_MediaStoredValue_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_MediaStoredValue 
  ADD CONSTRAINT [FK_DATA_MediaStoredValue_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fesposito</ADDEDBY><SQLVERSION>2445</SQLVERSION><RMTRACKLINK>79275</RMTRACKLINK><REASON>Rolling back DATA_Deposit, DATA_DepositDetail</REASON><TABLENAMES>DATA_Deposit=DepositId
DATA_DepositDetail=DepositDetailId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_Deposit_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_Deposit
  DROP CONSTRAINT FK_DATA_Deposit_Last_UserId_Log
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_Deposit_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_Deposit
  DROP CONSTRAINT FK_DATA_Deposit_Last_WorkstationId_Log
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_Deposit'))
BEGIN
  ALTER TABLE DATA_Deposit
  DROP COLUMN Last_UserId_Log, Last_WorkstationId_Log, Last_DateTime_Log
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_DepositDetail_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_DepositDetail
  DROP CONSTRAINT FK_DATA_DepositDetail_Last_UserId_Log
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_DepositDetail_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_DepositDetail
  DROP CONSTRAINT FK_DATA_DepositDetail_Last_WorkstationId_Log
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_DepositDetail'))
BEGIN
  ALTER TABLE DATA_DepositDetail
  DROP COLUMN Last_UserId_Log, Last_WorkstationId_Log, Last_DateTime_Log
END
</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fesposito</ADDEDBY><SQLVERSION>2444</SQLVERSION><RMTRACKLINK>79275</RMTRACKLINK><REASON>Rolling back DATA_Box</REASON><TABLENAMES>DATA_Box=BoxId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_Box_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_Box
  DROP CONSTRAINT FK_DATA_Box_Last_UserId_Log
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_Box_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_Box
  DROP CONSTRAINT FK_DATA_Box_Last_WorkstationId_Log
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_Box'))
BEGIN
  ALTER TABLE DATA_Box
  DROP COLUMN Last_UserId_Log, Last_WorkstationId_Log, Last_DateTime_Log
END
</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>2443</SQLVERSION><RMTRACKLINK>79275</RMTRACKLINK><REASON>3 new fields added:
1) Last_UserId_Log
2)Last_WorkstationId_Log
3)Last_DateTime_Log</REASON><TABLENAMES>CNF_SeatCategory=SeatCategoryId
CNF_SeatCategory_Permission=SeatCategoryPermissionId
CNF_SeatLayout=SeatLayoutId
CNF_SeatLayout2Template=SeatLayout2TemplateId
CNF_SeatLayoutItem=SeatLayoutItemID
CNF_SeatPerformance=SeatPerformanceId
CNF_SeatTemplate=SeatTemplateId
CNF_Shell=ShellId
CNF_ShopCartValidation=ShopCartValidationId
CNF_ShopCartValidation_Permission=ShopCartValidationPermissionID
CNF_ShopCartValidationItem=ShopCartValidationItemId
CNF_ShopCartValidationItem2Event=ShopCartValidationItem2EventId
CNF_ShopCartValidationItem2MatrixCell=ShopCartValidationItem2MatrixCellId
CNF_ShopCartValidationItem2StatisticalGroup=ShopCartValidationItem2StatisticalGroupId
CNF_Site=SiteId
CNF_Site_LoginPermission=SiteLoginPermissionId
CNF_SpaceStructure=SpaceStructureId
CNF_StatisticalGroup=StatisticalGroupId
CNF_StatisticalGroupValidity=StatisticalGroupValidityId
CNF_Subscription=SubscriptionId
CNF_Subscription2Performance=Subscription2PerformanceId
CNF_SuggestiveSell=SuggestiveSellId
CNF_SuggestiveSell_Permission=SuggestiveSellPermissionId
CNF_SuggestiveSell2Event=SuggestiveSell2EventId
CNF_SuggestiveSell2EventCategory=SuggestiveSell2EventCategoryId
CNF_SuggestiveSell2MatrixCell=SuggestiveSell2MatrixCellId
CNF_SuggestiveSell2StatisticalGroup=SuggestiveSell2StatisticalGroupId
CNF_Survey=SurveyId
CNF_System=SystemId
CNF_Tax=TaxId
CNF_Tax2Location=Tax2LocationId
CNF_Tax2Package=Tax2PackageId
CNF_TaxBracket=TaxBracketId
CNF_TaxPackage=TaxPackageId
CNF_TicketPackageGroup=TicketPackageGroupId
CNF_TicketPackageGroupPermission=TicketPackageGroupPermissionId
CNF_TimeSlot=TimeSlotId
CNF_TravelMatrix=TravelMatrixId
CNF_TravelTime=TravelTimeId
CNF_Trigger=TriggerId
CNF_Upgrade=UpgradeId
CNF_UpSale=UpSaleId
CNF_UpSell=UpSellId
CNF_UpSell_Permission=UpSellPermissionId
CNF_UpSell_Validity=UpSellValidityId
CNF_Upsell2MatrixCell=UpSell2MatrixCellId
CNF_User=UserId
CNF_User2Group=User2Group
CNF_UserGroup=UserGroupId
CNF_VenueMap=VenueMapId
CNF_VenueMapItem=VenueMapItemId
CNF_Workstation=WorkstationId
CNF_WorkstationDevice=WorkstationDeviceId
COA_CNF_Account=COAAccountId
COA_CNF_AccountConfig=COAAccountConfigId
COA_CNF_AccountType=COAAccountTypeId
DATA_Account=AccountId
DATA_Account2CRM=Account2CRMId
DATA_AccountFinancial=AccountId
DATA_AccountRelationship=AccountRelationshipId
DATA_AddressVerification=PaymentId
DATA_AptRotationCount=AptRotationCountId
DATA_BankAccount=BankAccountId
DATA_Batch=BatchId
DATA_Biometric=BiometricId
DATA_Biometric2Ticket=Biometric2TicketId
DATA_Box=BoxId
DATA_CapacityCounter=CapacityCounterId
DATA_CapacityCounterRef=CapacityCounterRefId
DATA_Coupon=CouponId
DATA_Deposit=DepositId
DATA_DepositDetail=DepositDetailId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_SeatCategory'))
BEGIN
  Alter Table CNF_SeatCategory
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_SeatCategory_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_SeatCategory
  ADD CONSTRAINT [FK_CNF_SeatCategory_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_SeatCategory_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_SeatCategory 
  ADD CONSTRAINT [FK_CNF_SeatCategory_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_SeatCategory_Permission'))
BEGIN
  Alter Table CNF_SeatCategory_Permission
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_SeatCategory_Permission_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_SeatCategory_Permission
  ADD CONSTRAINT [FK_CNF_SeatCategory_Permission_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_SeatCategory_Permission_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_SeatCategory_Permission 
  ADD CONSTRAINT [FK_CNF_SeatCategory_Permission_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_SeatLayout'))
BEGIN
  Alter Table CNF_SeatLayout
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_SeatLayout_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_SeatLayout
  ADD CONSTRAINT [FK_CNF_SeatLayout_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_SeatLayout_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_SeatLayout 
  ADD CONSTRAINT [FK_CNF_SeatLayout_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_SeatLayout2Template'))
BEGIN
  Alter Table CNF_SeatLayout2Template
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_SeatLayout2Template_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_SeatLayout2Template
  ADD CONSTRAINT [FK_CNF_SeatLayout2Template_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_SeatLayout2Template_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_SeatLayout2Template 
  ADD CONSTRAINT [FK_CNF_SeatLayout2Template_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_SeatLayoutItem'))
BEGIN
  Alter Table CNF_SeatLayoutItem
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_SeatLayoutItem_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_SeatLayoutItem
  ADD CONSTRAINT [FK_CNF_SeatLayoutItem_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_SeatLayoutItem_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_SeatLayoutItem 
  ADD CONSTRAINT [FK_CNF_SeatLayoutItem_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_SeatPerformance'))
BEGIN
  Alter Table CNF_SeatPerformance
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_SeatPerformance_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_SeatPerformance
  ADD CONSTRAINT [FK_CNF_SeatPerformance_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_SeatPerformance_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_SeatPerformance 
  ADD CONSTRAINT [FK_CNF_SeatPerformance_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_SeatTemplate'))
BEGIN
  Alter Table CNF_SeatTemplate
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_SeatTemplate_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_SeatTemplate
  ADD CONSTRAINT [FK_CNF_SeatTemplate_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_SeatTemplate_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_SeatTemplate 
  ADD CONSTRAINT [FK_CNF_SeatTemplate_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_Shell'))
BEGIN
  Alter Table CNF_Shell
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Shell_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_Shell
  ADD CONSTRAINT [FK_CNF_Shell_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Shell_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_Shell 
  ADD CONSTRAINT [FK_CNF_Shell_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_ShopCartValidation'))
BEGIN
  Alter Table CNF_ShopCartValidation
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_ShopCartValidation_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_ShopCartValidation
  ADD CONSTRAINT [FK_CNF_ShopCartValidation_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_ShopCartValidation_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_ShopCartValidation 
  ADD CONSTRAINT [FK_CNF_ShopCartValidation_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_ShopCartValidation_Permission'))
BEGIN
  Alter Table CNF_ShopCartValidation_Permission
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_ShopCartValidation_Permission_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_ShopCartValidation_Permission
  ADD CONSTRAINT [FK_CNF_ShopCartValidation_Permission_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_ShopCartValidation_Permission_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_ShopCartValidation_Permission 
  ADD CONSTRAINT [FK_CNF_ShopCartValidation_Permission_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_ShopCartValidationItem'))
BEGIN
  Alter Table CNF_ShopCartValidationItem
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_ShopCartValidationItem_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_ShopCartValidationItem
  ADD CONSTRAINT [FK_CNF_ShopCartValidationItem_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_ShopCartValidationItem_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_ShopCartValidationItem 
  ADD CONSTRAINT [FK_CNF_ShopCartValidationItem_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_ShopCartValidationItem2Event'))
BEGIN
  Alter Table CNF_ShopCartValidationItem2Event
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_ShopCartValidationItem2Event_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_ShopCartValidationItem2Event
  ADD CONSTRAINT [FK_CNF_ShopCartValidationItem2Event_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_ShopCartValidationItem2Event_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_ShopCartValidationItem2Event 
  ADD CONSTRAINT [FK_CNF_ShopCartValidationItem2Event_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_ShopCartValidationItem2MatrixCell'))
BEGIN
  Alter Table CNF_ShopCartValidationItem2MatrixCell
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_ShopCartValidationItem2MatrixCell_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_ShopCartValidationItem2MatrixCell
  ADD CONSTRAINT [FK_CNF_ShopCartValidationItem2MatrixCell_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_ShopCartValidationItem2MatrixCell_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_ShopCartValidationItem2MatrixCell 
  ADD CONSTRAINT [FK_CNF_ShopCartValidationItem2MatrixCell_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_ShopCartValidationItem2StatisticalGroup'))
BEGIN
  Alter Table CNF_ShopCartValidationItem2StatisticalGroup
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_ShopCartValidationItem2StatisticalGroup_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_ShopCartValidationItem2StatisticalGroup
  ADD CONSTRAINT [FK_CNF_ShopCartValidationItem2StatisticalGroup_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_ShopCartValidationItem2StatisticalGroup_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_ShopCartValidationItem2StatisticalGroup 
  ADD CONSTRAINT [FK_CNF_ShopCartValidationItem2StatisticalGroup_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_Site'))
BEGIN
  Alter Table CNF_Site
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Site_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_Site
  ADD CONSTRAINT [FK_CNF_Site_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Site_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_Site 
  ADD CONSTRAINT [FK_CNF_Site_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_Site_LoginPermission'))
BEGIN
  Alter Table CNF_Site_LoginPermission
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Site_LoginPermission_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_Site_LoginPermission
  ADD CONSTRAINT [FK_CNF_Site_LoginPermission_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Site_LoginPermission_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_Site_LoginPermission 
  ADD CONSTRAINT [FK_CNF_Site_LoginPermission_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_SpaceStructure'))
BEGIN
  Alter Table CNF_SpaceStructure
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_SpaceStructure_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_SpaceStructure
  ADD CONSTRAINT [FK_CNF_SpaceStructure_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_SpaceStructure_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_SpaceStructure 
  ADD CONSTRAINT [FK_CNF_SpaceStructure_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_StatisticalGroup'))
BEGIN
  Alter Table CNF_StatisticalGroup
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_StatisticalGroup_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_StatisticalGroup
  ADD CONSTRAINT [FK_CNF_StatisticalGroup_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_StatisticalGroup_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_StatisticalGroup 
  ADD CONSTRAINT [FK_CNF_StatisticalGroup_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_StatisticalGroupValidity'))
BEGIN
  Alter Table CNF_StatisticalGroupValidity
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_StatisticalGroupValidity_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_StatisticalGroupValidity
  ADD CONSTRAINT [FK_CNF_StatisticalGroupValidity_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_StatisticalGroupValidity_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_StatisticalGroupValidity 
  ADD CONSTRAINT [FK_CNF_StatisticalGroupValidity_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_Subscription'))
BEGIN
  Alter Table CNF_Subscription
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Subscription_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_Subscription
  ADD CONSTRAINT [FK_CNF_Subscription_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Subscription_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_Subscription 
  ADD CONSTRAINT [FK_CNF_Subscription_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_Subscription2Performance'))
BEGIN
  Alter Table CNF_Subscription2Performance
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Subscription2Performance_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_Subscription2Performance
  ADD CONSTRAINT [FK_CNF_Subscription2Performance_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Subscription2Performance_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_Subscription2Performance 
  ADD CONSTRAINT [FK_CNF_Subscription2Performance_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_SuggestiveSell'))
BEGIN
  Alter Table CNF_SuggestiveSell
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_SuggestiveSell_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_SuggestiveSell
  ADD CONSTRAINT [FK_CNF_SuggestiveSell_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_SuggestiveSell_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_SuggestiveSell 
  ADD CONSTRAINT [FK_CNF_SuggestiveSell_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_SuggestiveSell_Permission'))
BEGIN
  Alter Table CNF_SuggestiveSell_Permission
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_SuggestiveSell_Permission_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_SuggestiveSell_Permission
  ADD CONSTRAINT [FK_CNF_SuggestiveSell_Permission_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_SuggestiveSell_Permission_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_SuggestiveSell_Permission 
  ADD CONSTRAINT [FK_CNF_SuggestiveSell_Permission_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_SuggestiveSell2Event'))
BEGIN
  Alter Table CNF_SuggestiveSell2Event
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_SuggestiveSell2Event_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_SuggestiveSell2Event
  ADD CONSTRAINT [FK_CNF_SuggestiveSell2Event_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_SuggestiveSell2Event_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_SuggestiveSell2Event 
  ADD CONSTRAINT [FK_CNF_SuggestiveSell2Event_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_SuggestiveSell2EventCategory'))
BEGIN
  Alter Table CNF_SuggestiveSell2EventCategory
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_SuggestiveSell2EventCategory_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_SuggestiveSell2EventCategory
  ADD CONSTRAINT [FK_CNF_SuggestiveSell2EventCategory_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_SuggestiveSell2EventCategory_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_SuggestiveSell2EventCategory 
  ADD CONSTRAINT [FK_CNF_SuggestiveSell2EventCategory_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_SuggestiveSell2MatrixCell'))
BEGIN
  Alter Table CNF_SuggestiveSell2MatrixCell
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_SuggestiveSell2MatrixCell_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_SuggestiveSell2MatrixCell
  ADD CONSTRAINT [FK_CNF_SuggestiveSell2MatrixCell_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_SuggestiveSell2MatrixCell_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_SuggestiveSell2MatrixCell 
  ADD CONSTRAINT [FK_CNF_SuggestiveSell2MatrixCell_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_SuggestiveSell2StatisticalGroup'))
BEGIN
  Alter Table CNF_SuggestiveSell2StatisticalGroup
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_SuggestiveSell2StatisticalGroup_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_SuggestiveSell2StatisticalGroup
  ADD CONSTRAINT [FK_CNF_SuggestiveSell2StatisticalGroup_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_SuggestiveSell2StatisticalGroup_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_SuggestiveSell2StatisticalGroup 
  ADD CONSTRAINT [FK_CNF_SuggestiveSell2StatisticalGroup_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_Survey'))
BEGIN
  Alter Table CNF_Survey
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Survey_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_Survey
  ADD CONSTRAINT [FK_CNF_Survey_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Survey_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_Survey 
  ADD CONSTRAINT [FK_CNF_Survey_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_System'))
BEGIN
  Alter Table CNF_System
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_System_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_System
  ADD CONSTRAINT [FK_CNF_System_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_System_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_System 
  ADD CONSTRAINT [FK_CNF_System_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_Tax'))
BEGIN
  Alter Table CNF_Tax
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Tax_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_Tax
  ADD CONSTRAINT [FK_CNF_Tax_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Tax_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_Tax 
  ADD CONSTRAINT [FK_CNF_Tax_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_Tax2Location'))
BEGIN
  Alter Table CNF_Tax2Location
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Tax2Location_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_Tax2Location
  ADD CONSTRAINT [FK_CNF_Tax2Location_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Tax2Location_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_Tax2Location 
  ADD CONSTRAINT [FK_CNF_Tax2Location_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_Tax2Package'))
BEGIN
  Alter Table CNF_Tax2Package
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Tax2Package_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_Tax2Package
  ADD CONSTRAINT [FK_CNF_Tax2Package_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Tax2Package_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_Tax2Package 
  ADD CONSTRAINT [FK_CNF_Tax2Package_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_TaxBracket'))
BEGIN
  Alter Table CNF_TaxBracket
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_TaxBracket_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_TaxBracket
  ADD CONSTRAINT [FK_CNF_TaxBracket_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_TaxBracket_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_TaxBracket 
  ADD CONSTRAINT [FK_CNF_TaxBracket_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_TaxPackage'))
BEGIN
  Alter Table CNF_TaxPackage
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_TaxPackage_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_TaxPackage
  ADD CONSTRAINT [FK_CNF_TaxPackage_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_TaxPackage_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_TaxPackage 
  ADD CONSTRAINT [FK_CNF_TaxPackage_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_TicketPackageGroup'))
BEGIN
  Alter Table CNF_TicketPackageGroup
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_TicketPackageGroup_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_TicketPackageGroup
  ADD CONSTRAINT [FK_CNF_TicketPackageGroup_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_TicketPackageGroup_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_TicketPackageGroup 
  ADD CONSTRAINT [FK_CNF_TicketPackageGroup_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_TicketPackageGroupPermission'))
BEGIN
  Alter Table CNF_TicketPackageGroupPermission
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_TicketPackageGroupPermission_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_TicketPackageGroupPermission
  ADD CONSTRAINT [FK_CNF_TicketPackageGroupPermission_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_TicketPackageGroupPermission_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_TicketPackageGroupPermission 
  ADD CONSTRAINT [FK_CNF_TicketPackageGroupPermission_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_TimeSlot'))
BEGIN
  Alter Table CNF_TimeSlot
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_TimeSlot_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_TimeSlot
  ADD CONSTRAINT [FK_CNF_TimeSlot_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_TimeSlot_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_TimeSlot 
  ADD CONSTRAINT [FK_CNF_TimeSlot_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_TravelMatrix'))
BEGIN
  Alter Table CNF_TravelMatrix
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_TravelMatrix_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_TravelMatrix
  ADD CONSTRAINT [FK_CNF_TravelMatrix_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_TravelMatrix_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_TravelMatrix 
  ADD CONSTRAINT [FK_CNF_TravelMatrix_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_TravelTime'))
BEGIN
  Alter Table CNF_TravelTime
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_TravelTime_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_TravelTime
  ADD CONSTRAINT [FK_CNF_TravelTime_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_TravelTime_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_TravelTime 
  ADD CONSTRAINT [FK_CNF_TravelTime_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_Trigger'))
BEGIN
  Alter Table CNF_Trigger
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Trigger_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_Trigger
  ADD CONSTRAINT [FK_CNF_Trigger_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Trigger_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_Trigger 
  ADD CONSTRAINT [FK_CNF_Trigger_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_Upgrade'))
BEGIN
  Alter Table CNF_Upgrade
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Upgrade_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_Upgrade
  ADD CONSTRAINT [FK_CNF_Upgrade_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Upgrade_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_Upgrade 
  ADD CONSTRAINT [FK_CNF_Upgrade_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_UpSale'))
BEGIN
  Alter Table CNF_UpSale
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_UpSale_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_UpSale
  ADD CONSTRAINT [FK_CNF_UpSale_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_UpSale_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_UpSale 
  ADD CONSTRAINT [FK_CNF_UpSale_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_UpSell'))
BEGIN
  Alter Table CNF_UpSell
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_UpSell_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_UpSell
  ADD CONSTRAINT [FK_CNF_UpSell_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_UpSell_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_UpSell 
  ADD CONSTRAINT [FK_CNF_UpSell_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_UpSell_Permission'))
BEGIN
  Alter Table CNF_UpSell_Permission
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_UpSell_Permission_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_UpSell_Permission
  ADD CONSTRAINT [FK_CNF_UpSell_Permission_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_UpSell_Permission_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_UpSell_Permission 
  ADD CONSTRAINT [FK_CNF_UpSell_Permission_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_UpSell_Validity'))
BEGIN
  Alter Table CNF_UpSell_Validity
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_UpSell_Validity_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_UpSell_Validity
  ADD CONSTRAINT [FK_CNF_UpSell_Validity_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_UpSell_Validity_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_UpSell_Validity 
  ADD CONSTRAINT [FK_CNF_UpSell_Validity_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_Upsell2MatrixCell'))
BEGIN
  Alter Table CNF_Upsell2MatrixCell
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Upsell2MatrixCell_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_Upsell2MatrixCell
  ADD CONSTRAINT [FK_CNF_Upsell2MatrixCell_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Upsell2MatrixCell_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_Upsell2MatrixCell 
  ADD CONSTRAINT [FK_CNF_Upsell2MatrixCell_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_User'))
BEGIN
  Alter Table CNF_User
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_User_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_User
  ADD CONSTRAINT [FK_CNF_User_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_User_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_User 
  ADD CONSTRAINT [FK_CNF_User_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_User2Group'))
BEGIN
  Alter Table CNF_User2Group
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_User2Group_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_User2Group
  ADD CONSTRAINT [FK_CNF_User2Group_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_User2Group_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_User2Group 
  ADD CONSTRAINT [FK_CNF_User2Group_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_UserGroup'))
BEGIN
  Alter Table CNF_UserGroup
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_UserGroup_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_UserGroup
  ADD CONSTRAINT [FK_CNF_UserGroup_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_UserGroup_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_UserGroup 
  ADD CONSTRAINT [FK_CNF_UserGroup_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_VenueMap'))
BEGIN
  Alter Table CNF_VenueMap
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_VenueMap_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_VenueMap
  ADD CONSTRAINT [FK_CNF_VenueMap_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_VenueMap_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_VenueMap 
  ADD CONSTRAINT [FK_CNF_VenueMap_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_VenueMapItem'))
BEGIN
  Alter Table CNF_VenueMapItem
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_VenueMapItem_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_VenueMapItem
  ADD CONSTRAINT [FK_CNF_VenueMapItem_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_VenueMapItem_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_VenueMapItem 
  ADD CONSTRAINT [FK_CNF_VenueMapItem_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_Workstation'))
BEGIN
  Alter Table CNF_Workstation
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Workstation_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_Workstation
  ADD CONSTRAINT [FK_CNF_Workstation_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Workstation_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_Workstation 
  ADD CONSTRAINT [FK_CNF_Workstation_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_WorkstationDevice'))
BEGIN
  Alter Table CNF_WorkstationDevice
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_WorkstationDevice_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_WorkstationDevice
  ADD CONSTRAINT [FK_CNF_WorkstationDevice_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_WorkstationDevice_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_WorkstationDevice 
  ADD CONSTRAINT [FK_CNF_WorkstationDevice_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'COA_CNF_Account'))
BEGIN
  Alter Table COA_CNF_Account
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_COA_CNF_Account_Last_UserId_Log')
BEGIN
  ALTER TABLE COA_CNF_Account
  ADD CONSTRAINT [FK_COA_CNF_Account_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_COA_CNF_Account_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE COA_CNF_Account 
  ADD CONSTRAINT [FK_COA_CNF_Account_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'COA_CNF_AccountConfig'))
BEGIN
  Alter Table COA_CNF_AccountConfig
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_COA_CNF_AccountConfig_Last_UserId_Log')
BEGIN
  ALTER TABLE COA_CNF_AccountConfig
  ADD CONSTRAINT [FK_COA_CNF_AccountConfig_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_COA_CNF_AccountConfig_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE COA_CNF_AccountConfig 
  ADD CONSTRAINT [FK_COA_CNF_AccountConfig_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'COA_CNF_AccountType'))
BEGIN
  Alter Table COA_CNF_AccountType
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_COA_CNF_AccountType_Last_UserId_Log')
BEGIN
  ALTER TABLE COA_CNF_AccountType
  ADD CONSTRAINT [FK_COA_CNF_AccountType_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_COA_CNF_AccountType_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE COA_CNF_AccountType 
  ADD CONSTRAINT [FK_COA_CNF_AccountType_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_Account'))
BEGIN
  Alter Table DATA_Account
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_Account_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_Account
  ADD CONSTRAINT [FK_DATA_Account_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_Account_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_Account 
  ADD CONSTRAINT [FK_DATA_Account_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_Account2CRM'))
BEGIN
  Alter Table DATA_Account2CRM
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_Account2CRM_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_Account2CRM
  ADD CONSTRAINT [FK_DATA_Account2CRM_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_Account2CRM_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_Account2CRM 
  ADD CONSTRAINT [FK_DATA_Account2CRM_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_AccountFinancial'))
BEGIN
  Alter Table DATA_AccountFinancial
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_AccountFinancial_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_AccountFinancial
  ADD CONSTRAINT [FK_DATA_AccountFinancial_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_AccountFinancial_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_AccountFinancial 
  ADD CONSTRAINT [FK_DATA_AccountFinancial_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_AccountRelationship'))
BEGIN
  Alter Table DATA_AccountRelationship
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_AccountRelationship_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_AccountRelationship
  ADD CONSTRAINT [FK_DATA_AccountRelationship_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_AccountRelationship_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_AccountRelationship 
  ADD CONSTRAINT [FK_DATA_AccountRelationship_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_AddressVerification'))
BEGIN
  Alter Table DATA_AddressVerification
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_AddressVerification_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_AddressVerification
  ADD CONSTRAINT [FK_DATA_AddressVerification_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_AddressVerification_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_AddressVerification 
  ADD CONSTRAINT [FK_DATA_AddressVerification_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_AptRotationCount'))
BEGIN
  Alter Table DATA_AptRotationCount
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_AptRotationCount_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_AptRotationCount
  ADD CONSTRAINT [FK_DATA_AptRotationCount_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_AptRotationCount_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_AptRotationCount 
  ADD CONSTRAINT [FK_DATA_AptRotationCount_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_BankAccount'))
BEGIN
  Alter Table DATA_BankAccount
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_BankAccount_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_BankAccount
  ADD CONSTRAINT [FK_DATA_BankAccount_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_BankAccount_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_BankAccount 
  ADD CONSTRAINT [FK_DATA_BankAccount_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_Batch'))
BEGIN
  Alter Table DATA_Batch
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_Batch_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_Batch
  ADD CONSTRAINT [FK_DATA_Batch_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_Batch_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_Batch 
  ADD CONSTRAINT [FK_DATA_Batch_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_Biometric'))
BEGIN
  Alter Table DATA_Biometric
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_Biometric_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_Biometric
  ADD CONSTRAINT [FK_DATA_Biometric_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_Biometric_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_Biometric 
  ADD CONSTRAINT [FK_DATA_Biometric_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_Biometric2Ticket'))
BEGIN
  Alter Table DATA_Biometric2Ticket
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_Biometric2Ticket_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_Biometric2Ticket
  ADD CONSTRAINT [FK_DATA_Biometric2Ticket_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_Biometric2Ticket_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_Biometric2Ticket 
  ADD CONSTRAINT [FK_DATA_Biometric2Ticket_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_Box'))
BEGIN
  Alter Table DATA_Box
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_Box_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_Box
  ADD CONSTRAINT [FK_DATA_Box_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_Box_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_Box 
  ADD CONSTRAINT [FK_DATA_Box_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_CapacityCounter'))
BEGIN
  Alter Table DATA_CapacityCounter
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_CapacityCounter_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_CapacityCounter
  ADD CONSTRAINT [FK_DATA_CapacityCounter_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_CapacityCounter_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_CapacityCounter 
  ADD CONSTRAINT [FK_DATA_CapacityCounter_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_CapacityCounterRef'))
BEGIN
  Alter Table DATA_CapacityCounterRef
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_CapacityCounterRef_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_CapacityCounterRef
  ADD CONSTRAINT [FK_DATA_CapacityCounterRef_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_CapacityCounterRef_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_CapacityCounterRef 
  ADD CONSTRAINT [FK_DATA_CapacityCounterRef_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_Coupon'))
BEGIN
  Alter Table DATA_Coupon
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_Coupon_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_Coupon
  ADD CONSTRAINT [FK_DATA_Coupon_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_Coupon_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_Coupon 
  ADD CONSTRAINT [FK_DATA_Coupon_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_Deposit'))
BEGIN
  Alter Table DATA_Deposit
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_Deposit_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_Deposit
  ADD CONSTRAINT [FK_DATA_Deposit_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_Deposit_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_Deposit 
  ADD CONSTRAINT [FK_DATA_Deposit_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'DATA_DepositDetail'))
BEGIN
  Alter Table DATA_DepositDetail
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_DepositDetail_Last_UserId_Log')
BEGIN
  ALTER TABLE DATA_DepositDetail
  ADD CONSTRAINT [FK_DATA_DepositDetail_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_DepositDetail_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE DATA_DepositDetail 
  ADD CONSTRAINT [FK_DATA_DepositDetail_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>scoluccia</ADDEDBY><SQLVERSION>2442</SQLVERSION><RMTRACKLINK>78903</RMTRACKLINK><REASON>0)ADD PckVoidRefundType to CNF_Promotion
1)ADD PckVoidRefundType to DATA_SaleItemRule
</REASON><TABLENAMES>CNF_Promotion=PromotionId
DATA_SaleItemRule=SaleItemRuleId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
               WHERE Name = N'PckVoidRefundType' AND
                     Object_ID  = Object_ID(N'CNF_Promotion'))
BEGIN
  ALTER TABLE CNF_Promotion 
  ADD PckVoidRefundType [smallint] NOT NULL Default 0
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'PckVoidRefundType' AND
                Object_ID  = Object_ID(N'DATA_SaleItemRule'))
BEGIN
  ALTER TABLE DATA_SaleItemRule 
  ADD [PckVoidRefundType] [smallint] NULL
END
</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>2441</SQLVERSION><RMTRACKLINK>79275</RMTRACKLINK><REASON>3 new fields added to 36 tables:
1) Last_UserId_Log
2)Last_WorkstationId_Log
3)Last_DateTime_Log</REASON><TABLENAMES>CNF_Performance=PerformanceId
CNF_Performance_Permission=PerformancePermissionId
CNF_Performance_SaleValidity=PerformanceSaleValidityId
CNF_PerformanceCategory=PerformanceCategoryId
CNF_PerformanceCategoryValidity=PerfCatValidityId
CNF_PerformanceSeat=PerformanceSeatId
CNF_PriceList=PriceListId
CNF_PriceTable=PriceTableId
CNF_Producer=ProducerId
CNF_Product=ProductId
CNF_ProductValidity=ProductValidityId
CNF_ProductValidity2Event=ProductValidity2EventId
CNF_Projection=ProjectionId
CNF_Promotion=PromotionId
CNF_Promotion_Quota=PromotionQuotaId
CNF_PromotionAssociation=PromotionAssociationId
CNF_PromotionEvent=PromotionEventId
CNF_PromotionItem=PromotionItemId
CNF_PromotionItem_Quota=PromotionItemQuotaId
CNF_PromotionItemRule=PromotionItemRuleId
CNF_PromotionPermission=PromotionPermissionId
CNF_PromotionProduct=PromotionProductId
CNF_PromotionProductCategory=PromotionProductCategoryId
CNF_PromotionValidity=PromotionValidityId
CNF_PswDictionary=DictionaryId
CNF_RoundingRule=RoundingRuleId
CNF_SaleLimit=SaleLimitId
CNF_SaleLimitRestriction=SaleLimitRestrictionId
CNF_SaleRestriction=SaleRestrictionId
CNF_SaleRestrictionValidity=SaleRestrictionValidityId
CNF_SALTO_PERIPHERALS=RowId
CNF_SALTO_ZONE=RowId
CNF_Scheduler=SchedulerId
CNF_SeasonalRule=SeasonalRuleId
CNF_Seat=SeatId
CNF_PerformanceFilter=PerformaceFilterId
</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_Performance'))
BEGIN
  Alter Table CNF_Performance
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Performance_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_Performance
  ADD CONSTRAINT [FK_CNF_Performance_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Performance_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_Performance 
  ADD CONSTRAINT [FK_CNF_Performance_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_Performance_Permission'))
BEGIN
  Alter Table CNF_Performance_Permission
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Performance_Permission_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_Performance_Permission
  ADD CONSTRAINT [FK_CNF_Performance_Permission_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Performance_Permission_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_Performance_Permission 
  ADD CONSTRAINT [FK_CNF_Performance_Permission_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_Performance_SaleValidity'))
BEGIN
  Alter Table CNF_Performance_SaleValidity
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Performance_SaleValidity_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_Performance_SaleValidity
  ADD CONSTRAINT [FK_CNF_Performance_SaleValidity_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Performance_SaleValidity_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_Performance_SaleValidity 
  ADD CONSTRAINT [FK_CNF_Performance_SaleValidity_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_PerformanceCategory'))
BEGIN
  Alter Table CNF_PerformanceCategory
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_PerformanceCategory_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_PerformanceCategory
  ADD CONSTRAINT [FK_CNF_PerformanceCategory_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_PerformanceCategory_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_PerformanceCategory 
  ADD CONSTRAINT [FK_CNF_PerformanceCategory_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_PerformanceCategoryValidity'))
BEGIN
  Alter Table CNF_PerformanceCategoryValidity
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_PerformanceCategoryValidity_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_PerformanceCategoryValidity
  ADD CONSTRAINT [FK_CNF_PerformanceCategoryValidity_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_PerformanceCategoryValidity_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_PerformanceCategoryValidity 
  ADD CONSTRAINT [FK_CNF_PerformanceCategoryValidity_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_PerformanceSeat'))
BEGIN
  Alter Table CNF_PerformanceSeat
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_PerformanceSeat_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_PerformanceSeat
  ADD CONSTRAINT [FK_CNF_PerformanceSeat_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_PerformanceSeat_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_PerformanceSeat 
  ADD CONSTRAINT [FK_CNF_PerformanceSeat_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_PriceList'))
BEGIN
  Alter Table CNF_PriceList
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_PriceList_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_PriceList
  ADD CONSTRAINT [FK_CNF_PriceList_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_PriceList_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_PriceList 
  ADD CONSTRAINT [FK_CNF_PriceList_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_PriceTable'))
BEGIN
  Alter Table CNF_PriceTable
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_PriceTable_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_PriceTable
  ADD CONSTRAINT [FK_CNF_PriceTable_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_PriceTable_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_PriceTable 
  ADD CONSTRAINT [FK_CNF_PriceTable_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_Producer'))
BEGIN
  Alter Table CNF_Producer
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Producer_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_Producer
  ADD CONSTRAINT [FK_CNF_Producer_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Producer_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_Producer 
  ADD CONSTRAINT [FK_CNF_Producer_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_Product'))
BEGIN
  Alter Table CNF_Product
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Product_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_Product
  ADD CONSTRAINT [FK_CNF_Product_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Product_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_Product 
  ADD CONSTRAINT [FK_CNF_Product_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_ProductValidity'))
BEGIN
  Alter Table CNF_ProductValidity
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_ProductValidity_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_ProductValidity
  ADD CONSTRAINT [FK_CNF_ProductValidity_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_ProductValidity_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_ProductValidity 
  ADD CONSTRAINT [FK_CNF_ProductValidity_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_ProductValidity2Event'))
BEGIN
  Alter Table CNF_ProductValidity2Event
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_ProductValidity2Event_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_ProductValidity2Event
  ADD CONSTRAINT [FK_CNF_ProductValidity2Event_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_ProductValidity2Event_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_ProductValidity2Event 
  ADD CONSTRAINT [FK_CNF_ProductValidity2Event_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_Projection'))
BEGIN
  Alter Table CNF_Projection
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Projection_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_Projection
  ADD CONSTRAINT [FK_CNF_Projection_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Projection_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_Projection 
  ADD CONSTRAINT [FK_CNF_Projection_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_Promotion'))
BEGIN
  Alter Table CNF_Promotion
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Promotion_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_Promotion
  ADD CONSTRAINT [FK_CNF_Promotion_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Promotion_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_Promotion 
  ADD CONSTRAINT [FK_CNF_Promotion_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_Promotion_Quota'))
BEGIN
  Alter Table CNF_Promotion_Quota
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Promotion_Quota_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_Promotion_Quota
  ADD CONSTRAINT [FK_CNF_Promotion_Quota_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Promotion_Quota_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_Promotion_Quota 
  ADD CONSTRAINT [FK_CNF_Promotion_Quota_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_PromotionAssociation'))
BEGIN
  Alter Table CNF_PromotionAssociation
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_PromotionAssociation_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_PromotionAssociation
  ADD CONSTRAINT [FK_CNF_PromotionAssociation_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_PromotionAssociation_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_PromotionAssociation 
  ADD CONSTRAINT [FK_CNF_PromotionAssociation_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_PromotionEvent'))
BEGIN
  Alter Table CNF_PromotionEvent
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_PromotionEvent_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_PromotionEvent
  ADD CONSTRAINT [FK_CNF_PromotionEvent_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_PromotionEvent_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_PromotionEvent 
  ADD CONSTRAINT [FK_CNF_PromotionEvent_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_PromotionItem'))
BEGIN
  Alter Table CNF_PromotionItem
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_PromotionItem_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_PromotionItem
  ADD CONSTRAINT [FK_CNF_PromotionItem_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_PromotionItem_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_PromotionItem 
  ADD CONSTRAINT [FK_CNF_PromotionItem_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_PromotionItem_Quota'))
BEGIN
  Alter Table CNF_PromotionItem_Quota
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_PromotionItem_Quota_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_PromotionItem_Quota
  ADD CONSTRAINT [FK_CNF_PromotionItem_Quota_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_PromotionItem_Quota_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_PromotionItem_Quota 
  ADD CONSTRAINT [FK_CNF_PromotionItem_Quota_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_PromotionItemRule'))
BEGIN
  Alter Table CNF_PromotionItemRule
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_PromotionItemRule_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_PromotionItemRule
  ADD CONSTRAINT [FK_CNF_PromotionItemRule_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_PromotionItemRule_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_PromotionItemRule 
  ADD CONSTRAINT [FK_CNF_PromotionItemRule_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_PromotionPermission'))
BEGIN
  Alter Table CNF_PromotionPermission
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_PromotionPermission_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_PromotionPermission
  ADD CONSTRAINT [FK_CNF_PromotionPermission_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_PromotionPermission_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_PromotionPermission 
  ADD CONSTRAINT [FK_CNF_PromotionPermission_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_PromotionProduct'))
BEGIN
  Alter Table CNF_PromotionProduct
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_PromotionProduct_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_PromotionProduct
  ADD CONSTRAINT [FK_CNF_PromotionProduct_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_PromotionProduct_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_PromotionProduct 
  ADD CONSTRAINT [FK_CNF_PromotionProduct_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_PromotionProductCategory'))
BEGIN
  Alter Table CNF_PromotionProductCategory
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_PromotionProductCategory_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_PromotionProductCategory
  ADD CONSTRAINT [FK_CNF_PromotionProductCategory_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_PromotionProductCategory_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_PromotionProductCategory 
  ADD CONSTRAINT [FK_CNF_PromotionProductCategory_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_PromotionValidity'))
BEGIN
  Alter Table CNF_PromotionValidity
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_PromotionValidity_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_PromotionValidity
  ADD CONSTRAINT [FK_CNF_PromotionValidity_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_PromotionValidity_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_PromotionValidity 
  ADD CONSTRAINT [FK_CNF_PromotionValidity_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_PswDictionary'))
BEGIN
  Alter Table CNF_PswDictionary
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_PswDictionary_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_PswDictionary
  ADD CONSTRAINT [FK_CNF_PswDictionary_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_PswDictionary_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_PswDictionary 
  ADD CONSTRAINT [FK_CNF_PswDictionary_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_RoundingRule'))
BEGIN
  Alter Table CNF_RoundingRule
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_RoundingRule_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_RoundingRule
  ADD CONSTRAINT [FK_CNF_RoundingRule_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_RoundingRule_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_RoundingRule 
  ADD CONSTRAINT [FK_CNF_RoundingRule_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_SaleLimit'))
BEGIN
  Alter Table CNF_SaleLimit
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_SaleLimit_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_SaleLimit
  ADD CONSTRAINT [FK_CNF_SaleLimit_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_SaleLimit_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_SaleLimit 
  ADD CONSTRAINT [FK_CNF_SaleLimit_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_SaleLimitRestriction'))
BEGIN
  Alter Table CNF_SaleLimitRestriction
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_SaleLimitRestriction_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_SaleLimitRestriction
  ADD CONSTRAINT [FK_CNF_SaleLimitRestriction_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_SaleLimitRestriction_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_SaleLimitRestriction 
  ADD CONSTRAINT [FK_CNF_SaleLimitRestriction_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_SaleRestriction'))
BEGIN
  Alter Table CNF_SaleRestriction
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_SaleRestriction_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_SaleRestriction
  ADD CONSTRAINT [FK_CNF_SaleRestriction_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_SaleRestriction_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_SaleRestriction 
  ADD CONSTRAINT [FK_CNF_SaleRestriction_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_SaleRestrictionValidity'))
BEGIN
  Alter Table CNF_SaleRestrictionValidity
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_SaleRestrictionValidity_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_SaleRestrictionValidity
  ADD CONSTRAINT [FK_CNF_SaleRestrictionValidity_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_SaleRestrictionValidity_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_SaleRestrictionValidity 
  ADD CONSTRAINT [FK_CNF_SaleRestrictionValidity_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_SALTO_PERIPHERALS'))
BEGIN
  Alter Table CNF_SALTO_PERIPHERALS
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_SALTO_PERIPHERALS_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_SALTO_PERIPHERALS
  ADD CONSTRAINT [FK_CNF_SALTO_PERIPHERALS_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_SALTO_PERIPHERALS_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_SALTO_PERIPHERALS 
  ADD CONSTRAINT [FK_CNF_SALTO_PERIPHERALS_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_SALTO_ZONE'))
BEGIN
  Alter Table CNF_SALTO_ZONE
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_SALTO_ZONE_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_SALTO_ZONE
  ADD CONSTRAINT [FK_CNF_SALTO_ZONE_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_SALTO_ZONE_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_SALTO_ZONE 
  ADD CONSTRAINT [FK_CNF_SALTO_ZONE_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_Scheduler'))
BEGIN
  Alter Table CNF_Scheduler
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Scheduler_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_Scheduler
  ADD CONSTRAINT [FK_CNF_Scheduler_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Scheduler_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_Scheduler 
  ADD CONSTRAINT [FK_CNF_Scheduler_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_SeasonalRule'))
BEGIN
  Alter Table CNF_SeasonalRule
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_SeasonalRule_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_SeasonalRule
  ADD CONSTRAINT [FK_CNF_SeasonalRule_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_SeasonalRule_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_SeasonalRule 
  ADD CONSTRAINT [FK_CNF_SeasonalRule_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_Seat'))
BEGIN
  Alter Table CNF_Seat
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Seat_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_Seat
  ADD CONSTRAINT [FK_CNF_Seat_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Seat_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_Seat 
  ADD CONSTRAINT [FK_CNF_Seat_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_PerformanceFilter'))
BEGIN
  Alter Table CNF_PerformanceFilter
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_PerformanceFilter_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_PerformanceFilter
  ADD CONSTRAINT [FK_CNF_PerformanceFilter_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_PerformanceFilter_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_PerformanceFilter 
  ADD CONSTRAINT [FK_CNF_PerformanceFilter_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>2440</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>3 new fields added to 48 tables:
1) Last_UserId_Log
2)Last_WorkstationId_Log
3)Last_DateTime_Log</REASON><TABLENAMES>CNF_Family=FamilyId
CNF_FiscalYear=FiscalYearId
CNF_FlexContract=FlexContractId
CNF_FlexContractFee=FlexContractFeeId
CNF_FlexPlanTemplate=FlexPlanTemplateId
CNF_FundCash=StartingFundId
CNF_FundItem=FundItemId
CNF_FundType=FundTypeId
CNF_Geo=GeoId
CNF_ImportMatch=ImportMatchId
CNF_IncentiveTicket=IncentiveTicketId
CNF_Invoice=InvoiceId
CNF_Language=LanguageId
CNF_LedgerAccount=LedgerAccountId
CNF_License=LicenseId
CNF_Location=LocationId
CNF_LocationMatrix=LocationMatrixId
CNF_MapView=MapId
CNF_Mask=MaskId
CNF_Mask_Utility=MaskUtilityId
CNF_MaskTable=MaskTableId
CNF_MaskTableItem=MaskTableItemId
CNF_MaskTableItem_Translation=MaskTableTranslationId
CNF_MatrixCell=MatrixCellId
CNF_MatrixCell_QuickUpgrade=QuickUpgradeId
CNF_MatrixCell_Renew=RenewId
CNF_MatrixCell2Delivery=MatrixCell2DeliveryId
CNF_MatrixCell2FlexContract=MatrixCell2FlexContractId
CNF_MatrixCellInfo=MatrixCellInfoId
CNF_MatrixCellPermission=MatrixCellPermissionId
CNF_MatrixCellTranslation=MatrixCellTranslationId
CNF_MatrixDimension=MatrixDimensionId
CNF_MatrixSheet=MatrixSheetId
CNF_MatrixSheet_SaleValidity=MatrixSheetSaleValidityId
CNF_MembershipCard=MSCardId
CNF_Merchant=MerchantId
CNF_MerchantTable=MerchantTableId
CNF_MultiLanguage=MultiLanguageId
CNF_Notification=NotificationId
CNF_OperatingArea=OperatingAreaId
CNF_PAY=PayId
CNF_Pay_MatrixCell=PayMatrixCellId
CNF_PaymentCard=PaymentCardId
CNF_PaymentCardCode=PaymentCardCodeId
CNF_PaymentCardRange=PaymentCardRangeID
CNF_PaymentMethod=PaymentMethodId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_Family'))
BEGIN
  Alter Table CNF_Family
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Family_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_Family
  ADD CONSTRAINT [FK_CNF_Family_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Family_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_Family 
  ADD CONSTRAINT [FK_CNF_Family_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_FiscalYear'))
BEGIN
  Alter Table CNF_FiscalYear
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_FiscalYear_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_FiscalYear
  ADD CONSTRAINT [FK_CNF_FiscalYear_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_FiscalYear_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_FiscalYear 
  ADD CONSTRAINT [FK_CNF_FiscalYear_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_FlexContract'))
BEGIN
  Alter Table CNF_FlexContract
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_FlexContract_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_FlexContract
  ADD CONSTRAINT [FK_CNF_FlexContract_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_FlexContract_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_FlexContract 
  ADD CONSTRAINT [FK_CNF_FlexContract_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_FlexContractFee'))
BEGIN
  Alter Table CNF_FlexContractFee
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_FlexContractFee_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_FlexContractFee
  ADD CONSTRAINT [FK_CNF_FlexContractFee_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_FlexContractFee_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_FlexContractFee 
  ADD CONSTRAINT [FK_CNF_FlexContractFee_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_FlexPlanTemplate'))
BEGIN
  Alter Table CNF_FlexPlanTemplate
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_FlexPlanTemplate_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_FlexPlanTemplate
  ADD CONSTRAINT [FK_CNF_FlexPlanTemplate_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_FlexPlanTemplate_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_FlexPlanTemplate 
  ADD CONSTRAINT [FK_CNF_FlexPlanTemplate_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_FundCash'))
BEGIN
  Alter Table CNF_FundCash
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_FundCash_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_FundCash
  ADD CONSTRAINT [FK_CNF_FundCash_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_FundCash_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_FundCash 
  ADD CONSTRAINT [FK_CNF_FundCash_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_FundItem'))
BEGIN
  Alter Table CNF_FundItem
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_FundItem_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_FundItem
  ADD CONSTRAINT [FK_CNF_FundItem_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_FundItem_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_FundItem 
  ADD CONSTRAINT [FK_CNF_FundItem_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_FundType'))
BEGIN
  Alter Table CNF_FundType
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_FundType_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_FundType
  ADD CONSTRAINT [FK_CNF_FundType_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_FundType_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_FundType 
  ADD CONSTRAINT [FK_CNF_FundType_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_Geo'))
BEGIN
  Alter Table CNF_Geo
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Geo_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_Geo
  ADD CONSTRAINT [FK_CNF_Geo_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Geo_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_Geo 
  ADD CONSTRAINT [FK_CNF_Geo_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_ImportMatch'))
BEGIN
  Alter Table CNF_ImportMatch
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_ImportMatch_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_ImportMatch
  ADD CONSTRAINT [FK_CNF_ImportMatch_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_ImportMatch_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_ImportMatch 
  ADD CONSTRAINT [FK_CNF_ImportMatch_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_IncentiveTicket'))
BEGIN
  Alter Table CNF_IncentiveTicket
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_IncentiveTicket_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_IncentiveTicket
  ADD CONSTRAINT [FK_CNF_IncentiveTicket_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_IncentiveTicket_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_IncentiveTicket 
  ADD CONSTRAINT [FK_CNF_IncentiveTicket_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_Invoice'))
BEGIN
  Alter Table CNF_Invoice
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Invoice_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_Invoice
  ADD CONSTRAINT [FK_CNF_Invoice_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Invoice_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_Invoice 
  ADD CONSTRAINT [FK_CNF_Invoice_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_Language'))
BEGIN
  Alter Table CNF_Language
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Language_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_Language
  ADD CONSTRAINT [FK_CNF_Language_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Language_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_Language 
  ADD CONSTRAINT [FK_CNF_Language_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_LedgerAccount'))
BEGIN
  Alter Table CNF_LedgerAccount
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_LedgerAccount_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_LedgerAccount
  ADD CONSTRAINT [FK_CNF_LedgerAccount_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_LedgerAccount_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_LedgerAccount 
  ADD CONSTRAINT [FK_CNF_LedgerAccount_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_License'))
BEGIN
  Alter Table CNF_License
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_License_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_License
  ADD CONSTRAINT [FK_CNF_License_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_License_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_License 
  ADD CONSTRAINT [FK_CNF_License_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_Location'))
BEGIN
  Alter Table CNF_Location
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Location_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_Location
  ADD CONSTRAINT [FK_CNF_Location_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Location_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_Location 
  ADD CONSTRAINT [FK_CNF_Location_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_LocationMatrix'))
BEGIN
  Alter Table CNF_LocationMatrix
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_LocationMatrix_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_LocationMatrix
  ADD CONSTRAINT [FK_CNF_LocationMatrix_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_LocationMatrix_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_LocationMatrix 
  ADD CONSTRAINT [FK_CNF_LocationMatrix_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_MapView'))
BEGIN
  Alter Table CNF_MapView
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_MapView_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_MapView
  ADD CONSTRAINT [FK_CNF_MapView_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_MapView_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_MapView 
  ADD CONSTRAINT [FK_CNF_MapView_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_Mask'))
BEGIN
  Alter Table CNF_Mask
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Mask_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_Mask
  ADD CONSTRAINT [FK_CNF_Mask_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Mask_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_Mask 
  ADD CONSTRAINT [FK_CNF_Mask_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_Mask_Utility'))
BEGIN
  Alter Table CNF_Mask_Utility
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Mask_Utility_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_Mask_Utility
  ADD CONSTRAINT [FK_CNF_Mask_Utility_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Mask_Utility_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_Mask_Utility 
  ADD CONSTRAINT [FK_CNF_Mask_Utility_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_MaskTable'))
BEGIN
  Alter Table CNF_MaskTable
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_MaskTable_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_MaskTable
  ADD CONSTRAINT [FK_CNF_MaskTable_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_MaskTable_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_MaskTable 
  ADD CONSTRAINT [FK_CNF_MaskTable_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_MaskTableItem'))
BEGIN
  Alter Table CNF_MaskTableItem
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_MaskTableItem_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_MaskTableItem
  ADD CONSTRAINT [FK_CNF_MaskTableItem_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_MaskTableItem_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_MaskTableItem 
  ADD CONSTRAINT [FK_CNF_MaskTableItem_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_MaskTableItem_Translation'))
BEGIN
  Alter Table CNF_MaskTableItem_Translation
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_MaskTableItem_Translation_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_MaskTableItem_Translation
  ADD CONSTRAINT [FK_CNF_MaskTableItem_Translation_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_MaskTableItem_Translation_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_MaskTableItem_Translation 
  ADD CONSTRAINT [FK_CNF_MaskTableItem_Translation_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_MatrixCell'))
BEGIN
  Alter Table CNF_MatrixCell
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_MatrixCell_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_MatrixCell
  ADD CONSTRAINT [FK_CNF_MatrixCell_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_MatrixCell_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_MatrixCell 
  ADD CONSTRAINT [FK_CNF_MatrixCell_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_MatrixCell_QuickUpgrade'))
BEGIN
  Alter Table CNF_MatrixCell_QuickUpgrade
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_MatrixCell_QuickUpgrade_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_MatrixCell_QuickUpgrade
  ADD CONSTRAINT [FK_CNF_MatrixCell_QuickUpgrade_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_MatrixCell_QuickUpgrade_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_MatrixCell_QuickUpgrade 
  ADD CONSTRAINT [FK_CNF_MatrixCell_QuickUpgrade_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_MatrixCell_Renew'))
BEGIN
  Alter Table CNF_MatrixCell_Renew
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_MatrixCell_Renew_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_MatrixCell_Renew
  ADD CONSTRAINT [FK_CNF_MatrixCell_Renew_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_MatrixCell_Renew_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_MatrixCell_Renew 
  ADD CONSTRAINT [FK_CNF_MatrixCell_Renew_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_MatrixCell2Delivery'))
BEGIN
  Alter Table CNF_MatrixCell2Delivery
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_MatrixCell2Delivery_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_MatrixCell2Delivery
  ADD CONSTRAINT [FK_CNF_MatrixCell2Delivery_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_MatrixCell2Delivery_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_MatrixCell2Delivery 
  ADD CONSTRAINT [FK_CNF_MatrixCell2Delivery_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_MatrixCell2FlexContract'))
BEGIN
  Alter Table CNF_MatrixCell2FlexContract
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_MatrixCell2FlexContract_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_MatrixCell2FlexContract
  ADD CONSTRAINT [FK_CNF_MatrixCell2FlexContract_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_MatrixCell2FlexContract_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_MatrixCell2FlexContract 
  ADD CONSTRAINT [FK_CNF_MatrixCell2FlexContract_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_MatrixCellInfo'))
BEGIN
  Alter Table CNF_MatrixCellInfo
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_MatrixCellInfo_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_MatrixCellInfo
  ADD CONSTRAINT [FK_CNF_MatrixCellInfo_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_MatrixCellInfo_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_MatrixCellInfo 
  ADD CONSTRAINT [FK_CNF_MatrixCellInfo_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_MatrixCellPermission'))
BEGIN
  Alter Table CNF_MatrixCellPermission
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_MatrixCellPermission_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_MatrixCellPermission
  ADD CONSTRAINT [FK_CNF_MatrixCellPermission_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_MatrixCellPermission_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_MatrixCellPermission 
  ADD CONSTRAINT [FK_CNF_MatrixCellPermission_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_MatrixCellTranslation'))
BEGIN
  Alter Table CNF_MatrixCellTranslation
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_MatrixCellTranslation_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_MatrixCellTranslation
  ADD CONSTRAINT [FK_CNF_MatrixCellTranslation_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_MatrixCellTranslation_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_MatrixCellTranslation 
  ADD CONSTRAINT [FK_CNF_MatrixCellTranslation_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_MatrixDimension'))
BEGIN
  Alter Table CNF_MatrixDimension
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_MatrixDimension_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_MatrixDimension
  ADD CONSTRAINT [FK_CNF_MatrixDimension_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_MatrixDimension_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_MatrixDimension 
  ADD CONSTRAINT [FK_CNF_MatrixDimension_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_MatrixSheet'))
BEGIN
  Alter Table CNF_MatrixSheet
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_MatrixSheet_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_MatrixSheet
  ADD CONSTRAINT [FK_CNF_MatrixSheet_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_MatrixSheet_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_MatrixSheet 
  ADD CONSTRAINT [FK_CNF_MatrixSheet_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_MatrixSheet_SaleValidity'))
BEGIN
  Alter Table CNF_MatrixSheet_SaleValidity
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_MatrixSheet_SaleValidity_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_MatrixSheet_SaleValidity
  ADD CONSTRAINT [FK_CNF_MatrixSheet_SaleValidity_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_MatrixSheet_SaleValidity_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_MatrixSheet_SaleValidity 
  ADD CONSTRAINT [FK_CNF_MatrixSheet_SaleValidity_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_MembershipCard'))
BEGIN
  Alter Table CNF_MembershipCard
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_MembershipCard_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_MembershipCard
  ADD CONSTRAINT [FK_CNF_MembershipCard_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_MembershipCard_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_MembershipCard 
  ADD CONSTRAINT [FK_CNF_MembershipCard_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_Merchant'))
BEGIN
  Alter Table CNF_Merchant
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Merchant_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_Merchant
  ADD CONSTRAINT [FK_CNF_Merchant_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Merchant_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_Merchant 
  ADD CONSTRAINT [FK_CNF_Merchant_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_MerchantTable'))
BEGIN
  Alter Table CNF_MerchantTable
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_MerchantTable_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_MerchantTable
  ADD CONSTRAINT [FK_CNF_MerchantTable_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_MerchantTable_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_MerchantTable 
  ADD CONSTRAINT [FK_CNF_MerchantTable_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_MultiLanguage'))
BEGIN
  Alter Table CNF_MultiLanguage
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_MultiLanguage_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_MultiLanguage
  ADD CONSTRAINT [FK_CNF_MultiLanguage_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_MultiLanguage_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_MultiLanguage 
  ADD CONSTRAINT [FK_CNF_MultiLanguage_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_Notification'))
BEGIN
  Alter Table CNF_Notification
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Notification_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_Notification
  ADD CONSTRAINT [FK_CNF_Notification_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Notification_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_Notification 
  ADD CONSTRAINT [FK_CNF_Notification_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_OperatingArea'))
BEGIN
  Alter Table CNF_OperatingArea
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_OperatingArea_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_OperatingArea
  ADD CONSTRAINT [FK_CNF_OperatingArea_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_OperatingArea_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_OperatingArea 
  ADD CONSTRAINT [FK_CNF_OperatingArea_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_PAY'))
BEGIN
  Alter Table CNF_PAY
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_PAY_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_PAY
  ADD CONSTRAINT [FK_CNF_PAY_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_PAY_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_PAY 
  ADD CONSTRAINT [FK_CNF_PAY_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_Pay_MatrixCell'))
BEGIN
  Alter Table CNF_Pay_MatrixCell
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Pay_MatrixCell_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_Pay_MatrixCell
  ADD CONSTRAINT [FK_CNF_Pay_MatrixCell_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Pay_MatrixCell_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_Pay_MatrixCell 
  ADD CONSTRAINT [FK_CNF_Pay_MatrixCell_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_PaymentCard'))
BEGIN
  Alter Table CNF_PaymentCard
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_PaymentCard_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_PaymentCard
  ADD CONSTRAINT [FK_CNF_PaymentCard_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_PaymentCard_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_PaymentCard 
  ADD CONSTRAINT [FK_CNF_PaymentCard_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_PaymentCardCode'))
BEGIN
  Alter Table CNF_PaymentCardCode
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_PaymentCardCode_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_PaymentCardCode
  ADD CONSTRAINT [FK_CNF_PaymentCardCode_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_PaymentCardCode_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_PaymentCardCode 
  ADD CONSTRAINT [FK_CNF_PaymentCardCode_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_PaymentCardRange'))
BEGIN
  Alter Table CNF_PaymentCardRange
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_PaymentCardRange_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_PaymentCardRange
  ADD CONSTRAINT [FK_CNF_PaymentCardRange_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_PaymentCardRange_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_PaymentCardRange 
  ADD CONSTRAINT [FK_CNF_PaymentCardRange_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_PaymentMethod'))
BEGIN
  Alter Table CNF_PaymentMethod
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_PaymentMethod_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_PaymentMethod
  ADD CONSTRAINT [FK_CNF_PaymentMethod_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_PaymentMethod_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_PaymentMethod 
  ADD CONSTRAINT [FK_CNF_PaymentMethod_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>scoluccia</ADDEDBY><SQLVERSION>2439</SQLVERSION><RMTRACKLINK>78902</RMTRACKLINK><REASON>0)ADD HideItemPrice to CNF_Promotion
1)ADD HideItemPrice to DATA_SaleItemRule

</REASON><TABLENAMES>CNF_Promotion=PromotionId
DATA_SaleItemRule=SaleItemRuleId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'HideItemPrice' AND
                Object_ID  = Object_ID(N'CNF_Promotion'))
BEGIN
  ALTER TABLE CNF_Promotion 
  ADD [HideItemPrice] [smallint] NULL
END

</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'HideItemPrice' AND
                Object_ID  = Object_ID(N'DATA_SaleItemRule'))
BEGIN
  ALTER TABLE DATA_SaleItemRule 
  ADD [HideItemPrice] [smallint] NULL
END
</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>2438</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>3 new fields added to 48 tables:
1) Last_UserId_Log
2)Last_WorkstationId_Log
3)Last_DateTime_Log</REASON><TABLENAMES>CNF_Category=CategoryId
CNF_Category2Product=Category2ProductId
CNF_CC2OperatingArea=CC2OperatingAreaId
CNF_Combo=ComboId
CNF_Commission2Account=Commission2AccountId
CNF_CostCenter=CostCenterId
CNF_CostCenter_Validity=CostCenterValidityId
CNF_CRMTemplate=CRMTemplateId
CNF_CRMTemplateDetail=CRMTemplateDetailId
CNF_Currency=CurrencyId
CNF_CurrencyDetail=CurrencyDetailId
CNF_CustomColor=CustomColorId
CNF_DataMask=DataMaskId
CNF_DataMaskTranslation=DataMaskTranslationId
CNF_DBInfo=DBInfoId
CNF_Delivery=DeliveryId
CNF_Delivery_Permission=DeliveryPermissionId
CNF_Delivery2Entity=Delivery2EntityId
CNF_DeliveryMode=DeliveryModeId
CNF_Device=DeviceId
CNF_DmgCategory=DmgCategoryId
CNF_DmgCategory_Permission=DmgCategoryPermissionId
CNF_DmgCategory2CRMTemplate=DmgCategory2CRMTemplateId
CNF_DmgCategory2Mask=DmgCategory2MaskId
CNF_DocRepository=DocRepositoryId
CNF_DocTemplate=DocTemplateId
CNF_DocTemplate_Permission=DocTemplatePermissionId
CNF_DocTemplate2Device=DocTemplate2DeviceId
CNF_DocTemplate2IdentifierType=DocTemplate2IdentifierTypeId
CNF_DocTemplateParam=DocTemplateParamId
CNF_DocTemplateParamValue=DocTemplateParamValueId
CNF_DonationForm=DonationFormId
CNF_Driver=DriverId
CNF_Entity=EntityId
CNF_Entity2Attribute=Entity2AttributeId
CNF_Envelope=EnvelopeId
CNF_Envelope_Permission=EnvelopePermissionId
CNF_EnvelopeCapacity=EnvelopeCapacityId
CNF_EnvelopeRight=EnvelopeRightId
CNF_Event=EventId
CNF_Event_Permission=EventPermissionId
CNF_EventFilter=EventFilterId
CNF_ExchangeRate=ExchangeRateId
CNF_ExtCardTypePermission=ExtCardTypePermissionId
CNF_ExternalCardType=ExternalCardTypeId
CNF_ExternalMediaType=ExternalMediaTypeId
CNF_ExternalStoredInfo=ExternalMediaTypeId
CNF_ExternalTicketRange=ExternalTicketRangeId
</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_Category'))
BEGIN
  Alter Table CNF_Category
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Category_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_Category
  ADD CONSTRAINT [FK_CNF_Category_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Category_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_Category 
  ADD CONSTRAINT [FK_CNF_Category_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_Category2Product'))
BEGIN
  Alter Table CNF_Category2Product
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Category2Product_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_Category2Product
  ADD CONSTRAINT [FK_CNF_Category2Product_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Category2Product_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_Category2Product 
  ADD CONSTRAINT [FK_CNF_Category2Product_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_CC2OperatingArea'))
BEGIN
  Alter Table CNF_CC2OperatingArea
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_CC2OperatingArea_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_CC2OperatingArea
  ADD CONSTRAINT [FK_CNF_CC2OperatingArea_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_CC2OperatingArea_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_CC2OperatingArea
  ADD CONSTRAINT [FK_CNF_CC2OperatingArea_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_Combo'))
BEGIN
  Alter Table CNF_Combo
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Combo_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_Combo
  ADD CONSTRAINT [FK_CNF_Combo_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Combo_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_Combo 
  ADD CONSTRAINT [FK_CNF_Combo_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_Commission2Account'))
BEGIN
  Alter Table CNF_Commission2Account
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Commission2Account_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_Commission2Account
  ADD CONSTRAINT [FK_CNF_Commission2Account_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Commission2Account_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_Commission2Account 
  ADD CONSTRAINT [FK_CNF_Commission2Account_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_CostCenter'))
BEGIN
  Alter Table CNF_CostCenter
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_CostCenter_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_CostCenter
  ADD CONSTRAINT [FK_CNF_CostCenter_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_CostCenter_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_CostCenter 
  ADD CONSTRAINT [FK_CNF_CostCenter_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_CostCenter_Validity'))
BEGIN
  Alter Table CNF_CostCenter_Validity
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_CostCenter_Validity_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_CostCenter_Validity
  ADD CONSTRAINT [FK_CNF_CostCenter_Validity_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_CostCenter_Validity_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_CostCenter_Validity 
  ADD CONSTRAINT [FK_CNF_CostCenter_Validity_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_CRMTemplate'))
BEGIN
  Alter Table CNF_CRMTemplate
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_CRMTemplate_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_CRMTemplate
  ADD CONSTRAINT [FK_CNF_CRMTemplate_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_CRMTemplate_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_CRMTemplate 
  ADD CONSTRAINT [FK_CNF_CRMTemplate_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_CRMTemplateDetail'))
BEGIN
  Alter Table CNF_CRMTemplateDetail
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_CRMTemplateDetail_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_CRMTemplateDetail
  ADD CONSTRAINT [FK_CNF_CRMTemplateDetail_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_CRMTemplateDetail_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_CRMTemplateDetail 
  ADD CONSTRAINT [FK_CNF_CRMTemplateDetail_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_Currency'))
BEGIN
  Alter Table CNF_Currency
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Currency_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_Currency
  ADD CONSTRAINT [FK_CNF_Currency_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Currency_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_Currency 
  ADD CONSTRAINT [FK_CNF_Currency_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_CurrencyDetail'))
BEGIN
  Alter Table CNF_CurrencyDetail
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_CurrencyDetail_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_CurrencyDetail
  ADD CONSTRAINT [FK_CNF_CurrencyDetail_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_CurrencyDetail_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_CurrencyDetail 
  ADD CONSTRAINT [FK_CNF_CurrencyDetail_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_CustomColor'))
BEGIN
  Alter Table CNF_CustomColor
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_CustomColor_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_CustomColor
  ADD CONSTRAINT [FK_CNF_CustomColor_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_CustomColor_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_CustomColor 
  ADD CONSTRAINT [FK_CNF_CustomColor_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_DataMask'))
BEGIN
  Alter Table CNF_DataMask
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DataMask_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_DataMask
  ADD CONSTRAINT [FK_CNF_DataMask_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DataMask_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_DataMask 
  ADD CONSTRAINT [FK_CNF_DataMask_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_DataMaskTranslation'))
BEGIN
  Alter Table CNF_DataMaskTranslation
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DataMaskTranslation_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_DataMaskTranslation
  ADD CONSTRAINT [FK_CNF_DataMaskTranslation_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DataMaskTranslation_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_DataMaskTranslation 
  ADD CONSTRAINT [FK_CNF_DataMaskTranslation_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_DBInfo'))
BEGIN
  Alter Table CNF_DBInfo
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DBInfo_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_DBInfo
  ADD CONSTRAINT [FK_CNF_DBInfo_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DBInfo_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_DBInfo 
  ADD CONSTRAINT [FK_CNF_DBInfo_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_Delivery'))
BEGIN
  Alter Table CNF_Delivery
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Delivery_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_Delivery
  ADD CONSTRAINT [FK_CNF_Delivery_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Delivery_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_Delivery 
  ADD CONSTRAINT [FK_CNF_Delivery_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_Delivery_Permission'))
BEGIN
  Alter Table CNF_Delivery_Permission
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Delivery_Permission_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_Delivery_Permission
  ADD CONSTRAINT [FK_CNF_Delivery_Permission_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Delivery_Permission_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_Delivery_Permission 
  ADD CONSTRAINT [FK_CNF_Delivery_Permission_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_Delivery2Entity'))
BEGIN
  Alter Table CNF_Delivery2Entity
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Delivery2Entity_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_Delivery2Entity
  ADD CONSTRAINT [FK_CNF_Delivery2Entity_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Delivery2Entity_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_Delivery2Entity 
  ADD CONSTRAINT [FK_CNF_Delivery2Entity_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_DeliveryMode'))
BEGIN
  Alter Table CNF_DeliveryMode
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DeliveryMode_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_DeliveryMode
  ADD CONSTRAINT [FK_CNF_DeliveryMode_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DeliveryMode_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_DeliveryMode 
  ADD CONSTRAINT [FK_CNF_DeliveryMode_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_Device'))
BEGIN
  Alter Table CNF_Device
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Device_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_Device
  ADD CONSTRAINT [FK_CNF_Device_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Device_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_Device 
  ADD CONSTRAINT [FK_CNF_Device_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_DmgCategory'))
BEGIN
  Alter Table CNF_DmgCategory
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DmgCategory_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_DmgCategory
  ADD CONSTRAINT [FK_CNF_DmgCategory_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DmgCategory_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_DmgCategory 
  ADD CONSTRAINT [FK_CNF_DmgCategory_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_DmgCategory_Permission'))
BEGIN
  Alter Table CNF_DmgCategory_Permission
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DmgCategory_Permission_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_DmgCategory_Permission
  ADD CONSTRAINT [FK_CNF_DmgCategory_Permission_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DmgCategory_Permission_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_DmgCategory_Permission 
  ADD CONSTRAINT [FK_CNF_DmgCategory_Permission_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_DmgCategory2CRMTemplate'))
BEGIN
  Alter Table CNF_DmgCategory2CRMTemplate
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DmgCategory2CRMTemplate_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_DmgCategory2CRMTemplate
  ADD CONSTRAINT [FK_CNF_DmgCategory2CRMTemplate_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DmgCategory2CRMTemplate_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_DmgCategory2CRMTemplate 
  ADD CONSTRAINT [FK_CNF_DmgCategory2CRMTemplate_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_DmgCategory2Mask'))
BEGIN
  Alter Table CNF_DmgCategory2Mask
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DmgCategory2Mask_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_DmgCategory2Mask
  ADD CONSTRAINT [FK_CNF_DmgCategory2Mask_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DmgCategory2Mask_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_DmgCategory2Mask 
  ADD CONSTRAINT [FK_CNF_DmgCategory2Mask_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_DocRepository'))
BEGIN
  Alter Table CNF_DocRepository
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DocRepository_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_DocRepository
  ADD CONSTRAINT [FK_CNF_DocRepository_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DocRepository_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_DocRepository 
  ADD CONSTRAINT [FK_CNF_DocRepository_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_DocTemplate'))
BEGIN
  Alter Table CNF_DocTemplate
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DocTemplate_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_DocTemplate
  ADD CONSTRAINT [FK_CNF_DocTemplate_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DocTemplate_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_DocTemplate 
  ADD CONSTRAINT [FK_CNF_DocTemplate_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_DocTemplate_Permission'))
BEGIN
  Alter Table CNF_DocTemplate_Permission
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DocTemplate_Permission_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_DocTemplate_Permission
  ADD CONSTRAINT [FK_CNF_DocTemplate_Permission_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DocTemplate_Permission_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_DocTemplate_Permission 
  ADD CONSTRAINT [FK_CNF_DocTemplate_Permission_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_DocTemplate2Device'))
BEGIN
  Alter Table CNF_DocTemplate2Device
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DocTemplate2Device_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_DocTemplate2Device
  ADD CONSTRAINT [FK_CNF_DocTemplate2Device_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DocTemplate2Device_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_DocTemplate2Device 
  ADD CONSTRAINT [FK_CNF_DocTemplate2Device_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_DocTemplate2IdentifierType'))
BEGIN
  Alter Table CNF_DocTemplate2IdentifierType
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DocTemplate2IdentifierType_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_DocTemplate2IdentifierType
  ADD CONSTRAINT [FK_CNF_DocTemplate2IdentifierType_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DocTemplate2IdentifierType_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_DocTemplate2IdentifierType 
  ADD CONSTRAINT [FK_CNF_DocTemplate2IdentifierType_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_DocTemplateParam'))
BEGIN
  Alter Table CNF_DocTemplateParam
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DocTemplateParam_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_DocTemplateParam
  ADD CONSTRAINT [FK_CNF_DocTemplateParam_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DocTemplateParam_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_DocTemplateParam 
  ADD CONSTRAINT [FK_CNF_DocTemplateParam_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_DocTemplateParamValue'))
BEGIN
  Alter Table CNF_DocTemplateParamValue
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DocTemplateParamValue_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_DocTemplateParamValue
  ADD CONSTRAINT [FK_CNF_DocTemplateParamValue_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DocTemplateParamValue_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_DocTemplateParamValue 
  ADD CONSTRAINT [FK_CNF_DocTemplateParamValue_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_DonationForm'))
BEGIN
  Alter Table CNF_DonationForm
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DonationForm_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_DonationForm
  ADD CONSTRAINT [FK_CNF_DonationForm_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DonationForm_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_DonationForm 
  ADD CONSTRAINT [FK_CNF_DonationForm_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_Driver'))
BEGIN
  Alter Table CNF_Driver
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Driver_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_Driver
  ADD CONSTRAINT [FK_CNF_Driver_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Driver_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_Driver 
  ADD CONSTRAINT [FK_CNF_Driver_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_Entity'))
BEGIN
  Alter Table CNF_Entity
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Entity_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_Entity
  ADD CONSTRAINT [FK_CNF_Entity_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Entity_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_Entity 
  ADD CONSTRAINT [FK_CNF_Entity_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_Entity2Attribute'))
BEGIN
  Alter Table CNF_Entity2Attribute
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Entity2Attribute_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_Entity2Attribute
  ADD CONSTRAINT [FK_CNF_Entity2Attribute_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Entity2Attribute_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_Entity2Attribute 
  ADD CONSTRAINT [FK_CNF_Entity2Attribute_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_Envelope'))
BEGIN
  Alter Table CNF_Envelope
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Envelope_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_Envelope
  ADD CONSTRAINT [FK_CNF_Envelope_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Envelope_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_Envelope 
  ADD CONSTRAINT [FK_CNF_Envelope_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_Envelope_Permission'))
BEGIN
  Alter Table CNF_Envelope_Permission
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Envelope_Permission_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_Envelope_Permission
  ADD CONSTRAINT [FK_CNF_Envelope_Permission_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Envelope_Permission_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_Envelope_Permission 
  ADD CONSTRAINT [FK_CNF_Envelope_Permission_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_EnvelopeCapacity'))
BEGIN
  Alter Table CNF_EnvelopeCapacity
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_EnvelopeCapacity_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_EnvelopeCapacity
  ADD CONSTRAINT [FK_CNF_EnvelopeCapacity_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_EnvelopeCapacity_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_EnvelopeCapacity 
  ADD CONSTRAINT [FK_CNF_EnvelopeCapacity_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_EnvelopeRight'))
BEGIN
  Alter Table CNF_EnvelopeRight
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_EnvelopeRight_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_EnvelopeRight
  ADD CONSTRAINT [FK_CNF_EnvelopeRight_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_EnvelopeRight_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_EnvelopeRight 
  ADD CONSTRAINT [FK_CNF_EnvelopeRight_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_Event'))
BEGIN
  Alter Table CNF_Event
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Event_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_Event
  ADD CONSTRAINT [FK_CNF_Event_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Event_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_Event 
  ADD CONSTRAINT [FK_CNF_Event_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_Event_Permission'))
BEGIN
  Alter Table CNF_Event_Permission
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Event_Permission_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_Event_Permission
  ADD CONSTRAINT [FK_CNF_Event_Permission_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Event_Permission_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_Event_Permission 
  ADD CONSTRAINT [FK_CNF_Event_Permission_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_EventFilter'))
BEGIN
  Alter Table CNF_EventFilter
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_EventFilter_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_EventFilter
  ADD CONSTRAINT [FK_CNF_EventFilter_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_EventFilter_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_EventFilter 
  ADD CONSTRAINT [FK_CNF_EventFilter_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_ExchangeRate'))
BEGIN
  Alter Table CNF_ExchangeRate
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_ExchangeRate_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_ExchangeRate
  ADD CONSTRAINT [FK_CNF_ExchangeRate_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_ExchangeRate_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_ExchangeRate 
  ADD CONSTRAINT [FK_CNF_ExchangeRate_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_ExtCardTypePermission'))
BEGIN
  Alter Table CNF_ExtCardTypePermission
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_ExtCardTypePermission_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_ExtCardTypePermission
  ADD CONSTRAINT [FK_CNF_ExtCardTypePermission_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_ExtCardTypePermission_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_ExtCardTypePermission 
  ADD CONSTRAINT [FK_CNF_ExtCardTypePermission_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_ExternalCardType'))
BEGIN
  Alter Table CNF_ExternalCardType
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_ExternalCardType_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_ExternalCardType
  ADD CONSTRAINT [FK_CNF_ExternalCardType_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_ExternalCardType_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_ExternalCardType 
  ADD CONSTRAINT [FK_CNF_ExternalCardType_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_ExternalMediaType'))
BEGIN
  Alter Table CNF_ExternalMediaType
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_ExternalMediaType_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_ExternalMediaType
  ADD CONSTRAINT [FK_CNF_ExternalMediaType_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_ExternalMediaType_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_ExternalMediaType 
  ADD CONSTRAINT [FK_CNF_ExternalMediaType_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_ExternalStoredInfo'))
BEGIN
  Alter Table CNF_ExternalStoredInfo
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_ExternalStoredInfo_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_ExternalStoredInfo
  ADD CONSTRAINT [FK_CNF_ExternalStoredInfo_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_ExternalStoredInfo_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_ExternalStoredInfo 
  ADD CONSTRAINT [FK_CNF_ExternalStoredInfo_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_ExternalTicketRange'))
BEGIN
  Alter Table CNF_ExternalTicketRange
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_ExternalTicketRange_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_ExternalTicketRange
  ADD CONSTRAINT [FK_CNF_ExternalTicketRange_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_ExternalTicketRange_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_ExternalTicketRange 
  ADD CONSTRAINT [FK_CNF_ExternalTicketRange_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>2437</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>3 new fields added to 24 tables:
1) Last_UserId_Log
2)Last_WorkstationId_Log
3)Last_DateTime_Log</REASON><TABLENAMES>ADM_AccessConfiguration=AccessConfigurationId
ADM_AccessPoint=WorkstationId
ADM_Gate=GateId
ADM_Gate2AccessConfiguration=Gate2AccessConfigurationId
ARC_Document=DocumentId
ARC_Index=IndexId
CNF_AccessFilter=AccessFilterId
CNF_AlternativeCodes=AlternativeCodesId
CNF_Attribute=AttributeId
CNF_Attribute_SaleValidity=AttributeSaleValidityId
CNF_AttributeSet=AttributeSetId
CNF_AttributeSetDetail=AttributeSetDetail
CNF_AttributeTemplate=AttributeTemplateId
CNF_BoardFav=BoardFavId
CNF_BoardPackage=BoardPackageId
CNF_Calendar=CalendarId
CNF_CalendarTimeFrame=TimeFrameId
CNF_CalendarTimeFrameItem=TimeFrameItemId
CNF_CalendarValidity=CalendarValidityId
CNF_Capacity=CapacityId
CNF_Card=ProductId
CNF_CardBonus=ProductId
CNF_Catalog=CatalogId
CNF_Catalog2Product=Catalog2ProductId
</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'ADM_AccessConfiguration'))
BEGIN
  Alter Table ADM_AccessConfiguration
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_ADM_AccessConfiguration_Last_UserId_Log')
BEGIN
  ALTER TABLE ADM_AccessConfiguration 
  ADD CONSTRAINT [FK_ADM_AccessConfiguration_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_ADM_AccessConfiguration_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE ADM_AccessConfiguration 
  ADD CONSTRAINT [FK_ADM_AccessConfiguration_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'ADM_AccessPoint'))
BEGIN
  Alter Table ADM_AccessPoint
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_ADM_AccessPoint_Last_UserId_Log')
BEGIN
  ALTER TABLE ADM_AccessPoint
  ADD CONSTRAINT [FK_ADM_AccessPoint_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_ADM_AccessPoint_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE ADM_AccessPoint 
  ADD CONSTRAINT [FK_ADM_AccessPoint_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'ADM_Gate'))
BEGIN
  Alter Table ADM_Gate
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_ADM_Gate_Last_UserId_Log')
BEGIN
  ALTER TABLE ADM_Gate
  ADD CONSTRAINT [FK_ADM_Gate_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_ADM_Gate_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE ADM_Gate
  ADD CONSTRAINT [FK_ADM_Gate_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'ADM_Gate2AccessConfiguration'))
BEGIN
  Alter Table ADM_Gate2AccessConfiguration
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_ADM_Gate2AccessConfiguration_Last_UserId_Log')
BEGIN
  ALTER TABLE ADM_Gate2AccessConfiguration
  ADD CONSTRAINT [FK_ADM_Gate2AccessConfiguration_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_ADM_Gate2AccessConfiguration_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE ADM_Gate2AccessConfiguration 
  ADD CONSTRAINT [FK_ADM_Gate2AccessConfiguration_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'ARC_Document'))
BEGIN
  Alter Table ARC_Document
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_ARC_Document_Last_UserId_Log')
BEGIN
  ALTER TABLE ARC_Document
  ADD CONSTRAINT [FK_ARC_Document_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_ARC_Document_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE ARC_Document 
  ADD CONSTRAINT [FK_ARC_Document_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'ARC_Index'))
BEGIN
  Alter Table ARC_Index
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_ARC_Index_Last_UserId_Log')
BEGIN
  ALTER TABLE ARC_Index
  ADD CONSTRAINT [FK_ARC_Index_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_ARC_Index_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE ARC_Index 
  ADD CONSTRAINT [FK_ARC_Index_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_AccessFilter'))
BEGIN
  Alter Table CNF_AccessFilter
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_AccessFilter_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_AccessFilter
  ADD CONSTRAINT [FK_CNF_AccessFilter_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_AccessFilter_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_AccessFilter 
  ADD CONSTRAINT [FK_CNF_AccessFilter_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_AlternativeCodes'))
BEGIN
  Alter Table CNF_AlternativeCodes
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_AlternativeCodes_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_AlternativeCodes
  ADD CONSTRAINT [FK_CNF_AlternativeCodes_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_AlternativeCodes_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_AlternativeCodes 
  ADD CONSTRAINT [FK_CNF_AlternativeCodes_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_Attribute'))
BEGIN
  Alter Table CNF_Attribute
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Attribute_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_Attribute
  ADD CONSTRAINT [FK_CNF_Attribute_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Attribute_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_Attribute 
  ADD CONSTRAINT [FK_CNF_Attribute_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_Attribute_SaleValidity'))
BEGIN
  Alter Table CNF_Attribute_SaleValidity
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Attribute_SaleValidity_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_Attribute_SaleValidity
  ADD CONSTRAINT [FK_CNF_Attribute_SaleValidity_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Attribute_SaleValidity_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_Attribute_SaleValidity 
  ADD CONSTRAINT [FK_CNF_Attribute_SaleValidity_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_AttributeSet'))
BEGIN
  Alter Table CNF_AttributeSet
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_AttributeSet_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_AttributeSet
  ADD CONSTRAINT [FK_CNF_AttributeSet_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_AttributeSet_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_AttributeSet 
  ADD CONSTRAINT [FK_CNF_AttributeSet_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_AttributeSetDetail'))
BEGIN
  Alter Table CNF_AttributeSetDetail
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_AttributeSetDetail_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_AttributeSetDetail
  ADD CONSTRAINT [FK_CNF_AttributeSetDetail_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_AttributeSetDetail_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_AttributeSetDetail 
  ADD CONSTRAINT [FK_CNF_AttributeSetDetail_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_AttributeTemplate'))
BEGIN
  Alter Table CNF_AttributeTemplate
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_AttributeTemplate_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_AttributeTemplate
  ADD CONSTRAINT [FK_CNF_AttributeTemplate_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_AttributeTemplate_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_AttributeTemplate 
  ADD CONSTRAINT [FK_CNF_AttributeTemplate_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_BoardFav'))
BEGIN
  Alter Table CNF_BoardFav
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_BoardFav_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_BoardFav
  ADD CONSTRAINT [FK_CNF_BoardFav_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_BoardFav_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_BoardFav 
  ADD CONSTRAINT [FK_CNF_BoardFav_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_BoardPackage'))
BEGIN
  Alter Table CNF_BoardPackage
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_BoardPackage_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_BoardPackage
  ADD CONSTRAINT [FK_CNF_BoardPackage_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_BoardPackage_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_BoardPackage 
  ADD CONSTRAINT [FK_CNF_BoardPackage_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_Calendar'))
BEGIN
  Alter Table CNF_Calendar
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Calendar_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_Calendar
  ADD CONSTRAINT [FK_CNF_Calendar_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Calendar_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_Calendar 
  ADD CONSTRAINT [FK_CNF_Calendar_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_CalendarTimeFrame'))
BEGIN
  Alter Table CNF_CalendarTimeFrame
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_CalendarTimeFrame_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_CalendarTimeFrame
  ADD CONSTRAINT [FK_CNF_CalendarTimeFrame_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_CalendarTimeFrame_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_CalendarTimeFrame 
  ADD CONSTRAINT [FK_CNF_CalendarTimeFrame_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_CalendarTimeFrameItem'))
BEGIN
  Alter Table CNF_CalendarTimeFrameItem
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_CalendarTimeFrameItem_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_CalendarTimeFrameItem
  ADD CONSTRAINT [FK_CNF_CalendarTimeFrameItem_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_CalendarTimeFrameItem_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_CalendarTimeFrameItem 
  ADD CONSTRAINT [FK_CNF_CalendarTimeFrameItem_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_CalendarValidity'))
BEGIN
  Alter Table CNF_CalendarValidity
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_CalendarValidity_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_CalendarValidity
  ADD CONSTRAINT [FK_CNF_CalendarValidity_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_CalendarValidity_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_CalendarValidity 
  ADD CONSTRAINT [FK_CNF_CalendarValidity_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_Capacity'))
BEGIN
  Alter Table CNF_Capacity
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Capacity_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_Capacity
  ADD CONSTRAINT [FK_CNF_Capacity_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Capacity_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_Capacity 
  ADD CONSTRAINT [FK_CNF_Capacity_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_Card'))
BEGIN
  Alter Table CNF_Card
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Card_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_Card
  ADD CONSTRAINT [FK_CNF_Card_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Card_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_Card 
  ADD CONSTRAINT [FK_CNF_Card_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_CardBonus'))
BEGIN
  Alter Table CNF_CardBonus
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_CardBonus_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_CardBonus
  ADD CONSTRAINT [FK_CNF_CardBonus_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_CardBonus_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_CardBonus 
  ADD CONSTRAINT [FK_CNF_CardBonus_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_Catalog'))
BEGIN
  Alter Table CNF_Catalog
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Catalog_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_Catalog
  ADD CONSTRAINT [FK_CNF_Catalog_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Catalog_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_Catalog 
  ADD CONSTRAINT [FK_CNF_Catalog_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Last_UserId_Log' AND
                Object_ID  = Object_ID(N'CNF_Catalog2Product'))
BEGIN
  Alter Table CNF_Catalog2Product
  Add Last_UserId_Log Integer NULL,
	  Last_WorkstationId_Log Integer NULL,
	  Last_DateTime_Log Datetime NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Catalog2Product_Last_UserId_Log')
BEGIN
  ALTER TABLE CNF_Catalog2Product
  ADD CONSTRAINT [FK_CNF_Catalog2Product_Last_UserId_Log] FOREIGN KEY([Last_UserId_Log]) 
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Catalog2Product_Last_WorkstationId_Log')
BEGIN
  ALTER TABLE CNF_Catalog2Product 
  ADD CONSTRAINT [FK_CNF_Catalog2Product_Last_WorkstationId_Log] FOREIGN KEY([Last_WorkstationId_Log]) 
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dchen</ADDEDBY><SQLVERSION>2436</SQLVERSION><RMTRACKLINK>78730</RMTRACKLINK><REASON>Adding fields
	[UpgradePeriodEnabled] Smallint Default 0 NULL,
	[UpgradePeriodType] Smallint Default 0 NULL,
	[UpgradePeriodByDateFrom] Datetime NULL,
	[UpgradePeriodByDateTo] Datetime NULL,
	[UpgradePeriodByNumberDays] Smallint NULL,
</REASON><TABLENAMES>CNF_MatrixCellInfo=MatrixCellInfoId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'UpgradePeriodEnabled' AND
                Object_ID  = Object_ID(N'CNF_MatrixCellInfo'))
BEGIN
  ALTER TABLE CNF_MatrixCellInfo 
  ADD UpgradePeriodEnabled SmallInt Default 0 NULL
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'UpgradePeriodType' AND
                Object_ID  = Object_ID(N'CNF_MatrixCellInfo'))
BEGIN
  ALTER TABLE CNF_MatrixCellInfo 
  ADD UpgradePeriodType SmallInt Default 0 NULL
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'UpgradePeriodByDateFrom' AND
                Object_ID  = Object_ID(N'CNF_MatrixCellInfo'))
BEGIN
  ALTER TABLE CNF_MatrixCellInfo 
  ADD UpgradePeriodByDateFrom Datetime NULL
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'UpgradePeriodByDateTo' AND
                Object_ID  = Object_ID(N'CNF_MatrixCellInfo'))
BEGIN
  ALTER TABLE CNF_MatrixCellInfo 
  ADD UpgradePeriodByDateTo Datetime NULL
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'UpgradePeriodByNumberDays' AND
                Object_ID  = Object_ID(N'CNF_MatrixCellInfo'))
BEGIN
  ALTER TABLE CNF_MatrixCellInfo 
  ADD UpgradePeriodByNumberDays Smallint NULL
END
</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2435</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>0) Add SortOrder to ADM_Gate</REASON><TABLENAMES>ADM_Gate=GateId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'SortOrder' AND
                Object_ID  = Object_ID(N'ADM_Gate'))
BEGIN
  ALTER TABLE ADM_Gate ADD SortOrder int NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fesposito</ADDEDBY><SQLVERSION>2434</SQLVERSION><RMTRACKLINK>78899</RMTRACKLINK><REASON>Adding ShareableEntitlements to CNF_MatrixCell</REASON><TABLENAMES>CNF_MatrixCell=MatrixCellId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'ShareableEntitlements' AND
                Object_ID  = Object_ID(N'CNF_MatrixCell'))
BEGIN
  ALTER TABLE CNF_MatrixCell 
  ADD ShareableEntitlements SmallInt NULL
END
</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>2433</SQLVERSION><RMTRACKLINK>78925</RMTRACKLINK><REASON>Added new table DATA_History_Override
with FK WorkstationID, FK UserId, FK SupervisorUserId, and FK TransactionId</REASON><TABLENAMES>DATA_History_Override=HistoryOverrideId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'DATA_History_Override'))
                    
BEGIN
Create table [DATA_History_Override]
(
	[HistoryOverrideId] Integer Identity(1,1) NOT NULL,
	[WorkstationId] Integer NOT NULL,
	[UserId] Integer NOT NULL,
	[SupervisorUserId] Integer NOT NULL,
	[OverrideType] Smallint NOT NULL,
	[TransactionId] Integer NULL,
        [InsDateTime] Datetime NOT NULL,
Primary Key ([HistoryOverrideId])
) 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_History_Override_WorkstationId')
BEGIN
  ALTER TABLE DATA_History_Override
  ADD
  CONSTRAINT [FK_DATA_History_Override_WorkstationId] FOREIGN KEY([WorkstationId]) REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_History_Override_UserId')
BEGIN
  ALTER TABLE DATA_History_Override
  ADD
  CONSTRAINT [FK_DATA_History_Override_UserId] FOREIGN KEY([UserId]) REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_History_Override_SupervisorUserId')
BEGIN
  ALTER TABLE DATA_History_Override
  ADD
  CONSTRAINT [FK_DATA_History_Override_SupervisorUserId] FOREIGN KEY([SupervisorUserId]) REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_History_Override_TransactionId')
BEGIN
  ALTER TABLE DATA_History_Override
  ADD
  CONSTRAINT [FK_DATA_History_Override_TransactionId] FOREIGN KEY([TransactionId]) REFERENCES [DATA_Transaction] ([TransactionId])
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>scoluccia</ADDEDBY><SQLVERSION>2432</SQLVERSION><RMTRACKLINK>79146</RMTRACKLINK><REASON>0)ADD Description to DATA_SaleItemRule
1)ADD Code to DATA_SaleItemRule
2)ADD PromotionType to DATA_SaleItemRule</REASON><TABLENAMES>DATA_SaleItemRule=SaleItemRuleId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Description' AND
                Object_ID  = Object_ID(N'DATA_SaleItemRule'))
BEGIN
  ALTER TABLE DATA_SaleItemRule 
  ADD [Description] [nvarchar](50) NULL
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Code' AND
                Object_ID  = Object_ID(N'DATA_SaleItemRule'))
BEGIN
  ALTER TABLE DATA_SaleItemRule 
  ADD [Code] [nvarchar](40) NULL
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'PromotionType' AND
                Object_ID  = Object_ID(N'DATA_SaleItemRule'))
BEGIN
  ALTER TABLE DATA_SaleItemRule 
  ADD [PromotionType] [smallint] NULL
END
</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2431</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>0) Add AccessFilterExitType to ADM_Gate
1) Create Table LocationMatrix
2) Add  FK Table LocationMatrix - LocationId
3) Add  FK Table LocationMatrix - FromGateId
4) Add  FK Table LocationMatrix - ToGateId</REASON><TABLENAMES>ADM_Gate=GateId
CNF_LocationMatrix=LocationMatrixId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'AccessFilterExitType' AND
                Object_ID  = Object_ID(N'ADM_Gate'))
BEGIN
  ALTER TABLE ADM_Gate ADD AccessFilterExitType Smallint NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'CNF_LocationMatrix'))

BEGIN
   Create table [CNF_LocationMatrix]
  (
 	[LocationMatrixId] Integer Identity(1,1) NOT NULL,
        [LocationId] Integer NOT NULL,
        [FromGateId] Integer NOT NULL,
        [ToGateId] Integer NOT NULL,
        [Amount] float NULL,
        [SortOrder] smallint NULL,
  Primary Key ([LocationMatrixId])
  ) 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_LocationMatrix_LocationId')
BEGIN
  ALTER TABLE CNF_LocationMatrix
  ADD
  CONSTRAINT [FK_CNF_LocationMatrix_LocationId] FOREIGN KEY([LocationId]) REFERENCES [CNF_Location] ([LocationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_LocationMatrix_FromGateId')
BEGIN
  ALTER TABLE CNF_LocationMatrix
  ADD
  CONSTRAINT [FK_CNF_LocationMatrix_FromGateId] FOREIGN KEY([FromGateId]) REFERENCES [ADM_Gate] ([GateId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_LocationMatrix_ToGateId')
BEGIN
  ALTER TABLE CNF_LocationMatrix
  ADD
  CONSTRAINT [FK_CNF_LocationMatrix_ToGateId] FOREIGN KEY([ToGateId]) REFERENCES [ADM_Gate] ([GateId])
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>pchen</ADDEDBY><SQLVERSION>2430</SQLVERSION><RMTRACKLINK>78944</RMTRACKLINK><REASON>Adding ContractFilename to DATA_PaymentFlex</REASON><TABLENAMES>DATA_PaymentFlex=PaymentId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'ContractFilename' AND
                Object_ID  = Object_ID(N'DATA_PaymentFlex'))
BEGIN
  ALTER TABLE DATA_PaymentFlex 
  ADD ContractFilename varchar(100) NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fcaramella</ADDEDBY><SQLVERSION>2429</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>0) ADD Latitude to ADM_Gate
1) ADD Longitude to ADM_Gate
2) ADD Offset to ADM_Gate
3) ADD ExternalCode to ADM_Gate
4) ADD IsExit to CNF_AccessFilter</REASON><TABLENAMES>ADM_Gate=GateId
CNF_AccessFilter=AccessFilterId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Latitude' AND
                Object_ID  = Object_ID(N'ADM_Gate'))
BEGIN
  ALTER TABLE ADM_Gate 
  ADD Latitude varchar(200) NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Longitude' AND
                Object_ID  = Object_ID(N'ADM_Gate'))
BEGIN
  ALTER TABLE ADM_Gate 
  ADD Longitude varchar(200) NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Offset' AND
                Object_ID  = Object_ID(N'ADM_Gate'))
BEGIN
  ALTER TABLE ADM_Gate 
  ADD Offset int NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'ExternalCode' AND
                Object_ID  = Object_ID(N'ADM_Gate'))
BEGIN
  ALTER TABLE ADM_Gate 
  ADD ExternalCode varchar(200) NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'IsExit' AND
                Object_ID  = Object_ID(N'CNF_AccessFilter'))
BEGIN
  ALTER TABLE CNF_AccessFilter 
  ADD IsExit smallint NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>marosio</ADDEDBY><SQLVERSION>2428</SQLVERSION><RMTRACKLINK>69714</RMTRACKLINK><REASON>Add new external key to DATA_Payment and add constraint; also add  constraint to CNF_DonationForm (script 2426)</REASON><TABLENAMES>DATA_Payment=PaymentId
CNF_DonationForm=DonationFormId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'DonationFormId' AND
                Object_ID  = Object_ID(N'DATA_Payment'))
BEGIN
  Alter Table DATA_Payment
  Add DonationFormId Integer NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_DATA_Payment_DonationFormId')
BEGIN
  ALTER TABLE DATA_Payment 
  ADD
  CONSTRAINT [FK_DATA_Payment_DonationFormId] FOREIGN KEY([DonationFormId]) REFERENCES [CNF_DonationForm] ([DonationFormId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_DonationForm_COAAccountId')
BEGIN
  ALTER TABLE CNF_DonationForm 
  ADD
  CONSTRAINT [FK_CNF_DonationForm_COAAccountId] FOREIGN KEY([COAAccountId]) REFERENCES [COA_CNF_Account] ([COAAccountId])
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>2427</SQLVERSION><RMTRACKLINK>79080</RMTRACKLINK><REASON>Add Rounding Rules Pennies to Chart of Account
</REASON><TABLENAMES>CNF_RoundingRule=RoundingRuleId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'COAAccountId' AND
                Object_ID  = Object_ID(N'CNF_RoundingRule'))
BEGIN
	Alter Table CNF_RoundingRule
	Add COAAccountId Integer NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>marosio</ADDEDBY><SQLVERSION>2426</SQLVERSION><RMTRACKLINK>69714</RMTRACKLINK><REASON>Create table CNF_DonationForm</REASON><TABLENAMES>CNF_DonationForm=DonationFormId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT (EXISTS (SELECT * 
                FROM INFORMATION_SCHEMA.TABLES 
                WHERE TABLE_SCHEMA = 'dbo' 
                  AND TABLE_NAME = 'CNF_DonationForm'))
BEGIN
Create table CNF_DonationForm
(
	[DonationFormId] Integer Identity(1,1) NOT NULL,
	[DonationFormName] nvarchar(12) NOT NULL,
	[DonationFormTitle] nvarchar(200) NULL,
	[DonationFormDecline] nvarchar(20) NULL,
	[DonationFormRound] nvarchar(20) NULL,
	[DonationFormCurrency] nvarchar(3) NULL,
	[KeyValue1] Integer NULL,
	[KeyValue2] Integer NULL,
	[KeyValue3] Integer NULL,
	[KeyValue4] Integer NULL,
	[KeyValue5] Integer NULL,
	[KeyValue6] Integer NULL,
	[KeyValue7] Integer NULL,
	[KeyValue8] Integer NULL,
	[COAAccountId] Integer  NULL
Primary Key ([DonationFormId])
) 
END	</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>scoluccia</ADDEDBY><SQLVERSION>2425</SQLVERSION><RMTRACKLINK>78565</RMTRACKLINK><REASON>Added new filed "UserId" and its Foreign key to table 'DATA_TicketUsage'.</REASON><TABLENAMES>DATA_TicketUsage=UsageId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'UserId' AND
                Object_ID  = Object_ID(N'DATA_TicketUsage'))
BEGIN
  ALTER TABLE DATA_TicketUsage 
  ADD UserId Integer NOT NULL DEFAULT(1)
  CONSTRAINT [fk_DATA_TicketUsage_UserId] FOREIGN KEY([UserId])
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>marosio</ADDEDBY><SQLVERSION>2424</SQLVERSION><RMTRACKLINK>69714</RMTRACKLINK><REASON>Add field DonationAmount on DATA_Payment</REASON><TABLENAMES>DATA_Payment=PaymentID</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
               WHERE Name = N'DonationAmount' AND
                     Object_ID  = Object_ID(N'DATA_Payment'))
BEGIN
  ALTER TABLE DATA_Payment 
  ADD DonationAmount Float NOT NULL Default 0
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>lucafornaroli</ADDEDBY><SQLVERSION>2423</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>CNF_Delivery
[0] add field working days
[1] set default value
[2] set the field as not null</REASON><TABLENAMES>CNF_Delivery=DeliveryId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>alter table CNF_Delivery 
  add  WorkingDays Smallint null</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>update CNF_Delivery set WorkingDays = 0</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT> alter table CNF_Delivery 
  alter column  WorkingDays Smallint not null</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dchen</ADDEDBY><SQLVERSION>2422</SQLVERSION><RMTRACKLINK>78729</RMTRACKLINK><REASON>Adding field to persist the upgrade value</REASON><TABLENAMES>CNF_MatrixCell_QuickUpgrade=QuickUpgradeId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
               WHERE Name = N'CardDependencyType' AND
                     Object_ID  = Object_ID(N'CNF_MatrixCell_QuickUpgrade'))
BEGIN
  ALTER TABLE CNF_MatrixCell_QuickUpgrade 
  ADD UpgradeValue Float NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>mevans</ADDEDBY><SQLVERSION>2421</SQLVERSION><RMTRACKLINK>75037</RMTRACKLINK><REASON></REASON><TABLENAMES>DATA_SaleItem=SaleItemId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'CardDependencyType' AND
                Object_ID  = Object_ID(N'DATA_SaleItem'))
BEGIN
  ALTER TABLE DATA_SaleItem 
  ADD CardDependencyType integer NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>Emanuele Candido</ADDEDBY><SQLVERSION>2420</SQLVERSION><RMTRACKLINK>76365</RMTRACKLINK><REASON>In Payment Method:
Allow Cashback
Force Input Amount
Check for Overpayment

Null values are not treated properly on the Payment Method  Base window. They should be initialized to false instead of null.</REASON><TABLENAMES>CNF_PaymentMethod=PaymentMethodId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>UPDATE CNF_PaymentMethod
  SET Cashback = 0
WHERE Cashback is null;

ALTER TABLE CNF_PaymentMethod
ALTER COLUMN Cashback smallint NOT NULL;

IF EXISTS (SELECT * FROM sys.default_constraints
                WHERE Name Like 'DF__CNF_Payme__Cash%')
BEGIN
  DECLARE @ValCash VARCHAR(50)
  select @ValCash = name from sysobjects where OBJECTPROPERTY(id, N'IsConstraint') = 1 AND name like 'DF__CNF_Payme__Cash%'
  EXECUTE ('ALTER TABLE CNF_PaymentMethod DROP CONSTRAINT ' + @ValCash)
END;

IF NOT EXISTS (SELECT * FROM sys.default_constraints
                WHERE Name = 'DF_CNF_PaymentMethod_Cashback')
BEGIN
ALTER TABLE CNF_PaymentMethod 
    ADD CONSTRAINT DF_CNF_PaymentMethod_Cashback DEFAULT 0 FOR Cashback
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>UPDATE CNF_PaymentMethod
  SET ForceInputAmount = 0
WHERE ForceInputAmount is null;

ALTER TABLE CNF_PaymentMethod
ALTER COLUMN ForceInputAmount smallint NOT NULL;

IF EXISTS (SELECT * FROM sys.default_constraints
                WHERE Name Like 'DF__CNF_Payme__Force%')
BEGIN
  DECLARE @ValForce VARCHAR(50)
  select @ValForce = name from sysobjects where OBJECTPROPERTY(id, N'IsConstraint') = 1 AND name like 'DF__CNF_Payme__Force%'
  EXECUTE ('ALTER TABLE CNF_PaymentMethod DROP CONSTRAINT ' + @ValForce)
END;

IF NOT EXISTS (SELECT * FROM sys.default_constraints
                WHERE Name = 'DF_CNF_PaymentMethod_ForceInputAmount')
BEGIN
ALTER TABLE CNF_PaymentMethod 
    ADD CONSTRAINT DF_CNF_PaymentMethod_ForceInputAmount DEFAULT 0 FOR ForceInputAmount
END;</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>UPDATE CNF_PaymentMethod
  SET CheckOverpayment = 0
WHERE CheckOverpayment is null;

ALTER TABLE CNF_PaymentMethod
ALTER COLUMN CheckOverpayment smallint NOT NULL;

IF EXISTS (SELECT * FROM sys.default_constraints
                WHERE Name Like 'DF__CNF_Payme__Check%')
BEGIN
  DECLARE @ValCheck VARCHAR(50)
  select @ValCheck = name from sysobjects where OBJECTPROPERTY(id, N'IsConstraint') = 1 AND name like 'DF__CNF_Payme__Check%'
  EXECUTE ('ALTER TABLE CNF_PaymentMethod DROP CONSTRAINT ' + @ValCheck)
END;

IF NOT EXISTS (SELECT * FROM sys.default_constraints
                WHERE Name = 'DF_CNF_PaymentMethod_CheckOverpayment')
BEGIN
ALTER TABLE CNF_PaymentMethod 
    ADD CONSTRAINT DF_CNF_PaymentMethod_CheckOverpayment DEFAULT 0 FOR CheckOverpayment
END;</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>stefanocoluccia</ADDEDBY><SQLVERSION>2419</SQLVERSION><RMTRACKLINK>74906</RMTRACKLINK><REASON>Ability to Add a "Sort Order" to Price Tables and Display the Price Tables in Order on the Product Matrix</REASON><TABLENAMES>CNF_PriceTable=PriceTableId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'SortOrder' AND
                Object_ID  = Object_ID(N'CNF_PriceTable'))
BEGIN
  ALTER TABLE CNF_PriceTable 
  ADD SortOrder integer NULL
END
</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>FCaramella</ADDEDBY><SQLVERSION>2418</SQLVERSION><RMTRACKLINK>61590</RMTRACKLINK><REASON>CNF_Performance_SaleValidity
[0] Create table
[1] Add FK on Site
[2] Add FK on OpArea
[3] Add FK on Workstation
[4] Add FK on PErformance
[5]  Add FK on Dmgcategory</REASON><TABLENAMES>CNF_Performance_SaleValidity=PerformanceSaleValidityId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT (EXISTS (SELECT * 
                FROM INFORMATION_SCHEMA.TABLES 
                WHERE TABLE_SCHEMA = 'dbo' 
                  AND TABLE_NAME = 'CNF_Performance_SaleValidity'))

BEGIN
Create table [CNF_Performance_SaleValidity]
(
	[PerformanceSaleValidityId] Integer Identity(1,1) NOT NULL,
	[PerformanceId] Integer NOT NULL,
	[SiteId] Integer NULL,
	[OperatingAreaId] Integer NULL,
	[WorkstationId] Integer NULL,
	[DmgCategoryId] Integer NULL,	
	[OnSaleFrom] DateTime NOT NULL,
	[OnSaleUntil] DateTime NOT NULL,
Primary Key ([PerformanceSaleValidityId])
) 
END				
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Performance_SaleValidity_SiteId')
BEGIN
  ALTER TABLE CNF_Performance_SaleValidity 
  ADD
  CONSTRAINT [FK_CNF_Performance_SaleValidity_SiteId] FOREIGN KEY([SiteId]) REFERENCES [CNF_Site] ([SiteId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Performance_SaleValidity_OperatingAreaId')
BEGIN
  ALTER TABLE CNF_Performance_SaleValidity 
  ADD
  CONSTRAINT [FK_CNF_Performance_SaleValidity_OperatingAreaId] FOREIGN KEY([OperatingAreaId]) REFERENCES [CNF_OperatingArea] ([OperatingAreaId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Performance_SaleValidity_WorkstationId')
BEGIN
  ALTER TABLE CNF_Performance_SaleValidity 
  ADD
  CONSTRAINT [FK_CNF_Performance_SaleValidity_WorkstationId] FOREIGN KEY([WorkstationId]) REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Performance_SaleValidity_PerformanceId')
BEGIN
  ALTER TABLE CNF_Performance_SaleValidity 
  ADD
  CONSTRAINT [FK_CNF_Performance_SaleValidity_PerformanceId] FOREIGN KEY([PerformanceId]) REFERENCES [CNF_Performance] ([PerformanceId])
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_Performance_SaleValidity_DmgCategoryId')
BEGIN
  ALTER TABLE CNF_Performance_SaleValidity 
  ADD
  CONSTRAINT [FK_CNF_Performance_SaleValidity_DmgCategoryId] FOREIGN KEY([DmgCategoryId]) REFERENCES [CNF_DmgCategory] ([DmgCategoryId])
END
</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>marioarosio</ADDEDBY><SQLVERSION>2417</SQLVERSION><RMTRACKLINK>71585</RMTRACKLINK><REASON>Alter CNF_Performance Add Colot</REASON><TABLENAMES>CNF_Performance=PerformanceId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Color' AND
                Object_ID  = Object_ID(N'CNF_Performance'))
BEGIN
  ALTER TABLE CNF_Performance 
  ADD Color NVarchar(10) NULL
END;</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>AndreaDavanzo</ADDEDBY><SQLVERSION>2416</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.19.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>AndreaDavanzo</ADDEDBY><SQLVERSION>2415</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>AndreaDavanzo</ADDEDBY><SQLVERSION>2414</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>AndreaDavanzo</ADDEDBY><SQLVERSION>2413</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>AndreaDavanzo</ADDEDBY><SQLVERSION>2412</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>AndreaDavanzo</ADDEDBY><SQLVERSION>2411</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>AndreaDavanzo</ADDEDBY><SQLVERSION>2410</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>AndreaDavanzo</ADDEDBY><SQLVERSION>2409</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>AndreaDavanzo</ADDEDBY><SQLVERSION>2408</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>AndreaDavanzo</ADDEDBY><SQLVERSION>2407</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>AndreaDavanzo</ADDEDBY><SQLVERSION>2406</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>AndreaDavanzo</ADDEDBY><SQLVERSION>2405</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>AndreaDavanzo</ADDEDBY><SQLVERSION>2404</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>AndreaDavanzo</ADDEDBY><SQLVERSION>2403</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>AndreaDavanzo</ADDEDBY><SQLVERSION>2402</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>AndreaDavanzo</ADDEDBY><SQLVERSION>2401</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>AndreaDavanzo</ADDEDBY><SQLVERSION>2400</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>AndreaDavanzo</ADDEDBY><SQLVERSION>2399</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>AndreaDavanzo</ADDEDBY><SQLVERSION>2398</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>AndreaDavanzo</ADDEDBY><SQLVERSION>2397</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>AndreaDavanzo</ADDEDBY><SQLVERSION>2396</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>AndreaDavanzo</ADDEDBY><SQLVERSION>2395</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>AndreaDavanzo</ADDEDBY><SQLVERSION>2394</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>AndreaDavanzo</ADDEDBY><SQLVERSION>2393</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>AndreaDavanzo</ADDEDBY><SQLVERSION>2392</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>AndreaDavanzo</ADDEDBY><SQLVERSION>2391</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>AndreaDavanzo</ADDEDBY><SQLVERSION>2390</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>AndreaDavanzo</ADDEDBY><SQLVERSION>2389</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>AndreaDavanzo</ADDEDBY><SQLVERSION>2388</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>AndreaDavanzo</ADDEDBY><SQLVERSION>2387</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.19.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>fesposito</ADDEDBY><SQLVERSION>2386</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>Dropping Constraint</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * 
           FROM sys.foreign_keys 
           WHERE object_id = OBJECT_ID(N'FK_DATA_PaymentFlexInfo_AccountId') 
             AND parent_object_id = OBJECT_ID(N'DATA_PaymentFlexInfo'))
BEGIN
  ALTER TABLE DATA_PaymentFlexInfo 
   DROP CONSTRAINT FK_DATA_PaymentFlexInfo_AccountId
END 
</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>FCaramella</ADDEDBY><SQLVERSION>2385</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>New Table IMP_IdentifierCode</REASON><TABLENAMES>IMP_MediaIdentifier=MediaIdentifierId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS ( SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND  TABLE_NAME = 'IMP_MediaIdentifier' )

BEGIN
Create table [IMP_MediaIdentifier]
(
	[MediaIdentifierId] Integer Identity(1,1) NOT NULL,
	[IdentifierCode] Varchar(400) NOT NULL,
	[ExternalCode] Varchar(100) NULL,         
	[Status] Smallint NULL,
Primary Key ([MediaIdentifierId])
) 
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>stefanocoluccia</ADDEDBY><SQLVERSION>2384</SQLVERSION><RMTRACKLINK>76325</RMTRACKLINK><REASON>Workstation - Web Sale field  not null </REASON><TABLENAMES>CNF_Workstation=WorkstationId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
           WHERE Name = N'WebSalesInd' AND
           Object_ID  = Object_ID(N'CNF_Workstation'))
BEGIN
  UPDATE CNF_Workstation 
     SET WebSalesInd = 0 
   WHERE WebSalesInd IS NULL   

END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'WebSalesInd ' AND
                Object_ID  = Object_ID(N'CNF_Workstation'))
BEGIN
  ALTER TABLE CNF_Workstation ALTER COLUMN WebSalesInd SMALLINT NOT NULL 
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>2383</SQLVERSION><RMTRACKLINK>72843</RMTRACKLINK><REASON>'Added 'FinancialBlacklistOption' to DATA_Account</REASON><TABLENAMES>DATA_Account=AccountId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'FinancialBlacklistOption' AND
                Object_ID  = Object_ID(N'DATA_Account'))
BEGIN
  ALTER TABLE DATA_Account 
  ADD FinancialBlacklistOption smallint NULL default 0
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dchen</ADDEDBY><SQLVERSION>2382</SQLVERSION><RMTRACKLINK>72691</RMTRACKLINK><REASON>Add FK constraints for:
  MatrixCellId
  RenewMatrixCellId
</REASON><TABLENAMES>CNF_MatrixCell_Renew=RenewId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_MatrixCell_Renew_MatrixCellId')
BEGIN
  ALTER TABLE CNF_MatrixCell_Renew 
  ADD
  CONSTRAINT [FK_CNF_MatrixCell_Renew_MatrixCellId] FOREIGN KEY([MatrixCellId]) REFERENCES [CNF_MatrixCell] ([MatrixCellId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.foreign_keys
                WHERE Name = 'FK_CNF_MatrixCell_Renew_RenewMatrixCellId')
BEGIN
  ALTER TABLE CNF_MatrixCell_Renew 
  ADD
  CONSTRAINT [FK_CNF_MatrixCell_Renew_RenewMatrixCellId] FOREIGN KEY([MatrixCellId]) REFERENCES [CNF_MatrixCell] ([MatrixCellId])
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>2381</SQLVERSION><RMTRACKLINK>75026 </RMTRACKLINK><REASON>COA - OnMoneyCardLoad trigger does not work for Reservations</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT> IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_RR_RevenueData_batchJob]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_RR_RevenueData_batchJob</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT> 
CREATE Procedure dbo.otn_sp_RR_RevenueData_batchJob	 
	@FromDate Date,
	@ToDate Date
AS 
BEGIN

	delete from rr_data_revenue
	where fcalcdate between @FromDate and @ToDate

	Declare @BatchDate Date
	Declare @RRTransDateType Integer

	Declare @SuspendRRRId Integer
	Declare @SuspendCOAAccountId Integer
	Declare @SuspendRRRCode varchar(10)
	Declare @SuspendRRCalcTypeTrigger Integer
	Declare @SuspendRRCalcTypeWhere Integer
	Declare @SuspendRRCalcTypeMethod Integer
	Declare @SuspendCOAAccountConfigId Integer
	Declare @SuspendCOAAccountTypeId Integer
	Declare @SuspendCOAAccountCode varchar(10)
	Declare @SuspendPercentage float
	Declare @SuspendDays Integer
	Declare @SuspendPrice float
	Declare @SuspendCOAAccount_Percentage Float
	Declare @SuspendRemainingValues Integer
	Declare @SuspendRRCOAAccountingType Integer
	Declare @SuspendAccountingType Integer

	Declare @PaymentRRRId Integer
	Declare @PaymentCOAAccountId Integer
	Declare @PaymentRRRCode varchar(10)
	Declare @PaymentRRCalcTypeTrigger Integer
	Declare @PaymentRRCalcTypeWhere Integer
	Declare @PaymentRRCalcTypeMethod Integer
	Declare @PaymentCOAAccountConfigId Integer
	Declare @PaymentCOAAccountTypeId Integer
	Declare @PaymentCOAAccountCode varchar(10)
	Declare @PaymentPercentage float
	Declare @PaymentDays Integer
	Declare @PaymentPrice float
	Declare @PaymentCOAAccount_Percentage Float
	Declare @PaymentRemainingValues Integer
	Declare @PaymentRRCOAAccountingType Integer
	Declare @PaymentAccountingType Integer


	Declare @TaxRRRId Integer
	Declare @TaxCOAAccountId Integer
	Declare @TaxRRRCode varchar(10)
	Declare @TaxRRCalcTypeTrigger Integer
	Declare @TaxRRCalcTypeWhere Integer
	Declare @TaxRRCalcTypeMethod Integer
	Declare @TaxCOAAccountConfigId Integer
	Declare @TaxCOAAccountTypeId Integer
	Declare @TaxCOAAccountCode varchar(10)
	Declare @TaxPercentage float
	Declare @TaxDays Integer
	Declare @TaxPrice float
	Declare @TaxCOAAccount_Percentage Float
	Declare @TaxRemainingValues Integer
	Declare @TaxRRCOAAccountingType Integer
	Declare @TaxAccountingType Integer


	Declare @DiscountRRRId Integer
	Declare @DiscountCOAAccountId Integer
	Declare @DiscountRRRCode varchar(10)
	Declare @DiscountRRCalcTypeTrigger Integer
	Declare @DiscountRRCalcTypeWhere Integer
	Declare @DiscountRRCalcTypeMethod Integer
	Declare @DiscountCOAAccountConfigId Integer
	Declare @DiscountCOAAccountTypeId Integer
	Declare @DiscountCOAAccountCode varchar(10)
	Declare @DiscountPercentage float
	Declare @DiscountDays Integer
	Declare @DiscountPrice float
	Declare @DiscountCOAAccount_Percentage Float
	Declare @DiscountRemainingValues Integer
	Declare @DiscountRRCOAAccountingType Integer
	Declare @DiscountAccountingType Integer

	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer

	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1


	select @RRTransDateType = RRTransDateType
      from cnf_system

--Begin Move Transactions to Suspend Account
	select TOP 1 @SuspendRRRId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
			@SuspendRRRCode = RR_CNF_RevenueRecognitionRule.code,
			@SuspendRRCalcTypeTrigger = RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
			@SuspendRRCalcTypeWhere = RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
			@SuspendRRCalcTypeMethod = RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
			@SuspendCOAAccountConfigId = COA_CNF_AccountConfig.COAAccountConfigId,
			@SuspendCOAAccountTypeId = COA_CNF_AccountType.COAAccountTypeId,
			@SuspendCOAAccountId = coa_cnf_account.COAAccountId,
			@SuspendPercentage = RR_CNF_RevenueRecognitionRule.Percentage,
			@SuspendDays = RR_CNF_RevenueRecognitionRule.Days,
			@SuspendPrice = COA_CNF_AccountConfig.Price,
			@SuspendCOAAccount_Percentage = COA_CNF_AccountConfig.Percentage,
			@SuspendRemainingValues = COA_CNF_AccountConfig.RemainingValues,
			@SuspendCOAAccountCode = coa_cnf_account.Code,
			@SuspendRRCOAAccountingType = COA_CNF_AccountConfig.AccountingType
	from coa_cnf_account
		INNER JOIN COA_CNF_AccountType				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
		INNER JOIN COA_CNF_AccountConfig			on COA_CNF_AccountConfig.COAAccountId = coa_cnf_account.COAAccountId
		INNER JOIN RR_CNF_RevenueRecognitionRule	on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId
	where coa_cnf_account.COAAccountID = @SuspendID
	 order by RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId

	select TOP 1 @PaymentRRRId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
			@PaymentRRRCode = RR_CNF_RevenueRecognitionRule.code,
			@PaymentRRCalcTypeTrigger = RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
			@PaymentRRCalcTypeWhere = RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
			@PaymentRRCalcTypeMethod = RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
			@PaymentCOAAccountConfigId = COA_CNF_AccountConfig.COAAccountConfigId,
			@PaymentCOAAccountTypeId = COA_CNF_AccountType.COAAccountTypeId,
			@PaymentCOAAccountId = coa_cnf_account.COAAccountId,
			@PaymentPercentage = RR_CNF_RevenueRecognitionRule.Percentage,
			@PaymentDays = RR_CNF_RevenueRecognitionRule.Days,
			@PaymentPrice = COA_CNF_AccountConfig.Price,
			@PaymentCOAAccount_Percentage = COA_CNF_AccountConfig.Percentage,
			@PaymentRemainingValues = COA_CNF_AccountConfig.RemainingValues,
			@PaymentCOAAccountCode = coa_cnf_account.Code,
			@PaymentRRCOAAccountingType = COA_CNF_AccountConfig.AccountingType
	from coa_cnf_account
		INNER JOIN COA_CNF_AccountType				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
		INNER JOIN COA_CNF_AccountConfig			on COA_CNF_AccountConfig.COAAccountId = coa_cnf_account.COAAccountId
		INNER JOIN RR_CNF_RevenueRecognitionRule	on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId
	where coa_cnf_account.COAAccountID = @ACCPaymentMethod
	 order by RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId

	select TOP 1 @TaxRRRId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
			@TaxRRRCode = RR_CNF_RevenueRecognitionRule.code,
			@TaxRRCalcTypeTrigger = RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
			@TaxRRCalcTypeWhere = RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
			@TaxRRCalcTypeMethod = RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
			@TaxCOAAccountConfigId = COA_CNF_AccountConfig.COAAccountConfigId,
			@TaxCOAAccountTypeId = COA_CNF_AccountType.COAAccountTypeId,
			@TaxCOAAccountId = coa_cnf_account.COAAccountId,
			@TaxPercentage = RR_CNF_RevenueRecognitionRule.Percentage,
			@TaxDays = RR_CNF_RevenueRecognitionRule.Days,
			@TaxPrice = COA_CNF_AccountConfig.Price,
			@TaxCOAAccount_Percentage = COA_CNF_AccountConfig.Percentage,
			@TaxRemainingValues = COA_CNF_AccountConfig.RemainingValues,
			@TaxCOAAccountCode = coa_cnf_account.Code,
			@TaxRRCOAAccountingType = COA_CNF_AccountConfig.AccountingType
	from coa_cnf_account
		INNER JOIN COA_CNF_AccountType				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
		INNER JOIN COA_CNF_AccountConfig			on COA_CNF_AccountConfig.COAAccountId = coa_cnf_account.COAAccountId
		INNER JOIN RR_CNF_RevenueRecognitionRule	on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId
	where coa_cnf_account.COAAccountID = @TaxAccountID
	 order by RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId

	select TOP 1 @DiscountRRRId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
			@DiscountRRRCode = RR_CNF_RevenueRecognitionRule.code,
			@DiscountRRCalcTypeTrigger = RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
			@DiscountRRCalcTypeWhere = RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
			@DiscountRRCalcTypeMethod = RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
			@DiscountCOAAccountConfigId = COA_CNF_AccountConfig.COAAccountConfigId,
			@DiscountCOAAccountTypeId = COA_CNF_AccountType.COAAccountTypeId,
			@DiscountCOAAccountId = coa_cnf_account.COAAccountId,
			@DiscountPercentage = RR_CNF_RevenueRecognitionRule.Percentage,
			@DiscountDays = RR_CNF_RevenueRecognitionRule.Days,
			@DiscountPrice = COA_CNF_AccountConfig.Price,
			@DiscountCOAAccount_Percentage = COA_CNF_AccountConfig.Percentage,
			@DiscountRemainingValues = COA_CNF_AccountConfig.RemainingValues,
			@DiscountCOAAccountCode = coa_cnf_account.Code,
			@DiscountRRCOAAccountingType = COA_CNF_AccountConfig.AccountingType
	from coa_cnf_account
		INNER JOIN COA_CNF_AccountType				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
		INNER JOIN COA_CNF_AccountConfig			on COA_CNF_AccountConfig.COAAccountId = coa_cnf_account.COAAccountId
		INNER JOIN RR_CNF_RevenueRecognitionRule	on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId
	where coa_cnf_account.COAAccountID = @DiscountAccountID
	 order by RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId

	Declare @Temp table (BatchDate date)

	;with dates_CTE (date) as (
			select @FromDate 
		Union ALL
			select DATEADD(day, 1, date)
			from dates_CTE
			where date &lt; @ToDate
	) 
	INSERT INTO @Temp (
	BatchDate
	) 
	select *
	from dates_CTE 

	DECLARE date_Cursor CURSOR LOCAL FOR
				select * from @Temp

	OPEN date_Cursor

	FETCH NEXT FROM date_Cursor INTO
		@BatchDate

	WHILE @@FETCH_STATUS = 0
	BEGIN

				INSERT INTO [dbo].[RR_DATA_Revenue]
								([COAAccountId]
								,[RevenueRecognitionRuleId]
								,[RRCode]
								,[RRCalcTypeWhere]
								,[RRCalcTypeMethod]
								,[COAAccountConfigId]
								,[COAAccountType]
								,[COAAccountCode]
								,[TransactionId]
								,[SaleId]
								,[SaleItemId]
								,[MatrixCellId]
								,[MatrixCellCode]
								,[MatrixSheetID]
								,[SiteId]
								,[OperatingAreaId]
								,[WorkstationId]
								,[UserGroupId]
								,[UserId]
								,[FCalcDate]
								,[FRevenueDate]
								,[Quantity]
								,[UnitAmount]
								,[GrossAmount]
								,[NetAmount]
								,[Price]
								,[Percentage]
								,[RemaningValues]
								,[RevenueAmount]
								,[AccountingType]
								,[RRCalcTypeTrigger]
								,[RRPercentage]
								,[RRDays]
								,[AttributeIDS])
						select @SuspendCOAAccountId,
								@SuspendRRRId,
								@SuspendRRRCode,
								@SuspendRRCalcTypeWhere,
								@SuspendRRCalcTypeMethod,
								@SuspendCOAAccountConfigId,
								@SuspendCOAAccountTypeId,
								@SuspendCOAAccountCode,
								data_transaction.transactionid, 
								data_transaction.saleid,
								DATA_TransactionItem.saleitemid,
								DATA_SaleItem.Matrixcellid,
								CNF_MatrixCell.Code,
								CNF_MatrixCell.MatrixSheetid,
								data_transaction.Siteid,
								data_transaction.OperatingAreaId,
								data_transaction.Workstationid,
								data_transaction.UserGroupid,
								data_transaction.UserId,
								@BatchDate,
								CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
									 else data_transaction.TransactionDate
								end TransactionDate,
								Coalesce(DATA_TransactionItem.Quantity, 1),
								DATA_SaleItem.UnitPrice,
									DATA_SaleItem.UnitRecharge * data_saleitem.Quantity,
				DATA_SaleItem.UnitRecharge * data_saleitem.Quantity,
								@SuspendPrice,
								@SuspendCOAAccount_Percentage,
								@SuspendRemainingValues,
							DATA_SaleItem.UnitRecharge * data_saleitem.Quantity,
								case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
										when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
										when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 1
										when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 2
										else @SuspendRRCOAAccountingType
								end Accountingtype,
								@SuspendRRCalcTypeTrigger,
								@SuspendPercentage,
								@SuspendDays,
								CNF_AttributeSet.Attributeids
	   
						from DATA_Sale
							inner join data_transaction			on data_transaction.TransactionId = DATA_Sale.PaidTransactionId
							left join DATA_TransactionItem		on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
							left join DATA_SaleItem			    on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
							left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
							left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

						where DATA_Sale.Paid = 1
			and data_transaction.transactiontype in (14, 16, 39)
			and DATA_SaleItem.UnitRecharge &lt;&gt; 0
							and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
							   OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
							and data_transaction.transactionid in (select transactionid
																	from data_payment
																	where PaymentStatus = 1
																	and PaymentAmount &lt;&gt; 0
																)

				INSERT INTO [dbo].[RR_DATA_Revenue]
								([COAAccountId]
								,[RevenueRecognitionRuleId]
								,[RRCode]
								,[RRCalcTypeWhere]
								,[RRCalcTypeMethod]
								,[COAAccountConfigId]
								,[COAAccountType]
								,[COAAccountCode]
								,[TransactionId]
								,[SaleId]
								,[SaleItemId]
								,[MatrixCellId]
								,[MatrixCellCode]
								,[MatrixSheetID]
								,[SiteId]
								,[OperatingAreaId]
								,[WorkstationId]
								,[UserGroupId]
								,[UserId]
								,[FCalcDate]
								,[FRevenueDate]
								,[Quantity]
								,[UnitAmount]
								,[GrossAmount]
								,[NetAmount]
								,[Price]
								,[Percentage]
								,[RemaningValues]
								,[RevenueAmount]
								,[AccountingType]
								,[RRCalcTypeTrigger]
								,[RRPercentage]
								,[RRDays]
								,[AttributeIDS]
								)
				select *
				from(
		select @SuspendCOAAccountId suspendid,
				@SuspendRRRId  RRRID,
				@SuspendRRRCode RRCode,
				@SuspendRRCalcTypeWhere typewhere,
				@SuspendRRCalcTypeMethod method,
				@SuspendCOAAccountConfigId configid,
				@SuspendCOAAccountTypeId AccountTypeId,
				@SuspendCOAAccountCode AccountCode,
				data_transaction.transactionid, 
				data_transaction.saleid,
				DATA_TransactionItem.saleitemid,
				DATA_SaleItem.Matrixcellid,
				CNF_MatrixCell.Code,
				CNF_MatrixCell.MatrixSheetid,
				data_transaction.Siteid,
				data_transaction.OperatingAreaId,
				data_transaction.Workstationid,
				data_transaction.UserGroupid,
				data_transaction.UserId,
				@BatchDate BatchDate,
				CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
				     else data_transaction.TransactionDate
				end TransactionDate,
				Coalesce(DATA_TransactionItem.Quantity, 1) Quantity,
				DATA_SaleItem.UnitPrice,
				case when isnull(data_transactionitem.unitrecharge, 0 ) &lt;&gt; 0 then data_transactionitem.UnitRecharge
				    when isnull(DATA_TransactionItem.TotalAmount, 0) &lt;&gt; 0 then DATA_TransactionItem.TotalAmount
					when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
					else DATA_Sale.TotalAmount
				end GrossAmount,
				case when isnull(data_transactionitem.unitrecharge, 0 ) &lt;&gt; 0 then data_transactionitem.UnitRecharge
				     when isnull((DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes)
					when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
					else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
				end as NetAmount,
				@SuspendPrice price,
				@SuspendCOAAccount_Percentage coapercentage,
				@SuspendRemainingValues remainvalue,

				case    when (data_saleitem.ProductTaxType &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice ) * DATA_SaleItem.Quantity)
						when (data_saleitem.ProductTaxType = 1) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice - DATA_SaleItem.unittaxes) * DATA_SaleItem.Quantity)
						when (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 then 0				
						when isnull((data_transaction.TotalAmount), 0) &lt;&gt; 0 then data_transaction.TotalAmount
						when isnull((DATA_Sale.TotalAmount), 0) &lt;&gt; 0 then DATA_Sale.TotalAmount
						else (data_transaction.Revenue)
				end as Revenue,

				case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
						when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
						when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 1
						when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 2
						else @SuspendRRCOAAccountingType
				end Accountingtype,
				@SuspendRRCalcTypeTrigger typecalctrigger,
				@SuspendPercentage percentage,
				@SuspendDays Days,
								CNF_AttributeSet.Attributeids
	   
						from DATA_Sale
							inner join data_transaction			on data_transaction.TransactionId = DATA_Sale.PaidTransactionId
							left join DATA_TransactionItem		on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
							left join DATA_SaleItem			    on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
							left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
							left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

		where DATA_Sale.Paid = 1
			and data_transaction.transactiontype in (14)
			and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
			   OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
			and data_transaction.transactionid in (select transactionid
													from data_payment
													where PaymentStatus = 1
													and PaymentAmount &lt;&gt; 0)
			)p 
			where Revenue &lt;&gt; 0									

					INSERT INTO [dbo].[RR_DATA_Revenue]
								([COAAccountId]
								,[RevenueRecognitionRuleId]
								,[RRCode]
								,[RRCalcTypeWhere]
								,[RRCalcTypeMethod]
								,[COAAccountConfigId]
								,[COAAccountType]
								,[COAAccountCode]
								,[TransactionId]
								,[SaleId]
								,[SaleItemId]
								,[MatrixCellId]
								,[MatrixCellCode]
								,[MatrixSheetID]
								,[SiteId]
								,[OperatingAreaId]
								,[WorkstationId]
								,[UserGroupId]
								,[UserId]
								,[FCalcDate]
								,[FRevenueDate]
								,[Quantity]
								,[UnitAmount]
								,[GrossAmount]
								,[NetAmount]
								,[Price]
								,[Percentage]
								,[RemaningValues]
								,[RevenueAmount]
								,[AccountingType]
								,[RRCalcTypeTrigger]
								,[RRPercentage]
								,[RRDays]
								,[AttributeIDS])
						select @SuspendCOAAccountId,
								@SuspendRRRId,
								@SuspendRRRCode,
								@SuspendRRCalcTypeWhere,
								@SuspendRRCalcTypeMethod,
								@SuspendCOAAccountConfigId,
								@SuspendCOAAccountTypeId,
								@SuspendCOAAccountCode,
								data_transaction.transactionid, 
								data_transaction.saleid,
								DATA_TransactionItem.saleitemid,
								DATA_SaleItem.Matrixcellid,
								CNF_MatrixCell.Code,
								CNF_MatrixCell.MatrixSheetid,
								data_transaction.Siteid,
								data_transaction.OperatingAreaId,
								data_transaction.Workstationid,
								data_transaction.UserGroupid,
								data_transaction.UserId,
								@BatchDate,
								CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
									 else data_transaction.TransactionDate
								end TransactionDate,
								Coalesce(DATA_TransactionItem.Quantity, 1),
								DATA_SaleItem.UnitPrice,
								case when isnull(DATA_TransactionItem.TotalAmount, 0) &lt;&gt; 0 then DATA_TransactionItem.TotalAmount
									when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
									else DATA_Sale.TotalAmount
								end,
								case when isnull((DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes)
									when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
									else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
								end as NetAmount,
								@SuspendPrice,
								@SuspendCOAAccount_Percentage,
								@SuspendRemainingValues,
								case    when (data_saleitem.ProductTaxType &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) 
												  and (isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0) 
													   and (((select discountamount from data_saleitemrule where saleitemid = DATA_SaleItem.saleitemid) &gt; 0) and (data_transaction.transactiontype in (7, 20, 22)))							
											then ((DATA_SaleItem.UnitRawPrice + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)

				        when (data_saleitem.ProductTaxType &lt;&gt; 1) and (data_transaction.transactiontype in (18, 20, 22)) and (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitRawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitRawPrice  + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)
						when (data_saleitem.ProductTaxType = 1) and (data_transaction.transactiontype in (18, 20, 22)) and isnull((DATA_SaleItem.UnitRawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitRawPrice - DATA_SaleItem.unittaxes + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)

										when (data_saleitem.ProductTaxType &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice  + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)
										when (data_saleitem.ProductTaxType = 1) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice - DATA_SaleItem.unittaxes + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)

										when (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 and data_saleitem.unitRecharge = 0 then 0
										when (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 and data_saleitem.unitRecharge &lt;&gt; 0 then data_saleitem.unitRecharge
										when isnull((data_transaction.TotalAmount), 0) &lt;&gt; 0 then data_transaction.TotalAmount
										when isnull((DATA_Sale.TotalAmount), 0) &lt;&gt; 0 then DATA_Sale.TotalAmount
										else (data_transaction.Revenue)
								end,
								case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
										when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
										when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 1
										when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 2
										else @SuspendRRCOAAccountingType
								end Accountingtype,
								@SuspendRRCalcTypeTrigger,
								@SuspendPercentage,
								@SuspendDays,
								CNF_AttributeSet.Attributeids
	   
						from DATA_Sale
							inner join data_transaction			on data_transaction.TransactionId = ISNULL(data_sale.voidtransactionid, DATA_Sale.PaidTransactionId)
							left join DATA_TransactionItem		on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
							left join DATA_SaleItem			    on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
							left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
							left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

						where DATA_Sale.Paid = 1
							and data_transaction.transactiontype not in (6, 8, 10, 12, 14, 16, 42, 43, 31, 39, 48, 49, 52, 46, 47)
							and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
							   OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
							and data_transaction.transactionid in (select transactionid
																	from data_payment
																	where PaymentStatus = 1
																	and PaymentAmount &lt;&gt; 0
																)

						INSERT INTO [dbo].[RR_DATA_Revenue]
										([COAAccountId]
										,[RevenueRecognitionRuleId]
										,[RRCode]
										,[RRCalcTypeWhere]
										,[RRCalcTypeMethod]
										,[COAAccountConfigId]
										,[COAAccountType]
										,[COAAccountCode]
										,[TransactionId]
										,[SaleId]
										,[SiteId]
										,[OperatingAreaId]
										,[WorkstationId]
										,[UserGroupId]
										,[UserId]
										,[FCalcDate]
										,[FRevenueDate]
										,[Quantity]
										,[GrossAmount]
										,[NetAmount]
										,[Price]
										,[Percentage]
										,[RemaningValues]
										,[RevenueAmount]
										,[AccountingType]
										,[RRCalcTypeTrigger]
										,[RRPercentage]
										,[RRDays])
								select @SuspendCOAAccountId,
										@SuspendRRRId,
										@SuspendRRRCode,
										@SuspendRRCalcTypeWhere,
										@SuspendRRCalcTypeMethod,
										@SuspendCOAAccountConfigId,
										@SuspendCOAAccountTypeId,
										@SuspendCOAAccountCode,
										data_transaction.transactionid, 
										data_transaction.saleid,
										data_transaction.Siteid,
										data_transaction.OperatingAreaId,
										data_transaction.Workstationid,
										data_transaction.UserGroupid,
										data_transaction.UserId,
										@BatchDate,
										CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
											 else data_transaction.TransactionDate
										end TransactionDate,
										0 Quantity,
										data_transaction.revenue TotalAmount,
										data_transaction.revenue NetAmount,
										@SuspendPrice,
										@SuspendCOAAccount_Percentage,
										@SuspendRemainingValues,
										p.Amount,
										@SuspendRRCOAAccountingType,
										@SuspendRRCalcTypeTrigger,
										@SuspendPercentage,
										@SuspendDays
	   
						from DATA_Sale
							inner join data_transaction			on data_transaction.saleid = data_sale.saleid
							left  join  (select settletransactionid, sum(data_payment.paymentamount) as amount
											from data_paymentcredit
												INNER JOIN DATA_Payment						on data_payment.paymentid = data_paymentcredit.paymentid
												INNER JOIN DATA_Transaction					on data_transaction.transactionid = data_paymentcredit.SettleTransactionId
											where ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
												  OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
											group by settletransactionid)p					on p.SettleTransactionId = data_transaction.transactionid

						where DATA_Sale.Paid = 1
							and data_transaction.transactiontype in (6)
							and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
							   OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))


					INSERT INTO [dbo].[RR_DATA_Revenue]
								([COAAccountId]
								,[RevenueRecognitionRuleId]
								,[RRCode]
								,[RRCalcTypeWhere]
								,[RRCalcTypeMethod]
								,[COAAccountConfigId]
								,[COAAccountType]
								,[COAAccountCode]
								,[TransactionId]
								,[SaleId]
								,[SaleItemId]
								,[MatrixCellId]
								,[MatrixCellCode]
								,[MatrixSheetID]
								,[SiteId]
								,[OperatingAreaId]
								,[WorkstationId]
								,[UserGroupId]
								,[UserId]
								,[FCalcDate]
								,[FRevenueDate]
								,[Quantity]
								,[UnitAmount]
								,[GrossAmount]
								,[NetAmount]
								,[Price]
								,[Percentage]
								,[RemaningValues]
								,[RevenueAmount]
								,[AccountingType]
								,[RRCalcTypeTrigger]
								,[RRPercentage]
								,[RRDays]
								,[AttributeIDS])
						select @SuspendCOAAccountId,
								@SuspendRRRId,
								@SuspendRRRCode,
								@SuspendRRCalcTypeWhere,
								@SuspendRRCalcTypeMethod,
								@SuspendCOAAccountConfigId,
								@SuspendCOAAccountTypeId,
								@SuspendCOAAccountCode,
								data_transaction.transactionid, 
								data_transaction.saleid,
								DATA_SaleItem.saleitemid,
								DATA_SaleItem.Matrixcellid,
								CNF_MatrixCell.Code,
								CNF_MatrixCell.MatrixSheetid,
								data_transaction.Siteid,
								data_transaction.OperatingAreaId,
								data_transaction.Workstationid,
								data_transaction.UserGroupid,
								data_transaction.UserId,
								@BatchDate,
								CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
									 else data_transaction.TransactionDate
								end TransactionDate,
								Coalesce(DATA_SaleItem.Quantity, 1),
								DATA_SaleItem.UnitPrice,
								case when isnull(DATA_SaleItem.TotalAmount, 0) &lt;&gt; 0 then DATA_SaleItem.TotalAmount
									when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
									else DATA_Sale.TotalAmount
								end,
								case when isnull((DATA_SaleItem.TotalAmount - DATA_SaleItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_SaleItem.TotalAmount - DATA_SaleItem.TotalTaxes)
									when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
									else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
								end as NetAmount,
								@SuspendPrice,
								@SuspendCOAAccount_Percentage,
								@SuspendRemainingValues,
								case    when (data_saleitem.ProductTaxType &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) 
												  and (isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0) 
													   and (((select discountamount from data_saleitemrule where saleitemid = DATA_SaleItem.saleitemid) &gt; 0) and (data_transaction.transactiontype in (7, 20, 22)))							
											then ((DATA_SaleItem.UnitRawPrice + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)


										when (data_saleitem.ProductTaxType &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice  + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)
										when (data_saleitem.ProductTaxType = 1) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice - DATA_SaleItem.unittaxes + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)
										when (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 then 0
										when (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 and data_saleitem.unitRecharge &lt;&gt; 0 then data_saleitem.unitRecharge
										when isnull((data_transaction.TotalAmount), 0) &lt;&gt; 0 then data_transaction.TotalAmount
										when isnull((DATA_Sale.TotalAmount), 0) &lt;&gt; 0 then DATA_Sale.TotalAmount
										else (data_transaction.Revenue)
								end,
								case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
										when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
										when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 1
										when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 2
										else @SuspendRRCOAAccountingType
								end Accountingtype,
								@SuspendRRCalcTypeTrigger,
								@SuspendPercentage,
								@SuspendDays,
								CNF_AttributeSet.Attributeids
	   
						from DATA_Sale
							inner join data_transaction			on data_transaction.saleid = data_sale.saleid
							left join DATA_SaleItem			    on DATA_SaleItem.saleid = DATA_Transaction.saleid
							left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
							left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

						where DATA_Sale.Paid = 1
							and data_transaction.transactiontype in (46, 47)
							and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
							   OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
							and data_transaction.transactionid in (select transactionid
																	from data_payment
																	where PaymentStatus = 1
																	and PaymentAmount &lt;&gt; 0
																)


					INSERT INTO [dbo].[RR_DATA_Revenue]
								([COAAccountId]
								,[RevenueRecognitionRuleId]
								,[RRCode]
								,[RRCalcTypeWhere]
								,[RRCalcTypeMethod]
								,[COAAccountConfigId]
								,[COAAccountType]
								,[COAAccountCode]
								,[TransactionId]
								,[SaleId]
								,[SaleItemId]
								,[MatrixCellId]
								,[MatrixCellCode]
								,[MatrixSheetID]
								,[SiteId]
								,[OperatingAreaId]
								,[WorkstationId]
								,[UserGroupId]
								,[UserId]
								,[FCalcDate]
								,[FRevenueDate]
								,[Quantity]
								,[UnitAmount]
								,[GrossAmount]
								,[NetAmount]
								,[Price]
								,[Percentage]
								,[RemaningValues]
								,[RevenueAmount]
								,[AccountingType]
								,[RRCalcTypeTrigger]
								,[RRPercentage]
								,[RRDays]
								,[AttributeIDS])
						select @SuspendCOAAccountId,
								@SuspendRRRId,
								@SuspendRRRCode,
								@SuspendRRCalcTypeWhere,
								@SuspendRRCalcTypeMethod,
								@SuspendCOAAccountConfigId,
								@SuspendCOAAccountTypeId,
								@SuspendCOAAccountCode,
								data_transaction.transactionid, 
								data_transaction.saleid,
								DATA_TransactionItem.saleitemid,
								DATA_SaleItem.Matrixcellid,
								CNF_MatrixCell.Code,
								CNF_MatrixCell.MatrixSheetid,
								data_transaction.Siteid,
								data_transaction.OperatingAreaId,
								data_transaction.Workstationid,
								data_transaction.UserGroupid,
								data_transaction.UserId,
								@BatchDate,
								CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
									 else data_transaction.TransactionDate
								end TransactionDate,
								Coalesce(DATA_TransactionItem.Quantity, 1),
								DATA_SaleItem.UnitPrice,
								case when isnull(DATA_TransactionItem.TotalAmount, 0) &lt;&gt; 0 then DATA_TransactionItem.TotalAmount
									when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
									else DATA_Sale.TotalAmount
								end,
								case when isnull((DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes)
									when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
									else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
								end as NetAmount,
								@SuspendPrice,
								@SuspendCOAAccount_Percentage,
								@SuspendRemainingValues,
								DATA_SaleItem.Unitrecharge,
								case    when TransactionType in (5, 17, 8, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
										when TransactionType in (5, 17, 8, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
										when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 2
										when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 1
										else @SuspendRRCOAAccountingType
								end Accountingtype,
								@SuspendRRCalcTypeTrigger,
								@SuspendPercentage,
								@SuspendDays,
								CNF_AttributeSet.Attributeids
	   
						from DATA_Sale
							inner join data_transaction			on data_transaction.TransactionId = ISNULL(data_sale.voidtransactionid, DATA_Sale.PaidTransactionId)
							left join DATA_TransactionItem		on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
							left join DATA_SaleItem			    on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
							left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
							left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

						where DATA_Sale.Paid = 1
							and data_transaction.transactiontype in (10, 42, 43, 49)
							and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
							   OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
							and data_transaction.transactionid in (select transactionid
																	from data_payment
																	where PaymentStatus = 1
																	and PaymentAmount &lt;&gt; 0
																)
			
				INSERT INTO [dbo].[RR_DATA_Revenue]
								([COAAccountId]
								,[RevenueRecognitionRuleId]
								,[RRCode]
								,[RRCalcTypeWhere]
								,[RRCalcTypeMethod]
								,[COAAccountConfigId]
								,[COAAccountType]
								,[COAAccountCode]
								,[TransactionId]
								,[SaleId]
								,[SaleItemId]
								,[MatrixCellId]
								,[MatrixCellCode]
								,[MatrixSheetID]
								,[SiteId]
								,[OperatingAreaId]
								,[WorkstationId]
								,[UserGroupId]
								,[UserId]
								,[FCalcDate]
								,[FRevenueDate]
								,[Quantity]
								,[UnitAmount]
								,[GrossAmount]
								,[NetAmount]
								,[Price]
								,[Percentage]
								,[RemaningValues]
								,[RevenueAmount]
								,[AccountingType]
								,[RRCalcTypeTrigger]
								,[RRPercentage]
								,[RRDays]
								,[AttributeIDS])
						select @SuspendCOAAccountId,
								@SuspendRRRId,
								@SuspendRRRCode,
								@SuspendRRCalcTypeWhere,
								@SuspendRRCalcTypeMethod,
								@SuspendCOAAccountConfigId,
								@SuspendCOAAccountTypeId,
								@SuspendCOAAccountCode,
								data_transaction.transactionid, 
								data_transaction.saleid,
								DATA_TransactionItem.saleitemid,
								DATA_SaleItem.Matrixcellid,
								CNF_MatrixCell.Code,
								CNF_MatrixCell.MatrixSheetid,
								data_transaction.Siteid,
								data_transaction.OperatingAreaId,
								data_transaction.Workstationid,
								data_transaction.UserGroupid,
								data_transaction.UserId,
								@BatchDate,
								CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
									 else data_transaction.TransactionDate
								end TransactionDate,
								Coalesce(DATA_TransactionItem.Quantity, 1),
								DATA_SaleItem.UnitPrice,
								case when isnull(DATA_TransactionItem.TotalAmount, 0) &lt;&gt; 0 then DATA_TransactionItem.TotalAmount
									when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
									else DATA_Sale.TotalAmount
								end,
								case when isnull((DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes)
									when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
									else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
								end as NetAmount,
								@SuspendPrice,
								@SuspendCOAAccount_Percentage,
								@SuspendRemainingValues,
								ABS(DATA_SaleItem.Unitrecharge),
								case    when TransactionType in (5, 17, 8, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
										when TransactionType in (5, 17, 8, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
										when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 2
										when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 1
										else @SuspendRRCOAAccountingType
								end Accountingtype,
								@SuspendRRCalcTypeTrigger,
								@SuspendPercentage,
								@SuspendDays,
								CNF_AttributeSet.Attributeids
	   
						from DATA_Sale
							inner join data_transaction			on data_transaction.TransactionId = ISNULL(data_sale.voidtransactionid, DATA_Sale.PaidTransactionId)
							left join DATA_TransactionItem		on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
							left join DATA_SaleItem			    on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
							left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
							left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

						where DATA_Sale.Paid = 1
							and data_transaction.transactiontype in (31, 48, 52)
							and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
							   OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
							and data_transaction.transactionid in (select transactionid
																	from data_payment
																	where PaymentStatus = 1
																	and PaymentAmount &lt;&gt; 0
																   )


					INSERT INTO [dbo].[RR_DATA_Revenue]
										([COAAccountId]
										,[RevenueRecognitionRuleId]
										,[RRCode]
										,[RRCalcTypeWhere]
										,[RRCalcTypeMethod]
										,[COAAccountConfigId]
										,[COAAccountType]
										,[COAAccountCode]
										,[TransactionId]
										,[SaleId]
										,[SaleItemId]
										,[MatrixCellId]
										,[MatrixCellCode]
										,[MatrixSheetID]
										,[SiteId]
										,[OperatingAreaId]
										,[WorkstationId]
										,[UserGroupId]
										,[UserId]
										,[FCalcDate]
										,[FRevenueDate]
										,[Quantity]
										,[UnitAmount]
										,[GrossAmount]
										,[NetAmount]
										,[Price]
										,[Percentage]
										,[RemaningValues]
										,[RevenueAmount]
										,[AccountingType]
										,[RRCalcTypeTrigger]
										,[RRPercentage]
										,[RRDays]
										,[AttributeIDS])
								select @SuspendCOAAccountId,
										@SuspendRRRId,
										@SuspendRRRCode,
										@SuspendRRCalcTypeWhere,
										@SuspendRRCalcTypeMethod,
										@SuspendCOAAccountConfigId,
										@SuspendCOAAccountTypeId,
										@SuspendCOAAccountCode,
										data_transaction.transactionid, 
										data_transaction.saleid,
										DATA_TransactionItem.saleitemid,
										DATA_SaleItem.Matrixcellid,
										CNF_MatrixCell.Code,
										CNF_MatrixCell.MatrixSheetid,
										data_transaction.Siteid,
										data_transaction.OperatingAreaId,
										data_transaction.Workstationid,
										data_transaction.UserGroupid,
										data_transaction.UserId,
										@BatchDate,
										CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
											 else data_transaction.TransactionDate
										end TransactionDate,
										Coalesce(DATA_TransactionItem.Quantity, 1),
										DATA_SaleItem.UnitPrice,
										case when isnull(DATA_TransactionItem.TotalAmount, 0) &lt;&gt; 0 then DATA_TransactionItem.TotalAmount
											when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
											else DATA_Sale.TotalAmount
										end,
										case when isnull((DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes)
											when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
											else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
										end as NetAmount,
										@SuspendPrice,
										@SuspendCOAAccount_Percentage,
										@SuspendRemainingValues,
										case when (data_saleitem.ProductTaxType &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice + DATA_SaleItem.unittaxes) * DATA_SaleItem.Quantity)
											 when (data_saleitem.ProductTaxType = 1) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice) * DATA_SaleItem.Quantity)
											 when (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 then 0
											 when isnull((data_transaction.TotalAmount), 0) &lt;&gt; 0 then data_transaction.TotalAmount
											 when isnull((DATA_Sale.TotalAmount), 0) &lt;&gt; 0 then DATA_Sale.TotalAmount
											 else (data_transaction.Revenue)
										end,
										case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
												when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
												when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 2
												when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 1
												else @SuspendRRCOAAccountingType
										end Accountingtype,
										@SuspendRRCalcTypeTrigger,
										@SuspendPercentage,
										@SuspendDays,
										CNF_AttributeSet.Attributeids
	   
								from DATA_Sale
									inner join data_transaction			on data_transaction.Saleid = DATA_Sale.Saleid
									left join DATA_TransactionItem		on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
									left join DATA_SaleItem			    on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
									left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
									left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

								where data_transaction.transactiontype in (8)
									and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
										OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
									and data_transaction.transactionid in (select transactionid
																			from data_payment
																			where PaymentStatus = 1
																			and PaymentAmount &lt;&gt; 0
																		)

							INSERT INTO [dbo].[RR_DATA_Revenue]
										([COAAccountId]
										,[RevenueRecognitionRuleId]
										,[RRCode]
										,[RRCalcTypeWhere]
										,[RRCalcTypeMethod]
										,[COAAccountConfigId]
										,[COAAccountType]
										,[COAAccountCode]
										,[TransactionId]
										,[SaleId]
										,[SiteId]
										,[OperatingAreaId]
										,[WorkstationId]
										,[UserGroupId]
										,[UserId]
										,[FCalcDate]
										,[FRevenueDate]
										,[Quantity]
										,[GrossAmount]
										,[NetAmount]
										,[Price]
										,[Percentage]
										,[RemaningValues]
										,[RevenueAmount]
										,[AccountingType]
										,[RRCalcTypeTrigger]
										,[RRPercentage]
										,[RRDays])
								select @SuspendCOAAccountId,
										@SuspendRRRId,
										@SuspendRRRCode,
										@SuspendRRCalcTypeWhere,
										@SuspendRRCalcTypeMethod,
										@SuspendCOAAccountConfigId,
										@SuspendCOAAccountTypeId,
										@SuspendCOAAccountCode,
										data_transaction.transactionid, 
										data_transaction.saleid,
										data_transaction.Siteid,
										data_transaction.OperatingAreaId,
										data_transaction.Workstationid,
										data_transaction.UserGroupid,
										data_transaction.UserId,
										@BatchDate,
										CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
											 else data_transaction.TransactionDate
										end TransactionDate,
										0 Quantity,
										data_transaction.revenue TotalAmount,
										data_transaction.revenue NetAmount,
										@SuspendPrice,
										@SuspendCOAAccount_Percentage,
										@SuspendRemainingValues,
										data_transaction.revenue,
										@SuspendRRCOAAccountingType,
										@SuspendRRCalcTypeTrigger,
										@SuspendPercentage,
										@SuspendDays
	   
								from DATA_Sale
									inner join data_transaction			on data_transaction.saleid = DATA_Sale.saleid
								where data_transaction.transactiontype = 12
									and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
										OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
									and data_transaction.transactionid in (select transactionid
																			from data_payment
																			where PaymentStatus = 1
																			and PaymentAmount &lt;&gt; 0
																		)



								INSERT INTO [dbo].[RR_DATA_Revenue]
										([COAAccountId]
										,[RevenueRecognitionRuleId]
										,[RRCode]
										,[RRCalcTypeWhere]
										,[RRCalcTypeMethod]
										,[COAAccountConfigId]
										,[COAAccountType]
										,[COAAccountCode]
										,[TransactionId]
										,[SaleId]
										,[SaleItemId]
										,[MatrixCellId]
										,[MatrixCellCode]
										,[MatrixSheetID]
										,[SiteId]
										,[OperatingAreaId]
										,[WorkstationId]
										,[UserGroupId]
										,[UserId]
										,[FCalcDate]
										,[FRevenueDate]
										,[Quantity]
										,[UnitAmount]
										,[GrossAmount]
										,[NetAmount]
										,[Price]
										,[Percentage]
										,[RemaningValues]
										,[RevenueAmount]
										,[AccountingType]
										,[RRCalcTypeTrigger]
										,[RRPercentage]
										,[RRDays]
										,[AttributeIDS])
										select *
										from (
								select @SuspendCOAAccountId as COAAccountId,
										@SuspendRRRId as RevenueRecognitionRuleId,
										@SuspendRRRCode as RRCode,
										@SuspendRRCalcTypeWhere as RRCalcTypeWhere,
										@SuspendRRCalcTypeMethod as RRCalcTypeMethod,
										@SuspendCOAAccountConfigId as COAAccountConfigId,
										@SuspendCOAAccountTypeId as COAAccountType,
										@SuspendCOAAccountCode as COAAccountCode,
										data_transaction.transactionid, 
										data_transaction.saleid,
										DATA_SaleItem.saleitemid,
										DATA_SaleItem.Matrixcellid,
										CNF_MatrixCell.Code,
										CNF_MatrixCell.MatrixSheetid,
										data_transaction.Siteid,
										data_transaction.OperatingAreaId,
										data_transaction.Workstationid,
										data_transaction.UserGroupid,
										data_transaction.UserId,
										@BatchDate as calcdate,
										CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
												else data_transaction.TransactionDate
										end TransactionDate,
										Coalesce(DATA_SaleItem.Quantity, 1) as quantity,
										DATA_SaleItem.UnitPrice,
										case when isnull(DATA_SaleItem.TotalAmount, 0) &lt;&gt; 0 then DATA_SaleItem.TotalAmount
											when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
											else DATA_Sale.TotalAmount
										end as totalamount,
										case when isnull((DATA_SaleItem.TotalAmount - DATA_SaleItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_SaleItem.TotalAmount - DATA_SaleItem.TotalTaxes)
											when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
											else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
										end as NetAmount,
										@SuspendPrice as suspendprice,
										@SuspendCOAAccount_Percentage as percentage,
										@SuspendRemainingValues as remainingValues,
										case when (data_saleitem.ProductTaxType &lt;&gt; 1) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice) * DATA_SaleItem.Quantity)
											 when (data_saleitem.ProductTaxType = 1) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice - DATA_SaleItem.unittaxes) * DATA_SaleItem.Quantity)
											 when isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 then 0
											 when isnull((data_transaction.TotalAmount), 0) &lt;&gt; 0 then data_transaction.TotalAmount
											 when isnull((DATA_Sale.TotalAmount), 0) &lt;&gt; 0 then DATA_Sale.TotalAmount
											 else (data_transaction.Revenue)
										end as Revenueamount,
										case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
												when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
												when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 2
												when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 1
												else @SuspendRRCOAAccountingType
										end Accountingtype,
										@SuspendRRCalcTypeTrigger as rrTrigger,
										@SuspendPercentage as suspercentage,
										@SuspendDays as suspendday,
										CNF_AttributeSet.Attributeids
	   
								from DATA_Sale
									inner join data_transaction			on data_transaction.TransactionId = DATA_Sale.PaidTransactionId
									left join DATA_SaleItem			    on DATA_SaleItem.SAleid = data_transaction.SAleid
									left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
									left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

				where DATA_Sale.Paid = 1
					and data_transaction.transactiontype in (16)
					and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
					 OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
					and data_transaction.transactionid in (select transactionid
															from data_payment
															where PaymentStatus = 1
															--and PaymentAmount &lt;&gt; 0
														)
					and DATA_SaleItem.saleitemid not in (select distinct rr_data_Revenue.saleitemid
																from rr_data_Revenue																		
																where rr_data_Revenue.saleitemid is not null)
					and data_saleitem.saleitemid not in (select distinct data_saleitem.saleitemid
													from data_saleitem
															inner join data_transactionitem   on data_transactionitem.saleitemid = data_saleitem.saleitemid
															inner join data_transaction       on data_transaction.transactionid = data_transactionitem.transactionid
													where data_transaction.transactiontype in (5)
													)
					)p  where UnitPrice &lt;&gt; 0


								INSERT INTO [dbo].[RR_DATA_Revenue]
										([COAAccountId]
										,[RevenueRecognitionRuleId]
										,[RRCode]
										,[RRCalcTypeWhere]
										,[RRCalcTypeMethod]
										,[COAAccountConfigId]
										,[COAAccountType]
										,[COAAccountCode]
										,[TransactionId]
										,[SaleId]
										,[SaleItemId]
										,[MatrixCellId]
										,[MatrixCellCode]
										,[MatrixSheetID]
										,[SiteId]
										,[OperatingAreaId]
										,[WorkstationId]
										,[UserGroupId]
										,[UserId]
										,[FCalcDate]
										,[FRevenueDate]
										,[Quantity]
										,[UnitAmount]
										,[GrossAmount]
										,[NetAmount]
										,[Price]
										,[Percentage]
										,[RemaningValues]
										,[RevenueAmount]
										,[AccountingType]
										,[RRCalcTypeTrigger]
										,[RRPercentage]
										,[RRDays]
										,[AttributeIDS])
								select @SuspendCOAAccountId,
										@SuspendRRRId,
										@SuspendRRRCode,
										@SuspendRRCalcTypeWhere,
										@SuspendRRCalcTypeMethod,
										@SuspendCOAAccountConfigId,
										@SuspendCOAAccountTypeId,
										@SuspendCOAAccountCode,
										data_transaction.transactionid, 
										data_transaction.saleid,
										DATA_TransactionItem.saleitemid,
										DATA_SaleItem.Matrixcellid,
										CNF_MatrixCell.Code,
										CNF_MatrixCell.MatrixSheetid,
										data_transaction.Siteid,
										data_transaction.OperatingAreaId,
										data_transaction.Workstationid,
										data_transaction.UserGroupid,
										data_transaction.UserId,
										@BatchDate,
										CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
											 else data_transaction.TransactionDate
										end TransactionDate,
										Coalesce(DATA_TransactionItem.Quantity, 1),
										DATA_SaleItem.UnitPrice,
										case when isnull(DATA_TransactionItem.TotalAmount, 0) &lt;&gt; 0 then DATA_TransactionItem.TotalAmount
											when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
											else DATA_Sale.TotalAmount
										end,
										case when isnull((DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes)
											when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
											else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
										end as NetAmount,
										@SuspendPrice,
										@SuspendCOAAccount_Percentage,
										@SuspendRemainingValues,
										case when isnull((DATA_TransactionItem.UnitPrice *  DATA_TransactionItem.Quantity), 0) &lt;&gt; 0 then (DATA_TransactionItem.UnitPrice *  DATA_TransactionItem.Quantity)
											when isnull((data_transaction.TotalAmount), 0) &lt;&gt; 0 then data_transaction.TotalAmount
											when isnull((DATA_Sale.TotalAmount), 0) &lt;&gt; 0 then DATA_Sale.TotalAmount
											else (data_transaction.Revenue)
										end,
										case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
												when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
												when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 2
												when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 1
												else @SuspendRRCOAAccountingType
										end Accountingtype,
										@SuspendRRCalcTypeTrigger,
										@SuspendPercentage,
										@SuspendDays,
										CNF_AttributeSet.Attributeids
	   
								from DATA_Sale
									inner join data_transaction			on data_transaction.saleid = DATA_Sale.saleid
									inner join DATA_TransactionItem		on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
									left join DATA_SaleItem			    on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
									left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
									left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

								where DATA_Sale.Paid = 1
									and data_transaction.transactiontype in (5)
									and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
									 OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
					
									and data_transaction.transactionid in (select transactionid
																			from data_payment
																			where PaymentStatus = 1
																			and PaymentAmount &lt;&gt; 0
																		)
									and data_transaction.transactionid not in (select distinct transactionid
																				from rr_data_Revenue
																				where transactionid is not null)

				--PaymentMethod
								INSERT INTO [dbo].[RR_DATA_Revenue]
												([COAAccountId]
												,[RevenueRecognitionRuleId]
												,[RRCode]
												,[RRCalcTypeWhere]
												,[RRCalcTypeMethod]
												,[COAAccountConfigId]
												,[COAAccountType]
												,[COAAccountCode]
												,[TransactionId]
												,[SaleId]
												,[SiteId]
												,[OperatingAreaId]
												,[WorkstationId]
												,[UserGroupId]
												,[UserId]
												,[FCalcDate]
												,[FRevenueDate]
												,[Quantity]
												,[GrossAmount]
												,[NetAmount]
												,[Price]
												,[Percentage]
												,[RemaningValues]
												,[RevenueAmount]
												,[AccountingType]
												,[RRCalcTypeTrigger]
												,[RRPercentage]
												,[RRDays])
												select  coaaccountid,
														RRID,
														RRCode,
														TypeWhere,
														method,
														Configid,
														AccountType,
														AccountCode,
														transactionid, 
														saleid,
														Siteid,
														OperatingAreaId,
														WorkstationID,
														UserGroupid,
														UserId,
														BatchDate,
														TransactionDate,
														Qty,
														Gross,
														net,
														price,
														percentage,
														RemaningValue,
														sum(abs(RevenueAmount)),
														Accountingtype,
														TypeTrigger,
														PaymentPercentage,
														RRDays
												from (
												select  coaaccountid,
														RRID,
														RRCode,
														TypeWhere,
														method,
														Configid,
														AccountType,
														AccountCode,
														transactionid, 
														saleid,
														Siteid,
														OperatingAreaId,
														WorkstationID,
														UserGroupid,
														UserId,
														BatchDate,
														TransactionDate,
														Qty,
														Gross,
														net,
														price,
														percentage,
														RemaningValue,
														case when Rownumber = 1 then RevenueAmount + Change
															 else RevenueAmount
														 end RevenueAmount,
														Accountingtype,
														TypeTrigger,
														PaymentPercentage,
														RRDays
												from (
												select @PaymentCOAAccountId as coaaccountid,
														@PaymentRRRId as RRID,
														@PaymentRRRCode as RRCode,
														@PaymentRRCalcTypeWhere as TypeWhere,
														@PaymentRRCalcTypeMethod as method,
														@PaymentCOAAccountConfigId as Configid,
														@PaymentCOAAccountTypeId as AccountType,
														@PaymentCOAAccountCode as AccountCode,
														data_transaction.transactionid, 
														data_transaction.saleid,
														data_transaction.Siteid,
														data_transaction.OperatingAreaId,
														data_transaction.Workstationid,
														data_transaction.UserGroupid,
														data_transaction.UserId,
														@BatchDate as BatchDate,
														CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
															 else data_transaction.TransactionDate
														end TransactionDate,
														0 as Qty,
														0 as Gross,
														0 as net,
														0 as price,
														100 as percentage,
														0 as RemaningValue,
														(data_payment.PaymentAmount) as RevenueAmount,
														case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @PaymentRRCOAAccountingType = 1 then 2
																when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @PaymentRRCOAAccountingType = 2 then 1
																when TransactionType in (7) and (data_payment.PaymentAmount + data_Payment.PaymentFee) &lt;= 0  then 2
																when TransactionType in (7) and (data_payment.PaymentAmount + data_Payment.PaymentFee) &gt; 0  then 1
																else @PaymentRRCOAAccountingType
														end Accountingtype,
														data_transaction.Change,
														@PaymentRRCalcTypeTrigger as TypeTrigger,
														@PaymentPercentage as PaymentPercentage,
														@PaymentDays as RRDays,
														Row_Number ()  OVER (PARTITION BY data_transaction.transactionid order by data_transaction.transactionid)  as Rownumber
		  
												from DATA_Sale
															INNER join data_transaction			on ((data_transaction.TransactionId = Isnull(data_sale.voidtransactionid, DATA_Sale.PaidTransactionId)) or 
																								   (data_transaction.saleid = data_sale.saleid))
															INNER JOIN DATA_Payment				on data_payment.transactionid = data_transaction.transactionid
			
												where data_payment.PaymentStatus = 1
													and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
													 OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
											)p
											)r
											group by 	coaaccountid,
														RRID,
														RRCode,
														TypeWhere,
														method,
														Configid,
														AccountType,
														AccountCode,
														transactionid, 
														saleid,
														Siteid,
														OperatingAreaId,
														Workstationid,
														UserGroupid,
														UserId,
														BatchDate,
														TransactionDate,
														Qty,
														Gross,
														net,
														price,
														percentage,
														RemaningValue,
														Accountingtype,
														TypeTrigger,
														PaymentPercentage,
														RRDays
											Having sum(abs(RevenueAmount)) &lt;&gt; 0
						



				--Tax
									INSERT INTO [dbo].[RR_DATA_Revenue]
												([COAAccountId]
												,[RevenueRecognitionRuleId]
												,[RRCode]
												,[RRCalcTypeWhere]
												,[RRCalcTypeMethod]
												,[COAAccountConfigId]
												,[COAAccountType]
												,[COAAccountCode]
												,[TransactionId]
												,[SaleId]
												,[SiteId]
												,[OperatingAreaId]
												,[WorkstationId]
												,[UserGroupId]
												,[UserId]
												,[FCalcDate]
												,[FRevenueDate]
												,[Quantity]
												,[GrossAmount]
												,[NetAmount]
												,[Price]
												,[Percentage]
												,[RemaningValues]
												,[RevenueAmount]
												,[AccountingType]
												,[RRCalcTypeTrigger]
												,[RRPercentage]
												,[RRDays])

												select  @TaxCOAAccountId,
														@TaxRRRId,
														@TaxRRRCode,
														@TaxRRCalcTypeWhere,
														@TaxRRCalcTypeMethod,
														@TaxCOAAccountConfigId,
														@TaxCOAAccountTypeId,
														@TaxCOAAccountCode,
														data_transaction.transactionid, 
														data_transaction.saleid,
														data_transaction.Siteid,
														data_transaction.OperatingAreaId,
														data_transaction.Workstationid,
														data_transaction.UserGroupid,
														data_transaction.UserId,
														@BatchDate,
														CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
															 else data_transaction.TransactionDate
														end TransactionDate,
														0,
														0,
														0,
														0,
														100,
														0,
														ABS(sum(taxamount)) RevenueAmount,
														case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @TaxRRCOAAccountingType = 1 then 2
																when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @TaxRRCOAAccountingType = 2 then 1
																when TransactionType in (7) and sum(taxamount) &lt;= 0  then 1
																when TransactionType in (7) and sum(taxamount) &gt; 0  then 2
																else @TaxRRCOAAccountingType
														end Accountingtype,
														@TaxRRCalcTypeTrigger,
														@TaxPercentage,
														@TaxDays
		   
											from Data_Sale
												INNER JOIN DATA_Transaction						on data_transaction.Saleid = Data_Sale.Saleid
												INNER JOIN DATA_TransactionTax					on data_transactiontax.transactionid = data_transaction.transactionid
												INNER JOIN CNF_Tax								on cnf_tax.taxid = DATA_TransactionTax.taxid
												--INNER JOIN coa_cnf_account coa					on coa.coaaccountid = cnf_tax.coaaccountid


											where transactiontype NOT IN (33, 45, 46, 47)
											   and Data_Sale.paid = 1
												and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
												 OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
												  and data_transaction.transactionid in (select distinct transactionid
																						   from data_payment
																						   where data_payment.paymentstatus = 1
																						)
											group by 			data_transaction.transactionid, 
																data_transaction.saleid,
																data_transaction.Siteid,
																data_transaction.OperatingAreaId,
																data_transaction.Workstationid,
																data_transaction.UserGroupid,
																data_transaction.UserId,
																Data_Transaction.TransactionDate,
																TransactionType,
																fTransactionDate


				--Discount

										INSERT INTO [dbo].[RR_DATA_Revenue]
												([COAAccountId]
												,[RevenueRecognitionRuleId]
												,[RRCode]
												,[RRCalcTypeWhere]
												,[RRCalcTypeMethod]
												,[COAAccountConfigId]
												,[COAAccountType]
												,[COAAccountCode]
												,[TransactionId]
												,[SaleId]
												,[Saleitemid]
												,[SiteId]
												,[OperatingAreaId]
												,[WorkstationId]
												,[UserGroupId]
												,[UserId]
												,[FCalcDate]
												,[FRevenueDate]
												,[Quantity]
												,[GrossAmount]
												,[NetAmount]
												,[Price]
												,[Percentage]
												,[RemaningValues]
												,[RevenueAmount]
												,[AccountingType]
												,[RRCalcTypeTrigger]
												,[RRPercentage]
												,[RRDays])

												select  @DiscountCOAAccountId,
														@DiscountRRRId,
														@DiscountRRRCode,
														@DiscountRRCalcTypeWhere,
														@DiscountRRCalcTypeMethod,
														@DiscountCOAAccountConfigId,
														@DiscountCOAAccountTypeId,
														@DiscountCOAAccountCode,
														data_transaction.transactionid, 
														data_transaction.saleid,
														p.Saleitemid,
														data_transaction.Siteid,
														data_transaction.OperatingAreaId,
														data_transaction.Workstationid,
														data_transaction.UserGroupid,
														data_transaction.UserId,
														@BatchDate,
														CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
															 else data_transaction.TransactionDate
														end TransactionDate,
														0,
														0,
														0,
														0,
														100,
														0,
														ABS(p.GLAmount) RevenueAmount,
														case    when data_transaction.TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) then 2
																when data_transaction.TransactionType in (7) and (GLAmount) &lt;= 0  then 2
																when data_transaction.TransactionType in (7) and (GLAmount) &gt; 0  then 1
																else @DiscountRRCOAAccountingType
														end Accountingtype,

														@DiscountRRCalcTypeTrigger,
														@DiscountPercentage,
														@DiscountDays
											FROM
											(
												SELECT distinct DATA_SaleItem.Saleitemid,
																DATA_Sale.saleid AS SAleid,
      															DATA_Transaction.TransactionType,
      															( SELECT top 1 transactionid
																	FROM data_transaction		WITH (NOLOCK)
																   WHERE saleid = DATA_Sale.saleid
																	AND transactiontype in (14, 16)
																	AND paid = 1
																) AS tester,

																CASE WHEN DATA_Transaction.TransactionId IN (
																											  SELECT TR.TransactionID
																												FROM DATA_Transaction TR			WITH (NOLOCK)
																													LEFT JOIN DATA_Payment DP		WITH (NOLOCK) ON TR.TransactionId = DP.TransactionId
																											  WHERE TR.SaleId = DATA_Sale.SaleId
																												AND TR.Paid = 1
																												AND DP.PaymentStatus NOT IN (0, 2, 3)
																											)
      
																			THEN DATA_Transaction.Transactionid
																	 ELSE (
																			  SELECT MIN(TR.TransactionID)
																				FROM DATA_Transaction TR				WITH (NOLOCK)
																					LEFT JOIN DATA_Payment DP			WITH (NOLOCK) ON TR.TransactionId = DP.TransactionId
																			   WHERE TR.SaleId = DATA_Sale.saleid
																				 AND TR.TransactionType = 16
																				 AND TR.Paid = 1
																				 AND DP.PaymentStatus NOT IN (0, 2, 3)
																		  )
																END Transactionid, 
																 CASE WHEN CNF_Promotion.PromotionType = 1 AND CNF_PromotionItemRule.NewProduct = 1 THEN  (CNF_MatrixCell.Price - SUM(DATA_SaleItemRule.DiscountAmount))
																	  ELSE  CASE WHEN sum(1*data_saleItemRule.DiscountAmount) &lt; 0 AND transactiontype IN(20, 22, 30, 7, 5, 46, 47) AND
																																												(SELECT Count(*) 
																																												   FROM data_transaction WITH (NOLOCK)
																																												  WHERE saleid = data_sale.saleid
																																												 ) = 1 					  					  					  										  
																					  THEN Sum(1 * DATA_SaleItemRule.DiscountAmount)
																				 WHEN sum(1*data_saleItemRule.DiscountAmount) &lt; 0 THEN	Sum(-1 * DATA_SaleItemRule.DiscountAmount)
																				 WHEN sum(1*data_saleItemRule.DiscountAmount) &gt; 0 AND transactiontype IN(20, 22, 30, 7, 5, 46, 47) THEN Sum(-1 * DATA_SaleItemRule.DiscountAmount)		            	                  
																				 ELSE sum(1*Data_SaleItemRule.DiscountAmount)
																			END
																END AS GLAmount


												FROM dbo.DATA_SaleItemRule				WITH (NOLOCK)
													LEFT JOIN dbo.CNF_PromotionItemRule WITH (NOLOCK) ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
													LEFT JOIN dbo.CNF_PromotionItem		WITH (NOLOCK) ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
													LEFT JOIN dbo.CNF_Promotion			WITH (NOLOCK) ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId
													LEFT JOIN dbo.CNF_DmgCategory		WITH (NOLOCK) ON CNF_DmgCategory.DmgCategoryId = CNF_Promotion.DmgCategoryId
													LEFT JOIN dbo.DATA_SaleItem			WITH (NOLOCK) ON DATA_SaleItem.SaleItemId = DATA_SaleItemRule.SaleItemId
													LEFT JOIN dbo.DATA_Sale				WITH (NOLOCK) ON DATA_Sale.SaleID = DATA_SaleItem.SaleID
													LEFT JOIN DATA_TransactionItem		WITH (NOLOCK) ON DATA_TransactionItem.SaleItemId = DATA_SaleItem.SaleItemId 
													LEFT JOIN DATA_Transaction			WITH (NOLOCK) ON  DATA_Transaction.TransactionId = DATA_TransactionItem.TransactionId
													LEFT JOIN CNF_MatrixCell			WITH (NOLOCK) ON CNF_MatrixCell.MatrixCellId =  DATA_SaleItem.MatrixCellId

 
												WHERE DATA_Transaction.saleid in (
																					SELECT ff.saleid 
																					  FROM DATA_Transaction ff WITH (NOLOCK) 
																						LEFT JOIN Data_Payment WITH (NOLOCK) on (ff.Transactionid = Data_Payment.Transactionid) 
																					 WHERE  ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
																						OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
																					   AND DATA_PAyment.PaymentStatus NOT in (0,2,3) 
																					   AND (TransactionType not in (12)) 
																					   AND ff.PAid = 1
																				 )  

												 AND DATA_Sale.Paid = 1
												 and transactiontype NOT IN (33, 45, 46, 47)
												 AND ((DATA_SaleItem.quantity &gt; 0) OR ((DATA_SaleItem.quantity &lt; 0) AND (transactiontype IN (20, 22, 30, 7, 5, 46, 47))))

         
												group BY DATA_SaleItem.Saleitemid,
														 DATA_Sale.saleid,
														 Data_transaction.Paid,
														 Data_Transaction.Transactionid,
														 Data_Transaction.fTransactionDate,
														 Data_Saleitem.Matrixcellid,
														 CNF_DmgCategory.DmgCategoryCode,
														 PromotionType,
														 CNF_PromotionItemRule.NewProduct,
														 CNF_MatrixCell.Price,
														 transactiontype,
														 CNF_DmgCategory.Description
											)p
												LEFT JOIN data_transaction WITH (NOLOCK) on data_transaction.transactionid = p.transactionid

											WHERE ((p.TransactionType &lt;&gt; 5) or (Tester is not null))
											  AND data_transaction.transactionid is not null


					
						--End Move Transactions to Suspend Account

						exec otn_sp_RR_RevenueData_OnDepositTrigger @BatchDate, @RRTransDateType

						exec otn_sp_RR_RevenueData_OnSaleTrigger @BatchDate, @RRTransDateType
		
						exec otn_sp_RR_RevenueData_OnMoneyCardLoad @BatchDate, @RRTransDateType

						exec otn_sp_RR_RevenueData_OnMoneyCardCashOut @BatchDate, @RRTransDateType

						exec otn_sp_RR_RevenueData_OnExternalMoneyCardCashOut @BatchDate, @RRTransDateType

						exec otn_sp_RR_RevenueData_OnExternalMoneyCardLoad @BatchDate, @RRTransDateType

						exec otn_sp_RR_RevenueData_OnCreditWriteoff @BatchDate, @RRTransDateType

						exec otn_sp_RR_RevenueData_OnMoneyRefundTrigger @BatchDate, @RRTransDateType

						exec otn_sp_RR_RevenueData_OnAdvancedPaymentTrigger @BatchDate, @RRTransDateType
		
						--exec otn_sp_RR_RevenueData_OnFlexContractPayment @BatchDate, @RRTransDateType

						--exec otn_sp_RR_RevenueData_OnFlexContractCancelled @BatchDate, @RRTransDateType

						exec otn_sp_RR_RevenueData_OnCreditSettlementTrigger @BatchDate, @RRTransDateType
		
						exec otn_sp_RR_RevenueData_SettleUpSuspendAccount @BatchDate, @RRTransDateType


						exec otn_sp_RR_RevenueData_OnTicketUsageTrigger @BatchDate, @RRTransDateType

						exec otn_sp_RR_RevenueData_OnEventTrigger @BatchDate, @RRTransDateType

						exec otn_sp_RR_RevenueData_OnTimePeriodTrigger @BatchDate, @RRTransDateType

						exec otn_sp_RR_RevenueData_OnTicketExpiredTrigger @BatchDate, @RRTransDateType

						exec otn_sp_RR_RevenueData_OnChangeValiditydateTrigger @BatchDate, @RRTransDateType
		

	FETCH NEXT FROM date_Cursor INTO
		@BatchDate

end

End</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>2380</SQLVERSION><RMTRACKLINK>75026 </RMTRACKLINK><REASON>COA - OnMoneyCardLoad trigger does not work for Reservations</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_RR_RevenueData_batchJob]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_RR_RevenueData_batchJob</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>--e.RevenueRecognitionRuleId

--	select TOP 1 @TaxRRRId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
--			@TaxRRRCode = RR_CNF_RevenueRecognitionRule.code,
--			@TaxRRCalcTypeTrigger = RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
--			@TaxRRCalcTypeWhere = RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
--			@TaxRRCalcTypeMethod = RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
--			@TaxCOAAccountConfigId = COA_CNF_AccountConfig.COAAccountConfigId,
--			@TaxCOAAccountTypeId = COA_CNF_AccountType.COAAccountTypeId,
--			@TaxCOAAccountId = coa_cnf_account.COAAccountId,
--			@TaxPercentage = RR_CNF_RevenueRecognitionRule.Percentage,
--			@TaxDays = RR_CNF_RevenueRecognitionRule.Days,
--			@TaxPrice = COA_CNF_AccountConfig.Price,
--			@TaxCOAAccount_Percentage = COA_CNF_AccountConfig.Percentage,
--			@TaxRemainingValues = COA_CNF_AccountConfig.RemainingValues,
--			@TaxCOAAccountCode = coa_cnf_account.Code,
--			@TaxRRCOAAccountingType = COA_CNF_AccountConfig.AccountingType
--	from coa_cnf_account
--		INNER JOIN COA_CNF_AccountType				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
--		INNER JOIN COA_CNF_AccountConfig			on COA_CNF_AccountConfig.COAAccountId = coa_cnf_account.COAAccountId
--		INNER JOIN RR_CNF_RevenueRecognitionRule	on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId
--	where coa_cnf_account.COAAccountID = @TaxAccountID
--	 order by RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId

--	select TOP 1 @DiscountRRRId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
--			@DiscountRRRCode = RR_CNF_RevenueRecognitionRule.code,
--			@DiscountRRCalcTypeTrigger = RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
--			@DiscountRRCalcTypeWhere = RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
--			@DiscountRRCalcTypeMethod = RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
--			@DiscountCOAAccountConfigId = COA_CNF_AccountConfig.COAAccountConfigId,
--			@DiscountCOAAccountTypeId = COA_CNF_AccountType.COAAccountTypeId,
--			@DiscountCOAAccountId = coa_cnf_account.COAAccountId,
--			@DiscountPercentage = RR_CNF_RevenueRecognitionRule.Percentage,
--			@DiscountDays = RR_CNF_RevenueRecognitionRule.Days,
--			@DiscountPrice = COA_CNF_AccountConfig.Price,
--			@DiscountCOAAccount_Percentage = COA_CNF_AccountConfig.Percentage,
--			@DiscountRemainingValues = COA_CNF_AccountConfig.RemainingValues,
--			@DiscountCOAAccountCode = coa_cnf_account.Code,
--			@DiscountRRCOAAccountingType = COA_CNF_AccountConfig.AccountingType
--	from coa_cnf_account
--		INNER JOIN COA_CNF_AccountType				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
--		INNER JOIN COA_CNF_AccountConfig			on COA_CNF_AccountConfig.COAAccountId = coa_cnf_account.COAAccountId
--		INNER JOIN RR_CNF_RevenueRecognitionRule	on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId
--	where coa_cnf_account.COAAccountID = @DiscountAccountID
--	 order by RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId

--	Declare @Temp table (BatchDate date)

--	;with dates_CTE (date) as (
--			select @FromDate 
--		Union ALL
--			select DATEADD(day, 1, date)
--			from dates_CTE
--			where date &lt; @ToDate
--	) 
--	INSERT INTO @Temp (
--	BatchDate
--	) 
--	select *
--	from dates_CTE 

--	DECLARE date_Cursor CURSOR LOCAL FOR
--				select * from @Temp

--	OPEN date_Cursor

--	FETCH NEXT FROM date_Cursor INTO
--		@BatchDate

--	WHILE @@FETCH_STATUS = 0
--	BEGIN

--				INSERT INTO [dbo].[RR_DATA_Revenue]
--								([COAAccountId]
--								,[RevenueRecognitionRuleId]
--								,[RRCode]
--								,[RRCalcTypeWhere]
--								,[RRCalcTypeMethod]
--								,[COAAccountConfigId]
--								,[COAAccountType]
--								,[COAAccountCode]
--								,[TransactionId]
--								,[SaleId]
--								,[SaleItemId]
--								,[MatrixCellId]
--								,[MatrixCellCode]
--								,[MatrixSheetID]
--								,[SiteId]
--								,[OperatingAreaId]
--								,[WorkstationId]
--								,[UserGroupId]
--								,[UserId]
--								,[FCalcDate]
--								,[FRevenueDate]
--								,[Quantity]
--								,[UnitAmount]
--								,[GrossAmount]
--								,[NetAmount]
--								,[Price]
--								,[Percentage]
--								,[RemaningValues]
--								,[RevenueAmount]
--								,[AccountingType]
--								,[RRCalcTypeTrigger]
--								,[RRPercentage]
--								,[RRDays]
--								,[AttributeIDS])
--						select @SuspendCOAAccountId,
--								@SuspendRRRId,
--								@SuspendRRRCode,
--								@SuspendRRCalcTypeWhere,
--								@SuspendRRCalcTypeMethod,
--								@SuspendCOAAccountConfigId,
--								@SuspendCOAAccountTypeId,
--								@SuspendCOAAccountCode,
--								data_transaction.transactionid, 
--								data_transaction.saleid,
--								DATA_TransactionItem.saleitemid,
--								DATA_SaleItem.Matrixcellid,
--								CNF_MatrixCell.Code,
--								CNF_MatrixCell.MatrixSheetid,
--								data_transaction.Siteid,
--								data_transaction.OperatingAreaId,
--								data_transaction.Workstationid,
--								data_transaction.UserGroupid,
--								data_transaction.UserId,
--								@BatchDate,
--								CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
--									 else data_transaction.TransactionDate
--								end TransactionDate,
--								Coalesce(DATA_TransactionItem.Quantity, 1),
--								DATA_SaleItem.UnitPrice,
--									DATA_SaleItem.UnitRecharge * data_saleitem.Quantity,
--				DATA_SaleItem.UnitRecharge * data_saleitem.Quantity,
--								@SuspendPrice,
--								@SuspendCOAAccount_Percentage,
--								@SuspendRemainingValues,
--							DATA_SaleItem.UnitRecharge * data_saleitem.Quantity,
--								case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
--										when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
--										when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 1
--										when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 2
--										else @SuspendRRCOAAccountingType
--								end Accountingtype,
--								@SuspendRRCalcTypeTrigger,
--								@SuspendPercentage,
--								@SuspendDays,
--								CNF_AttributeSet.Attributeids
	   
--						from DATA_Sale
--							inner join data_transaction			on data_transaction.TransactionId = DATA_Sale.PaidTransactionId
--							left join DATA_TransactionItem		on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
--							left join DATA_SaleItem			    on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
--							left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
--							left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

--						where DATA_Sale.Paid = 1
--			and data_transaction.transactiontype in (14, 16, 39)
--			and DATA_SaleItem.UnitRecharge &lt;&gt; 0
--							and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
--							   OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
--							and data_transaction.transactionid in (select transactionid
--																	from data_payment
--																	where PaymentStatus = 1
--																	and PaymentAmount &lt;&gt; 0
--																)

--				INSERT INTO [dbo].[RR_DATA_Revenue]
--								([COAAccountId]
--								,[RevenueRecognitionRuleId]
--								,[RRCode]
--								,[RRCalcTypeWhere]
--								,[RRCalcTypeMethod]
--								,[COAAccountConfigId]
--								,[COAAccountType]
--								,[COAAccountCode]
--								,[TransactionId]
--								,[SaleId]
--								,[SaleItemId]
--								,[MatrixCellId]
--								,[MatrixCellCode]
--								,[MatrixSheetID]
--								,[SiteId]
--								,[OperatingAreaId]
--								,[WorkstationId]
--								,[UserGroupId]
--								,[UserId]
--								,[FCalcDate]
--								,[FRevenueDate]
--								,[Quantity]
--								,[UnitAmount]
--								,[GrossAmount]
--								,[NetAmount]
--								,[Price]
--								,[Percentage]
--								,[RemaningValues]
--								,[RevenueAmount]
--								,[AccountingType]
--								,[RRCalcTypeTrigger]
--								,[RRPercentage]
--								,[RRDays]
--								,[AttributeIDS]
--								)
--				select *
--				from(
--		select @SuspendCOAAccountId suspendid,
--				@SuspendRRRId  RRRID,
--				@SuspendRRRCode RRCode,
--				@SuspendRRCalcTypeWhere typewhere,
--				@SuspendRRCalcTypeMethod method,
--				@SuspendCOAAccountConfigId configid,
--				@SuspendCOAAccountTypeId AccountTypeId,
--				@SuspendCOAAccountCode AccountCode,
--				data_transaction.transactionid, 
--				data_transaction.saleid,
--				DATA_TransactionItem.saleitemid,
--				DATA_SaleItem.Matrixcellid,
--				CNF_MatrixCell.Code,
--				CNF_MatrixCell.MatrixSheetid,
--				data_transaction.Siteid,
--				data_transaction.OperatingAreaId,
--				data_transaction.Workstationid,
--				data_transaction.UserGroupid,
--				data_transaction.UserId,
--				@BatchDate BatchDate,
--				CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
--				     else data_transaction.TransactionDate
--				end TransactionDate,
--				Coalesce(DATA_TransactionItem.Quantity, 1) Quantity,
--				DATA_SaleItem.UnitPrice,
--				case when isnull(data_transactionitem.unitrecharge, 0 ) &lt;&gt; 0 then data_transactionitem.UnitRecharge
--				    when isnull(DATA_TransactionItem.TotalAmount, 0) &lt;&gt; 0 then DATA_TransactionItem.TotalAmount
--					when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
--					else DATA_Sale.TotalAmount
--				end GrossAmount,
--				case when isnull(data_transactionitem.unitrecharge, 0 ) &lt;&gt; 0 then data_transactionitem.UnitRecharge
--				     when isnull((DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes)
--					when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
--					else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
--				end as NetAmount,
--				@SuspendPrice price,
--				@SuspendCOAAccount_Percentage coapercentage,
--				@SuspendRemainingValues remainvalue,

--				case    when (data_saleitem.ProductTaxType &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice ) * DATA_SaleItem.Quantity)
--						when (data_saleitem.ProductTaxType = 1) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice - DATA_SaleItem.unittaxes) * DATA_SaleItem.Quantity)
--						when (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 then 0				
--						when isnull((data_transaction.TotalAmount), 0) &lt;&gt; 0 then data_transaction.TotalAmount
--						when isnull((DATA_Sale.TotalAmount), 0) &lt;&gt; 0 then DATA_Sale.TotalAmount
--						else (data_transaction.Revenue)
--				end as Revenue,

--				case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
--						when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
--						when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 1
--						when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 2
--						else @SuspendRRCOAAccountingType
--				end Accountingtype,
--				@SuspendRRCalcTypeTrigger typecalctrigger,
--				@SuspendPercentage percentage,
--				@SuspendDays Days,
--								CNF_AttributeSet.Attributeids
	   
--						from DATA_Sale
--							inner join data_transaction			on data_transaction.TransactionId = DATA_Sale.PaidTransactionId
--							left join DATA_TransactionItem		on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
--							left join DATA_SaleItem			    on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
--							left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
--							left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

--		where DATA_Sale.Paid = 1
--			and data_transaction.transactiontype in (14)
--			and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
--			   OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
--			and data_transaction.transactionid in (select transactionid
--													from data_payment
--													where PaymentStatus = 1
--													and PaymentAmount &lt;&gt; 0)
--			)p 
--			where Revenue &lt;&gt; 0									

--					INSERT INTO [dbo].[RR_DATA_Revenue]
--								([COAAccountId]
--								,[RevenueRecognitionRuleId]
--								,[RRCode]
--								,[RRCalcTypeWhere]
--								,[RRCalcTypeMethod]
--								,[COAAccountConfigId]
--								,[COAAccountType]
--								,[COAAccountCode]
--								,[TransactionId]
--								,[SaleId]
--								,[SaleItemId]
--								,[MatrixCellId]
--								,[MatrixCellCode]
--								,[MatrixSheetID]
--								,[SiteId]
--								,[OperatingAreaId]
--								,[WorkstationId]
--								,[UserGroupId]
--								,[UserId]
--								,[FCalcDate]
--								,[FRevenueDate]
--								,[Quantity]
--								,[UnitAmount]
--								,[GrossAmount]
--								,[NetAmount]
--								,[Price]
--								,[Percentage]
--								,[RemaningValues]
--								,[RevenueAmount]
--								,[AccountingType]
--								,[RRCalcTypeTrigger]
--								,[RRPercentage]
--								,[RRDays]
--								,[AttributeIDS])
--						select @SuspendCOAAccountId,
--								@SuspendRRRId,
--								@SuspendRRRCode,
--								@SuspendRRCalcTypeWhere,
--								@SuspendRRCalcTypeMethod,
--								@SuspendCOAAccountConfigId,
--								@SuspendCOAAccountTypeId,
--								@SuspendCOAAccountCode,
--								data_transaction.transactionid, 
--								data_transaction.saleid,
--								DATA_TransactionItem.saleitemid,
--								DATA_SaleItem.Matrixcellid,
--								CNF_MatrixCell.Code,
--								CNF_MatrixCell.MatrixSheetid,
--								data_transaction.Siteid,
--								data_transaction.OperatingAreaId,
--								data_transaction.Workstationid,
--								data_transaction.UserGroupid,
--								data_transaction.UserId,
--								@BatchDate,
--								CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
--									 else data_transaction.TransactionDate
--								end TransactionDate,
--								Coalesce(DATA_TransactionItem.Quantity, 1),
--								DATA_SaleItem.UnitPrice,
--								case when isnull(DATA_TransactionItem.TotalAmount, 0) &lt;&gt; 0 then DATA_TransactionItem.TotalAmount
--									when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
--									else DATA_Sale.TotalAmount
--								end,
--								case when isnull((DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes)
--									when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
--									else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
--								end as NetAmount,
--								@SuspendPrice,
--								@SuspendCOAAccount_Percentage,
--								@SuspendRemainingValues,
--								case    when (data_saleitem.ProductTaxType &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) 
--												  and (isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0) 
--													   and (((select discountamount from data_saleitemrule where saleitemid = DATA_SaleItem.saleitemid) &gt; 0) and (data_transaction.transactiontype in (7, 20, 22)))							
--											then ((DATA_SaleItem.UnitRawPrice + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)

--				        when (data_saleitem.ProductTaxType &lt;&gt; 1) and (data_transaction.transactiontype in (18, 20, 22)) and (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitRawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitRawPrice  + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)
--						when (data_saleitem.ProductTaxType = 1) and (data_transaction.transactiontype in (18, 20, 22)) and isnull((DATA_SaleItem.UnitRawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitRawPrice - DATA_SaleItem.unittaxes + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)

--										when (data_saleitem.ProductTaxType &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice  + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)
--										when (data_saleitem.ProductTaxType = 1) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice - DATA_SaleItem.unittaxes + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)

--										when (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 and data_saleitem.unitRecharge = 0 then 0
--										when (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 and data_saleitem.unitRecharge &lt;&gt; 0 then data_saleitem.unitRecharge
--										when isnull((data_transaction.TotalAmount), 0) &lt;&gt; 0 then data_transaction.TotalAmount
--										when isnull((DATA_Sale.TotalAmount), 0) &lt;&gt; 0 then DATA_Sale.TotalAmount
--										else (data_transaction.Revenue)
--								end,
--								case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
--										when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
--										when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 1
--										when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 2
--										else @SuspendRRCOAAccountingType
--								end Accountingtype,
--								@SuspendRRCalcTypeTrigger,
--								@SuspendPercentage,
--								@SuspendDays,
--								CNF_AttributeSet.Attributeids
	   
--						from DATA_Sale
--							inner join data_transaction			on data_transaction.TransactionId = ISNULL(data_sale.voidtransactionid, DATA_Sale.PaidTransactionId)
--							left join DATA_TransactionItem		on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
--							left join DATA_SaleItem			    on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
--							left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
--							left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

--						where DATA_Sale.Paid = 1
--							and data_transaction.transactiontype not in (6, 8, 10, 12, 14, 16, 42, 43, 31, 39, 48, 49, 52, 46, 47)
--							and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
--							   OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
--							and data_transaction.transactionid in (select transactionid
--																	from data_payment
--																	where PaymentStatus = 1
--																	and PaymentAmount &lt;&gt; 0
--																)

--						INSERT INTO [dbo].[RR_DATA_Revenue]
--										([COAAccountId]
--										,[RevenueRecognitionRuleId]
--										,[RRCode]
--										,[RRCalcTypeWhere]
--										,[RRCalcTypeMethod]
--										,[COAAccountConfigId]
--										,[COAAccountType]
--										,[COAAccountCode]
--										,[TransactionId]
--										,[SaleId]
--										,[SiteId]
--										,[OperatingAreaId]
--										,[WorkstationId]
--										,[UserGroupId]
--										,[UserId]
--										,[FCalcDate]
--										,[FRevenueDate]
--										,[Quantity]
--										,[GrossAmount]
--										,[NetAmount]
--										,[Price]
--										,[Percentage]
--										,[RemaningValues]
--										,[RevenueAmount]
--										,[AccountingType]
--										,[RRCalcTypeTrigger]
--										,[RRPercentage]
--										,[RRDays])
--								select @SuspendCOAAccountId,
--										@SuspendRRRId,
--										@SuspendRRRCode,
--										@SuspendRRCalcTypeWhere,
--										@SuspendRRCalcTypeMethod,
--										@SuspendCOAAccountConfigId,
--										@SuspendCOAAccountTypeId,
--										@SuspendCOAAccountCode,
--										data_transaction.transactionid, 
--										data_transaction.saleid,
--										data_transaction.Siteid,
--										data_transaction.OperatingAreaId,
--										data_transaction.Workstationid,
--										data_transaction.UserGroupid,
--										data_transaction.UserId,
--										@BatchDate,
--										CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
--											 else data_transaction.TransactionDate
--										end TransactionDate,
--										0 Quantity,
--										data_transaction.revenue TotalAmount,
--										data_transaction.revenue NetAmount,
--										@SuspendPrice,
--										@SuspendCOAAccount_Percentage,
--										@SuspendRemainingValues,
--										p.Amount,
--										@SuspendRRCOAAccountingType,
--										@SuspendRRCalcTypeTrigger,
--										@SuspendPercentage,
--										@SuspendDays
	   
--						from DATA_Sale
--							inner join data_transaction			on data_transaction.saleid = data_sale.saleid
--							left  join  (select settletransactionid, sum(data_payment.paymentamount) as amount
--											from data_paymentcredit
--												INNER JOIN DATA_Payment						on data_payment.paymentid = data_paymentcredit.paymentid
--												INNER JOIN DATA_Transaction					on data_transaction.transactionid = data_paymentcredit.SettleTransactionId
--											where ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
--												  OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
--											group by settletransactionid)p					on p.SettleTransactionId = data_transaction.transactionid

--						where DATA_Sale.Paid = 1
--							and data_transaction.transactiontype in (6)
--							and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
--							   OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))


--					INSERT INTO [dbo].[RR_DATA_Revenue]
--								([COAAccountId]
--								,[RevenueRecognitionRuleId]
--								,[RRCode]
--								,[RRCalcTypeWhere]
--								,[RRCalcTypeMethod]
--								,[COAAccountConfigId]
--								,[COAAccountType]
--								,[COAAccountCode]
--								,[TransactionId]
--								,[SaleId]
--								,[SaleItemId]
--								,[MatrixCellId]
--								,[MatrixCellCode]
--								,[MatrixSheetID]
--								,[SiteId]
--								,[OperatingAreaId]
--								,[WorkstationId]
--								,[UserGroupId]
--								,[UserId]
--								,[FCalcDate]
--								,[FRevenueDate]
--								,[Quantity]
--								,[UnitAmount]
--								,[GrossAmount]
--								,[NetAmount]
--								,[Price]
--								,[Percentage]
--								,[RemaningValues]
--								,[RevenueAmount]
--								,[AccountingType]
--								,[RRCalcTypeTrigger]
--								,[RRPercentage]
--								,[RRDays]
--								,[AttributeIDS])
--						select @SuspendCOAAccountId,
--								@SuspendRRRId,
--								@SuspendRRRCode,
--								@SuspendRRCalcTypeWhere,
--								@SuspendRRCalcTypeMethod,
--								@SuspendCOAAccountConfigId,
--								@SuspendCOAAccountTypeId,
--								@SuspendCOAAccountCode,
--								data_transaction.transactionid, 
--								data_transaction.saleid,
--								DATA_SaleItem.saleitemid,
--								DATA_SaleItem.Matrixcellid,
--								CNF_MatrixCell.Code,
--								CNF_MatrixCell.MatrixSheetid,
--								data_transaction.Siteid,
--								data_transaction.OperatingAreaId,
--								data_transaction.Workstationid,
--								data_transaction.UserGroupid,
--								data_transaction.UserId,
--								@BatchDate,
--								CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
--									 else data_transaction.TransactionDate
--								end TransactionDate,
--								Coalesce(DATA_SaleItem.Quantity, 1),
--								DATA_SaleItem.UnitPrice,
--								case when isnull(DATA_SaleItem.TotalAmount, 0) &lt;&gt; 0 then DATA_SaleItem.TotalAmount
--									when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
--									else DATA_Sale.TotalAmount
--								end,
--								case when isnull((DATA_SaleItem.TotalAmount - DATA_SaleItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_SaleItem.TotalAmount - DATA_SaleItem.TotalTaxes)
--									when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
--									else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
--								end as NetAmount,
--								@SuspendPrice,
--								@SuspendCOAAccount_Percentage,
--								@SuspendRemainingValues,
--								case    when (data_saleitem.ProductTaxType &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) 
--												  and (isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0) 
--													   and (((select discountamount from data_saleitemrule where saleitemid = DATA_SaleItem.saleitemid) &gt; 0) and (data_transaction.transactiontype in (7, 20, 22)))							
--											then ((DATA_SaleItem.UnitRawPrice + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)


--										when (data_saleitem.ProductTaxType &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice  + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)
--										when (data_saleitem.ProductTaxType = 1) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice - DATA_SaleItem.unittaxes + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)
--										when (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 then 0
--										when (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 and data_saleitem.unitRecharge &lt;&gt; 0 then data_saleitem.unitRecharge
--										when isnull((data_transaction.TotalAmount), 0) &lt;&gt; 0 then data_transaction.TotalAmount
--										when isnull((DATA_Sale.TotalAmount), 0) &lt;&gt; 0 then DATA_Sale.TotalAmount
--										else (data_transaction.Revenue)
--								end,
--								case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
--										when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
--										when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 1
--										when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 2
--										else @SuspendRRCOAAccountingType
--								end Accountingtype,
--								@SuspendRRCalcTypeTrigger,
--								@SuspendPercentage,
--								@SuspendDays,
--								CNF_AttributeSet.Attributeids
	   
--						from DATA_Sale
--							inner join data_transaction			on data_transaction.saleid = data_sale.saleid
--							left join DATA_SaleItem			    on DATA_SaleItem.saleid = DATA_Transaction.saleid
--							left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
--							left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

--						where DATA_Sale.Paid = 1
--							and data_transaction.transactiontype in (46, 47)
--							and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
--							   OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
--							and data_transaction.transactionid in (select transactionid
--																	from data_payment
--																	where PaymentStatus = 1
--																	and PaymentAmount &lt;&gt; 0
--																)


--					INSERT INTO [dbo].[RR_DATA_Revenue]
--								([COAAccountId]
--								,[RevenueRecognitionRuleId]
--								,[RRCode]
--								,[RRCalcTypeWhere]
--								,[RRCalcTypeMethod]
--								,[COAAccountConfigId]
--								,[COAAccountType]
--								,[COAAccountCode]
--								,[TransactionId]
--								,[SaleId]
--								,[SaleItemId]
--								,[MatrixCellId]
--								,[MatrixCellCode]
--								,[MatrixSheetID]
--								,[SiteId]
--								,[OperatingAreaId]
--								,[WorkstationId]
--								,[UserGroupId]
--								,[UserId]
--								,[FCalcDate]
--								,[FRevenueDate]
--								,[Quantity]
--								,[UnitAmount]
--								,[GrossAmount]
--								,[NetAmount]
--								,[Price]
--								,[Percentage]
--								,[RemaningValues]
--								,[RevenueAmount]
--								,[AccountingType]
--								,[RRCalcTypeTrigger]
--								,[RRPercentage]
--								,[RRDays]
--								,[AttributeIDS])
--						select @SuspendCOAAccountId,
--								@SuspendRRRId,
--								@SuspendRRRCode,
--								@SuspendRRCalcTypeWhere,
--								@SuspendRRCalcTypeMethod,
--								@SuspendCOAAccountConfigId,
--								@SuspendCOAAccountTypeId,
--								@SuspendCOAAccountCode,
--								data_transaction.transactionid, 
--								data_transaction.saleid,
--								DATA_TransactionItem.saleitemid,
--								DATA_SaleItem.Matrixcellid,
--								CNF_MatrixCell.Code,
--								CNF_MatrixCell.MatrixSheetid,
--								data_transaction.Siteid,
--								data_transaction.OperatingAreaId,
--								data_transaction.Workstationid,
--								data_transaction.UserGroupid,
--								data_transaction.UserId,
--								@BatchDate,
--								CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
--									 else data_transaction.TransactionDate
--								end TransactionDate,
--								Coalesce(DATA_TransactionItem.Quantity, 1),
--								DATA_SaleItem.UnitPrice,
--								case when isnull(DATA_TransactionItem.TotalAmount, 0) &lt;&gt; 0 then DATA_TransactionItem.TotalAmount
--									when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
--									else DATA_Sale.TotalAmount
--								end,
--								case when isnull((DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes)
--									when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
--									else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
--								end as NetAmount,
--								@SuspendPrice,
--								@SuspendCOAAccount_Percentage,
--								@SuspendRemainingValues,
--								DATA_SaleItem.Unitrecharge,
--								case    when TransactionType in (5, 17, 8, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
--										when TransactionType in (5, 17, 8, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
--										when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 2
--										when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 1
--										else @SuspendRRCOAAccountingType
--								end Accountingtype,
--								@SuspendRRCalcTypeTrigger,
--								@SuspendPercentage,
--								@SuspendDays,
--								CNF_AttributeSet.Attributeids
	   
--						from DATA_Sale
--							inner join data_transaction			on data_transaction.TransactionId = ISNULL(data_sale.voidtransactionid, DATA_Sale.PaidTransactionId)
--							left join DATA_TransactionItem		on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
--							left join DATA_SaleItem			    on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
--							left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
--							left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

--						where DATA_Sale.Paid = 1
--							and data_transaction.transactiontype in (10, 42, 43, 49)
--							and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
--							   OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
--							and data_transaction.transactionid in (select transactionid
--																	from data_payment
--																	where PaymentStatus = 1
--																	and PaymentAmount &lt;&gt; 0
--																)
			
--				INSERT INTO [dbo].[RR_DATA_Revenue]
--								([COAAccountId]
--								,[RevenueRecognitionRuleId]
--								,[RRCode]
--								,[RRCalcTypeWhere]
--								,[RRCalcTypeMethod]
--								,[COAAccountConfigId]
--								,[COAAccountType]
--								,[COAAccountCode]
--								,[TransactionId]
--								,[SaleId]
--								,[SaleItemId]
--								,[MatrixCellId]
--								,[MatrixCellCode]
--								,[MatrixSheetID]
--								,[SiteId]
--								,[OperatingAreaId]
--								,[WorkstationId]
--								,[UserGroupId]
--								,[UserId]
--								,[FCalcDate]
--								,[FRevenueDate]
--								,[Quantity]
--								,[UnitAmount]
--								,[GrossAmount]
--								,[NetAmount]
--								,[Price]
--								,[Percentage]
--								,[RemaningValues]
--								,[RevenueAmount]
--								,[AccountingType]
--								,[RRCalcTypeTrigger]
--								,[RRPercentage]
--								,[RRDays]
--								,[AttributeIDS])
--						select @SuspendCOAAccountId,
--								@SuspendRRRId,
--								@SuspendRRRCode,
--								@SuspendRRCalcTypeWhere,
--								@SuspendRRCalcTypeMethod,
--								@SuspendCOAAccountConfigId,
--								@SuspendCOAAccountTypeId,
--								@SuspendCOAAccountCode,
--								data_transaction.transactionid, 
--								data_transaction.saleid,
--								DATA_TransactionItem.saleitemid,
--								DATA_SaleItem.Matrixcellid,
--								CNF_MatrixCell.Code,
--								CNF_MatrixCell.MatrixSheetid,
--								data_transaction.Siteid,
--								data_transaction.OperatingAreaId,
--								data_transaction.Workstationid,
--								data_transaction.UserGroupid,
--								data_transaction.UserId,
--								@BatchDate,
--								CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
--									 else data_transaction.TransactionDate
--								end TransactionDate,
--								Coalesce(DATA_TransactionItem.Quantity, 1),
--								DATA_SaleItem.UnitPrice,
--								case when isnull(DATA_TransactionItem.TotalAmount, 0) &lt;&gt; 0 then DATA_TransactionItem.TotalAmount
--									when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
--									else DATA_Sale.TotalAmount
--								end,
--								case when isnull((DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes)
--									when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
--									else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
--								end as NetAmount,
--								@SuspendPrice,
--								@SuspendCOAAccount_Percentage,
--								@SuspendRemainingValues,
--								ABS(DATA_SaleItem.Unitrecharge),
--								case    when TransactionType in (5, 17, 8, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
--										when TransactionType in (5, 17, 8, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
--										when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 2
--										when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 1
--										else @SuspendRRCOAAccountingType
--								end Accountingtype,
--								@SuspendRRCalcTypeTrigger,
--								@SuspendPercentage,
--								@SuspendDays,
--								CNF_AttributeSet.Attributeids
	   
--						from DATA_Sale
--							inner join data_transaction			on data_transaction.TransactionId = ISNULL(data_sale.voidtransactionid, DATA_Sale.PaidTransactionId)
--							left join DATA_TransactionItem		on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
--							left join DATA_SaleItem			    on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
--							left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
--							left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

--						where DATA_Sale.Paid = 1
--							and data_transaction.transactiontype in (31, 48, 52)
--							and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
--							   OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
--							and data_transaction.transactionid in (select transactionid
--																	from data_payment
--																	where PaymentStatus = 1
--																	and PaymentAmount &lt;&gt; 0
--																   )


--					INSERT INTO [dbo].[RR_DATA_Revenue]
--										([COAAccountId]
--										,[RevenueRecognitionRuleId]
--										,[RRCode]
--										,[RRCalcTypeWhere]
--										,[RRCalcTypeMethod]
--										,[COAAccountConfigId]
--										,[COAAccountType]
--										,[COAAccountCode]
--										,[TransactionId]
--										,[SaleId]
--										,[SaleItemId]
--										,[MatrixCellId]
--										,[MatrixCellCode]
--										,[MatrixSheetID]
--										,[SiteId]
--										,[OperatingAreaId]
--										,[WorkstationId]
--										,[UserGroupId]
--										,[UserId]
--										,[FCalcDate]
--										,[FRevenueDate]
--										,[Quantity]
--										,[UnitAmount]
--										,[GrossAmount]
--										,[NetAmount]
--										,[Price]
--										,[Percentage]
--										,[RemaningValues]
--										,[RevenueAmount]
--										,[AccountingType]
--										,[RRCalcTypeTrigger]
--										,[RRPercentage]
--										,[RRDays]
--										,[AttributeIDS])
--								select @SuspendCOAAccountId,
--										@SuspendRRRId,
--										@SuspendRRRCode,
--										@SuspendRRCalcTypeWhere,
--										@SuspendRRCalcTypeMethod,
--										@SuspendCOAAccountConfigId,
--										@SuspendCOAAccountTypeId,
--										@SuspendCOAAccountCode,
--										data_transaction.transactionid, 
--										data_transaction.saleid,
--										DATA_TransactionItem.saleitemid,
--										DATA_SaleItem.Matrixcellid,
--										CNF_MatrixCell.Code,
--										CNF_MatrixCell.MatrixSheetid,
--										data_transaction.Siteid,
--										data_transaction.OperatingAreaId,
--										data_transaction.Workstationid,
--										data_transaction.UserGroupid,
--										data_transaction.UserId,
--										@BatchDate,
--										CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
--											 else data_transaction.TransactionDate
--										end TransactionDate,
--										Coalesce(DATA_TransactionItem.Quantity, 1),
--										DATA_SaleItem.UnitPrice,
--										case when isnull(DATA_TransactionItem.TotalAmount, 0) &lt;&gt; 0 then DATA_TransactionItem.TotalAmount
--											when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
--											else DATA_Sale.TotalAmount
--										end,
--										case when isnull((DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes)
--											when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
--											else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
--										end as NetAmount,
--										@SuspendPrice,
--										@SuspendCOAAccount_Percentage,
--										@SuspendRemainingValues,
--										case when (data_saleitem.ProductTaxType &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice + DATA_SaleItem.unittaxes) * DATA_SaleItem.Quantity)
--											 when (data_saleitem.ProductTaxType = 1) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice) * DATA_SaleItem.Quantity)
--											 when (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 then 0
--											 when isnull((data_transaction.TotalAmount), 0) &lt;&gt; 0 then data_transaction.TotalAmount
--											 when isnull((DATA_Sale.TotalAmount), 0) &lt;&gt; 0 then DATA_Sale.TotalAmount
--											 else (data_transaction.Revenue)
--										end,
--										case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
--												when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
--												when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 2
--												when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 1
--												else @SuspendRRCOAAccountingType
--										end Accountingtype,
--										@SuspendRRCalcTypeTrigger,
--										@SuspendPercentage,
--										@SuspendDays,
--										CNF_AttributeSet.Attributeids
	   
--								from DATA_Sale
--									inner join data_transaction			on data_transaction.Saleid = DATA_Sale.Saleid
--									left join DATA_TransactionItem		on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
--									left join DATA_SaleItem			    on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
--									left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
--									left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

--								where data_transaction.transactiontype in (8)
--									and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
--										OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
--									and data_transaction.transactionid in (select transactionid
--																			from data_payment
--																			where PaymentStatus = 1
--																			and PaymentAmount &lt;&gt; 0
--																		)

--							INSERT INTO [dbo].[RR_DATA_Revenue]
--										([COAAccountId]
--										,[RevenueRecognitionRuleId]
--										,[RRCode]
--										,[RRCalcTypeWhere]
--										,[RRCalcTypeMethod]
--										,[COAAccountConfigId]
--										,[COAAccountType]
--										,[COAAccountCode]
--										,[TransactionId]
--										,[SaleId]
--										,[SiteId]
--										,[OperatingAreaId]
--										,[WorkstationId]
--										,[UserGroupId]
--										,[UserId]
--										,[FCalcDate]
--										,[FRevenueDate]
--										,[Quantity]
--										,[GrossAmount]
--										,[NetAmount]
--										,[Price]
--										,[Percentage]
--										,[RemaningValues]
--										,[RevenueAmount]
--										,[AccountingType]
--										,[RRCalcTypeTrigger]
--										,[RRPercentage]
--										,[RRDays])
--								select @SuspendCOAAccountId,
--										@SuspendRRRId,
--										@SuspendRRRCode,
--										@SuspendRRCalcTypeWhere,
--										@SuspendRRCalcTypeMethod,
--										@SuspendCOAAccountConfigId,
--										@SuspendCOAAccountTypeId,
--										@SuspendCOAAccountCode,
--										data_transaction.transactionid, 
--										data_transaction.saleid,
--										data_transaction.Siteid,
--										data_transaction.OperatingAreaId,
--										data_transaction.Workstationid,
--										data_transaction.UserGroupid,
--										data_transaction.UserId,
--										@BatchDate,
--										CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
--											 else data_transaction.TransactionDate
--										end TransactionDate,
--										0 Quantity,
--										data_transaction.revenue TotalAmount,
--										data_transaction.revenue NetAmount,
--										@SuspendPrice,
--										@SuspendCOAAccount_Percentage,
--										@SuspendRemainingValues,
--										data_transaction.revenue,
--										@SuspendRRCOAAccountingType,
--										@SuspendRRCalcTypeTrigger,
--										@SuspendPercentage,
--										@SuspendDays
	   
--								from DATA_Sale
--									inner join data_transaction			on data_transaction.saleid = DATA_Sale.saleid
--								where data_transaction.transactiontype = 12
--									and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
--										OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
--									and data_transaction.transactionid in (select transactionid
--																			from data_payment
--																			where PaymentStatus = 1
--																			and PaymentAmount &lt;&gt; 0
--																		)



--								INSERT INTO [dbo].[RR_DATA_Revenue]
--										([COAAccountId]
--										,[RevenueRecognitionRuleId]
--										,[RRCode]
--										,[RRCalcTypeWhere]
--										,[RRCalcTypeMethod]
--										,[COAAccountConfigId]
--										,[COAAccountType]
--										,[COAAccountCode]
--										,[TransactionId]
--										,[SaleId]
--										,[SaleItemId]
--										,[MatrixCellId]
--										,[MatrixCellCode]
--										,[MatrixSheetID]
--										,[SiteId]
--										,[OperatingAreaId]
--										,[WorkstationId]
--										,[UserGroupId]
--										,[UserId]
--										,[FCalcDate]
--										,[FRevenueDate]
--										,[Quantity]
--										,[UnitAmount]
--										,[GrossAmount]
--										,[NetAmount]
--										,[Price]
--										,[Percentage]
--										,[RemaningValues]
--										,[RevenueAmount]
--										,[AccountingType]
--										,[RRCalcTypeTrigger]
--										,[RRPercentage]
--										,[RRDays]
--										,[AttributeIDS])
--										select *
--										from (
--								select @SuspendCOAAccountId as COAAccountId,
--										@SuspendRRRId as RevenueRecognitionRuleId,
--										@SuspendRRRCode as RRCode,
--										@SuspendRRCalcTypeWhere as RRCalcTypeWhere,
--										@SuspendRRCalcTypeMethod as RRCalcTypeMethod,
--										@SuspendCOAAccountConfigId as COAAccountConfigId,
--										@SuspendCOAAccountTypeId as COAAccountType,
--										@SuspendCOAAccountCode as COAAccountCode,
--										data_transaction.transactionid, 
--										data_transaction.saleid,
--										DATA_SaleItem.saleitemid,
--										DATA_SaleItem.Matrixcellid,
--										CNF_MatrixCell.Code,
--										CNF_MatrixCell.MatrixSheetid,
--										data_transaction.Siteid,
--										data_transaction.OperatingAreaId,
--										data_transaction.Workstationid,
--										data_transaction.UserGroupid,
--										data_transaction.UserId,
--										@BatchDate as calcdate,
--										CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
--												else data_transaction.TransactionDate
--										end TransactionDate,
--										Coalesce(DATA_SaleItem.Quantity, 1) as quantity,
--										DATA_SaleItem.UnitPrice,
--										case when isnull(DATA_SaleItem.TotalAmount, 0) &lt;&gt; 0 then DATA_SaleItem.TotalAmount
--											when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
--											else DATA_Sale.TotalAmount
--										end as totalamount,
--										case when isnull((DATA_SaleItem.TotalAmount - DATA_SaleItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_SaleItem.TotalAmount - DATA_SaleItem.TotalTaxes)
--											when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
--											else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
--										end as NetAmount,
--										@SuspendPrice as suspendprice,
--										@SuspendCOAAccount_Percentage as percentage,
--										@SuspendRemainingValues as remainingValues,
--										case when (data_saleitem.ProductTaxType &lt;&gt; 1) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice) * DATA_SaleItem.Quantity)
--											 when (data_saleitem.ProductTaxType = 1) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice - DATA_SaleItem.unittaxes) * DATA_SaleItem.Quantity)
--											 when isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 then 0
--											 when isnull((data_transaction.TotalAmount), 0) &lt;&gt; 0 then data_transaction.TotalAmount
--											 when isnull((DATA_Sale.TotalAmount), 0) &lt;&gt; 0 then DATA_Sale.TotalAmount
--											 else (data_transaction.Revenue)
--										end as Revenueamount,
--										case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
--												when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
--												when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 2
--												when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 1
--												else @SuspendRRCOAAccountingType
--										end Accountingtype,
--										@SuspendRRCalcTypeTrigger as rrTrigger,
--										@SuspendPercentage as suspercentage,
--										@SuspendDays as suspendday,
--										CNF_AttributeSet.Attributeids
	   
--								from DATA_Sale
--									inner join data_transaction			on data_transaction.TransactionId = DATA_Sale.PaidTransactionId
--									left join DATA_SaleItem			    on DATA_SaleItem.SAleid = data_transaction.SAleid
--									left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
--									left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

--				where DATA_Sale.Paid = 1
--					and data_transaction.transactiontype in (16)
--					and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
--					 OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
--					and data_transaction.transactionid in (select transactionid
--															from data_payment
--															where PaymentStatus = 1
--															--and PaymentAmount &lt;&gt; 0
--														)
--					and DATA_SaleItem.saleitemid not in (select distinct rr_data_Revenue.saleitemid
--																from rr_data_Revenue																		
--																where rr_data_Revenue.saleitemid is not null)
--					and data_saleitem.saleitemid not in (select distinct data_saleitem.saleitemid
--													from data_saleitem
--															inner join data_transactionitem   on data_transactionitem.saleitemid = data_saleitem.saleitemid
--															inner join data_transaction       on data_transaction.transactionid = data_transactionitem.transactionid
--													where data_transaction.transactiontype in (5)
--													)
--					)p  where UnitPrice &lt;&gt; 0


--								INSERT INTO [dbo].[RR_DATA_Revenue]
--										([COAAccountId]
--										,[RevenueRecognitionRuleId]
--										,[RRCode]
--										,[RRCalcTypeWhere]
--										,[RRCalcTypeMethod]
--										,[COAAccountConfigId]
--										,[COAAccountType]
--										,[COAAccountCode]
--										,[TransactionId]
--										,[SaleId]
--										,[SaleItemId]
--										,[MatrixCellId]
--										,[MatrixCellCode]
--										,[MatrixSheetID]
--										,[SiteId]
--										,[OperatingAreaId]
--										,[WorkstationId]
--										,[UserGroupId]
--										,[UserId]
--										,[FCalcDate]
--										,[FRevenueDate]
--										,[Quantity]
--										,[UnitAmount]
--										,[GrossAmount]
--										,[NetAmount]
--										,[Price]
--										,[Percentage]
--										,[RemaningValues]
--										,[RevenueAmount]
--										,[AccountingType]
--										,[RRCalcTypeTrigger]
--										,[RRPercentage]
--										,[RRDays]
--										,[AttributeIDS])
--								select @SuspendCOAAccountId,
--										@SuspendRRRId,
--										@SuspendRRRCode,
--										@SuspendRRCalcTypeWhere,
--										@SuspendRRCalcTypeMethod,
--										@SuspendCOAAccountConfigId,
--										@SuspendCOAAccountTypeId,
--										@SuspendCOAAccountCode,
--										data_transaction.transactionid, 
--										data_transaction.saleid,
--										DATA_TransactionItem.saleitemid,
--										DATA_SaleItem.Matrixcellid,
--										CNF_MatrixCell.Code,
--										CNF_MatrixCell.MatrixSheetid,
--										data_transaction.Siteid,
--										data_transaction.OperatingAreaId,
--										data_transaction.Workstationid,
--										data_transaction.UserGroupid,
--										data_transaction.UserId,
--										@BatchDate,
--										CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
--											 else data_transaction.TransactionDate
--										end TransactionDate,
--										Coalesce(DATA_TransactionItem.Quantity, 1),
--										DATA_SaleItem.UnitPrice,
--										case when isnull(DATA_TransactionItem.TotalAmount, 0) &lt;&gt; 0 then DATA_TransactionItem.TotalAmount
--											when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
--											else DATA_Sale.TotalAmount
--										end,
--										case when isnull((DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes)
--											when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
--											else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
--										end as NetAmount,
--										@SuspendPrice,
--										@SuspendCOAAccount_Percentage,
--										@SuspendRemainingValues,
--										case when isnull((DATA_TransactionItem.UnitPrice *  DATA_TransactionItem.Quantity), 0) &lt;&gt; 0 then (DATA_TransactionItem.UnitPrice *  DATA_TransactionItem.Quantity)
--											when isnull((data_transaction.TotalAmount), 0) &lt;&gt; 0 then data_transaction.TotalAmount
--											when isnull((DATA_Sale.TotalAmount), 0) &lt;&gt; 0 then DATA_Sale.TotalAmount
--											else (data_transaction.Revenue)
--										end,
--										case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
--												when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
--												when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 2
--												when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 1
--												else @SuspendRRCOAAccountingType
--										end Accountingtype,
--										@SuspendRRCalcTypeTrigger,
--										@SuspendPercentage,
--										@SuspendDays,
--										CNF_AttributeSet.Attributeids
	   
--								from DATA_Sale
--									inner join data_transaction			on data_transaction.saleid = DATA_Sale.saleid
--									inner join DATA_TransactionItem		on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
--									left join DATA_SaleItem			    on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
--									left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
--									left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

--								where DATA_Sale.Paid = 1
--									and data_transaction.transactiontype in (5)
--									and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
--									 OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
					
--									and data_transaction.transactionid in (select transactionid
--																			from data_payment
--																			where PaymentStatus = 1
--																			and PaymentAmount &lt;&gt; 0
--																		)
--									and data_transaction.transactionid not in (select distinct transactionid
--																				from rr_data_Revenue
--																				where transactionid is not null)

--				--PaymentMethod
--								INSERT INTO [dbo].[RR_DATA_Revenue]
--												([COAAccountId]
--												,[RevenueRecognitionRuleId]
--												,[RRCode]
--												,[RRCalcTypeWhere]
--												,[RRCalcTypeMethod]
--												,[COAAccountConfigId]
--												,[COAAccountType]
--												,[COAAccountCode]
--												,[TransactionId]
--												,[SaleId]
--												,[SiteId]
--												,[OperatingAreaId]
--												,[WorkstationId]
--												,[UserGroupId]
--												,[UserId]
--												,[FCalcDate]
--												,[FRevenueDate]
--												,[Quantity]
--												,[GrossAmount]
--												,[NetAmount]
--												,[Price]
--												,[Percentage]
--												,[RemaningValues]
--												,[RevenueAmount]
--												,[AccountingType]
--												,[RRCalcTypeTrigger]
--												,[RRPercentage]
--												,[RRDays])
--												select  coaaccountid,
--														RRID,
--														RRCode,
--														TypeWhere,
--														method,
--														Configid,
--														AccountType,
--														AccountCode,
--														transactionid, 
--														saleid,
--														Siteid,
--														OperatingAreaId,
--														WorkstationID,
--														UserGroupid,
--														UserId,
--														BatchDate,
--														TransactionDate,
--														Qty,
--														Gross,
--														net,
--														price,
--														percentage,
--														RemaningValue,
--														sum(abs(RevenueAmount)),
--														Accountingtype,
--														TypeTrigger,
--														PaymentPercentage,
--														RRDays
--												from (
--												select  coaaccountid,
--														RRID,
--														RRCode,
--														TypeWhere,
--														method,
--														Configid,
--														AccountType,
--														AccountCode,
--														transactionid, 
--														saleid,
--														Siteid,
--														OperatingAreaId,
--														WorkstationID,
--														UserGroupid,
--														UserId,
--														BatchDate,
--														TransactionDate,
--														Qty,
--														Gross,
--														net,
--														price,
--														percentage,
--														RemaningValue,
--														case when Rownumber = 1 then RevenueAmount + Change
--															 else RevenueAmount
--														 end RevenueAmount,
--														Accountingtype,
--														TypeTrigger,
--														PaymentPercentage,
--														RRDays
--												from (
--												select @PaymentCOAAccountId as coaaccountid,
--														@PaymentRRRId as RRID,
--														@PaymentRRRCode as RRCode,
--														@PaymentRRCalcTypeWhere as TypeWhere,
--														@PaymentRRCalcTypeMethod as method,
--														@PaymentCOAAccountConfigId as Configid,
--														@PaymentCOAAccountTypeId as AccountType,
--														@PaymentCOAAccountCode as AccountCode,
--														data_transaction.transactionid, 
--														data_transaction.saleid,
--														data_transaction.Siteid,
--														data_transaction.OperatingAreaId,
--														data_transaction.Workstationid,
--														data_transaction.UserGroupid,
--														data_transaction.UserId,
--														@BatchDate as BatchDate,
--														CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
--															 else data_transaction.TransactionDate
--														end TransactionDate,
--														0 as Qty,
--														0 as Gross,
--														0 as net,
--														0 as price,
--														100 as percentage,
--														0 as RemaningValue,
--														(data_payment.PaymentAmount) as RevenueAmount,
--														case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @PaymentRRCOAAccountingType = 1 then 2
--																when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @PaymentRRCOAAccountingType = 2 then 1
--																when TransactionType in (7) and (data_payment.PaymentAmount + data_Payment.PaymentFee) &lt;= 0  then 2
--																when TransactionType in (7) and (data_payment.PaymentAmount + data_Payment.PaymentFee) &gt; 0  then 1
--																else @PaymentRRCOAAccountingType
--														end Accountingtype,
--														data_transaction.Change,
--														@PaymentRRCalcTypeTrigger as TypeTrigger,
--														@PaymentPercentage as PaymentPercentage,
--														@PaymentDays as RRDays,
--														Row_Number ()  OVER (PARTITION BY data_transaction.transactionid order by data_transaction.transactionid)  as Rownumber
		  
--												from DATA_Sale
--															INNER join data_transaction			on ((data_transaction.TransactionId = Isnull(data_sale.voidtransactionid, DATA_Sale.PaidTransactionId)) or 
--																								   (data_transaction.saleid = data_sale.saleid))
--															INNER JOIN DATA_Payment				on data_payment.transactionid = data_transaction.transactionid
			
--												where data_payment.PaymentStatus = 1
--													and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
--													 OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
--											)p
--											)r
--											group by 	coaaccountid,
--														RRID,
--														RRCode,
--														TypeWhere,
--														method,
--														Configid,
--														AccountType,
--														AccountCode,
--														transactionid, 
--														saleid,
--														Siteid,
--														OperatingAreaId,
--														Workstationid,
--														UserGroupid,
--														UserId,
--														BatchDate,
--														TransactionDate,
--														Qty,
--														Gross,
--														net,
--														price,
--														percentage,
--														RemaningValue,
--														Accountingtype,
--														TypeTrigger,
--														PaymentPercentage,
--														RRDays
--											Having sum(abs(RevenueAmount)) &lt;&gt; 0
						



--				--Tax
--									INSERT INTO [dbo].[RR_DATA_Revenue]
--												([COAAccountId]
--												,[RevenueRecognitionRuleId]
--												,[RRCode]
--												,[RRCalcTypeWhere]
--												,[RRCalcTypeMethod]
--												,[COAAccountConfigId]
--												,[COAAccountType]
--												,[COAAccountCode]
--												,[TransactionId]
--												,[SaleId]
--												,[SiteId]
--												,[OperatingAreaId]
--												,[WorkstationId]
--												,[UserGroupId]
--												,[UserId]
--												,[FCalcDate]
--												,[FRevenueDate]
--												,[Quantity]
--												,[GrossAmount]
--												,[NetAmount]
--												,[Price]
--												,[Percentage]
--												,[RemaningValues]
--												,[RevenueAmount]
--												,[AccountingType]
--												,[RRCalcTypeTrigger]
--												,[RRPercentage]
--												,[RRDays])

--												select  @TaxCOAAccountId,
--														@TaxRRRId,
--														@TaxRRRCode,
--														@TaxRRCalcTypeWhere,
--														@TaxRRCalcTypeMethod,
--														@TaxCOAAccountConfigId,
--														@TaxCOAAccountTypeId,
--														@TaxCOAAccountCode,
--														data_transaction.transactionid, 
--														data_transaction.saleid,
--														data_transaction.Siteid,
--														data_transaction.OperatingAreaId,
--														data_transaction.Workstationid,
--														data_transaction.UserGroupid,
--														data_transaction.UserId,
--														@BatchDate,
--														CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
--															 else data_transaction.TransactionDate
--														end TransactionDate,
--														0,
--														0,
--														0,
--														0,
--														100,
--														0,
--														ABS(sum(taxamount)) RevenueAmount,
--														case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @TaxRRCOAAccountingType = 1 then 2
--																when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @TaxRRCOAAccountingType = 2 then 1
--																when TransactionType in (7) and sum(taxamount) &lt;= 0  then 1
--																when TransactionType in (7) and sum(taxamount) &gt; 0  then 2
--																else @TaxRRCOAAccountingType
--														end Accountingtype,
--														@TaxRRCalcTypeTrigger,
--														@TaxPercentage,
--														@TaxDays
		   
--											from Data_Sale
--												INNER JOIN DATA_Transaction						on data_transaction.Saleid = Data_Sale.Saleid
--												INNER JOIN DATA_TransactionTax					on data_transactiontax.transactionid = data_transaction.transactionid
--												INNER JOIN CNF_Tax								on cnf_tax.taxid = DATA_TransactionTax.taxid
--												--INNER JOIN coa_cnf_account coa					on coa.coaaccountid = cnf_tax.coaaccountid


--											where transactiontype NOT IN (33, 45, 46, 47)
--											   and Data_Sale.paid = 1
--												and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
--												 OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
--												  and data_transaction.transactionid in (select distinct transactionid
--																						   from data_payment
--																						   where data_payment.paymentstatus = 1
--																						)
--											group by 			data_transaction.transactionid, 
--																data_transaction.saleid,
--																data_transaction.Siteid,
--																data_transaction.OperatingAreaId,
--																data_transaction.Workstationid,
--																data_transaction.UserGroupid,
--																data_transaction.UserId,
--																Data_Transaction.TransactionDate,
--																TransactionType,
--																fTransactionDate


--				--Discount

--										INSERT INTO [dbo].[RR_DATA_Revenue]
--												([COAAccountId]
--												,[RevenueRecognitionRuleId]
--												,[RRCode]
--												,[RRCalcTypeWhere]
--												,[RRCalcTypeMethod]
--												,[COAAccountConfigId]
--												,[COAAccountType]
--												,[COAAccountCode]
--												,[TransactionId]
--												,[SaleId]
--												,[Saleitemid]
--												,[SiteId]
--												,[OperatingAreaId]
--												,[WorkstationId]
--												,[UserGroupId]
--												,[UserId]
--												,[FCalcDate]
--												,[FRevenueDate]
--												,[Quantity]
--												,[GrossAmount]
--												,[NetAmount]
--												,[Price]
--												,[Percentage]
--												,[RemaningValues]
--												,[RevenueAmount]
--												,[AccountingType]
--												,[RRCalcTypeTrigger]
--												,[RRPercentage]
--												,[RRDays])

--												select  @DiscountCOAAccountId,
--														@DiscountRRRId,
--														@DiscountRRRCode,
--														@DiscountRRCalcTypeWhere,
--														@DiscountRRCalcTypeMethod,
--														@DiscountCOAAccountConfigId,
--														@DiscountCOAAccountTypeId,
--														@DiscountCOAAccountCode,
--														data_transaction.transactionid, 
--														data_transaction.saleid,
--														p.Saleitemid,
--														data_transaction.Siteid,
--														data_transaction.OperatingAreaId,
--														data_transaction.Workstationid,
--														data_transaction.UserGroupid,
--														data_transaction.UserId,
--														@BatchDate,
--														CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
--															 else data_transaction.TransactionDate
--														end TransactionDate,
--														0,
--														0,
--														0,
--														0,
--														100,
--														0,
--														ABS(p.GLAmount) RevenueAmount,
--														case    when data_transaction.TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) then 2
--																when data_transaction.TransactionType in (7) and (GLAmount) &lt;= 0  then 2
--																when data_transaction.TransactionType in (7) and (GLAmount) &gt; 0  then 1
--																else @DiscountRRCOAAccountingType
--														end Accountingtype,

--														@DiscountRRCalcTypeTrigger,
--														@DiscountPercentage,
--														@DiscountDays
--											FROM
--											(
--												SELECT distinct DATA_SaleItem.Saleitemid,
--																DATA_Sale.saleid AS SAleid,
--      															DATA_Transaction.TransactionType,
--      															( SELECT top 1 transactionid
--																	FROM data_transaction		WITH (NOLOCK)
--																   WHERE saleid = DATA_Sale.saleid
--																	AND transactiontype in (14, 16)
--																	AND paid = 1
--																) AS tester,

--																CASE WHEN DATA_Transaction.TransactionId IN (
--																											  SELECT TR.TransactionID
--																												FROM DATA_Transaction TR			WITH (NOLOCK)
--																													LEFT JOIN DATA_Payment DP		WITH (NOLOCK) ON TR.TransactionId = DP.TransactionId
--																											  WHERE TR.SaleId = DATA_Sale.SaleId
--																												AND TR.Paid = 1
--																												AND DP.PaymentStatus NOT IN (0, 2, 3)
--																											)
      
--																			THEN DATA_Transaction.Transactionid
--																	 ELSE (
--																			  SELECT MIN(TR.TransactionID)
--																				FROM DATA_Transaction TR				WITH (NOLOCK)
--																					LEFT JOIN DATA_Payment DP			WITH (NOLOCK) ON TR.TransactionId = DP.TransactionId
--																			   WHERE TR.SaleId = DATA_Sale.saleid
--																				 AND TR.TransactionType = 16
--																				 AND TR.Paid = 1
--																				 AND DP.PaymentStatus NOT IN (0, 2, 3)
--																		  )
--																END Transactionid, 
--																 CASE WHEN CNF_Promotion.PromotionType = 1 AND CNF_PromotionItemRule.NewProduct = 1 THEN  (CNF_MatrixCell.Price - SUM(DATA_SaleItemRule.DiscountAmount))
--																	  ELSE  CASE WHEN sum(1*data_saleItemRule.DiscountAmount) &lt; 0 AND transactiontype IN(20, 22, 30, 7, 5, 46, 47) AND
--																																												(SELECT Count(*) 
--																																												   FROM data_transaction WITH (NOLOCK)
--																																												  WHERE saleid = data_sale.saleid
--																																												 ) = 1 					  					  					  										  
--																					  THEN Sum(1 * DATA_SaleItemRule.DiscountAmount)
--																				 WHEN sum(1*data_saleItemRule.DiscountAmount) &lt; 0 THEN	Sum(-1 * DATA_SaleItemRule.DiscountAmount)
--																				 WHEN sum(1*data_saleItemRule.DiscountAmount) &gt; 0 AND transactiontype IN(20, 22, 30, 7, 5, 46, 47) THEN Sum(-1 * DATA_SaleItemRule.DiscountAmount)		            	                  
--																				 ELSE sum(1*Data_SaleItemRule.DiscountAmount)
--																			END
--																END AS GLAmount


--												FROM dbo.DATA_SaleItemRule				WITH (NOLOCK)
--													LEFT JOIN dbo.CNF_PromotionItemRule WITH (NOLOCK) ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
--													LEFT JOIN dbo.CNF_PromotionItem		WITH (NOLOCK) ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
--													LEFT JOIN dbo.CNF_Promotion			WITH (NOLOCK) ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId
--													LEFT JOIN dbo.CNF_DmgCategory		WITH (NOLOCK) ON CNF_DmgCategory.DmgCategoryId = CNF_Promotion.DmgCategoryId
--													LEFT JOIN dbo.DATA_SaleItem			WITH (NOLOCK) ON DATA_SaleItem.SaleItemId = DATA_SaleItemRule.SaleItemId
--													LEFT JOIN dbo.DATA_Sale				WITH (NOLOCK) ON DATA_Sale.SaleID = DATA_SaleItem.SaleID
--													LEFT JOIN DATA_TransactionItem		WITH (NOLOCK) ON DATA_TransactionItem.SaleItemId = DATA_SaleItem.SaleItemId 
--													LEFT JOIN DATA_Transaction			WITH (NOLOCK) ON  DATA_Transaction.TransactionId = DATA_TransactionItem.TransactionId
--													LEFT JOIN CNF_MatrixCell			WITH (NOLOCK) ON CNF_MatrixCell.MatrixCellId =  DATA_SaleItem.MatrixCellId

 
--												WHERE DATA_Transaction.saleid in (
--																					SELECT ff.saleid 
--																					  FROM DATA_Transaction ff WITH (NOLOCK) 
--																						LEFT JOIN Data_Payment WITH (NOLOCK) on (ff.Transactionid = Data_Payment.Transactionid) 
--																					 WHERE  ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
--																						OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
--																					   AND DATA_PAyment.PaymentStatus NOT in (0,2,3) 
--																					   AND (TransactionType not in (12)) 
--																					   AND ff.PAid = 1
--																				 )  

--												 AND DATA_Sale.Paid = 1
--												 and transactiontype NOT IN (33, 45, 46, 47)
--												 AND ((DATA_SaleItem.quantity &gt; 0) OR ((DATA_SaleItem.quantity &lt; 0) AND (transactiontype IN (20, 22, 30, 7, 5, 46, 47))))

         
--												group BY DATA_SaleItem.Saleitemid,
--														 DATA_Sale.saleid,
--														 Data_transaction.Paid,
--														 Data_Transaction.Transactionid,
--														 Data_Transaction.fTransactionDate,
--														 Data_Saleitem.Matrixcellid,
--														 CNF_DmgCategory.DmgCategoryCode,
--														 PromotionType,
--														 CNF_PromotionItemRule.NewProduct,
--														 CNF_MatrixCell.Price,
--														 transactiontype,
--														 CNF_DmgCategory.Description
--											)p
--												LEFT JOIN data_transaction WITH (NOLOCK) on data_transaction.transactionid = p.transactionid

--											WHERE ((p.TransactionType &lt;&gt; 5) or (Tester is not null))
--											  AND data_transaction.transactionid is not null


					
--						--End Move Transactions to Suspend Account

--						exec otn_sp_RR_RevenueData_OnDepositTrigger @BatchDate, @RRTransDateType

--						exec otn_sp_RR_RevenueData_OnSaleTrigger @BatchDate, @RRTransDateType
		
--						exec otn_sp_RR_RevenueData_OnMoneyCardLoad @BatchDate, @RRTransDateType

--						exec otn_sp_RR_RevenueData_OnMoneyCardCashOut @BatchDate, @RRTransDateType

--						exec otn_sp_RR_RevenueData_OnExternalMoneyCardCashOut @BatchDate, @RRTransDateType

--						exec otn_sp_RR_RevenueData_OnExternalMoneyCardLoad @BatchDate, @RRTransDateType

--						exec otn_sp_RR_RevenueData_OnCreditWriteoff @BatchDate, @RRTransDateType

--						exec otn_sp_RR_RevenueData_OnMoneyRefundTrigger @BatchDate, @RRTransDateType

--						exec otn_sp_RR_RevenueData_OnAdvancedPaymentTrigger @BatchDate, @RRTransDateType
		
--						--exec otn_sp_RR_RevenueData_OnFlexContractPayment @BatchDate, @RRTransDateType

--						--exec otn_sp_RR_RevenueData_OnFlexContractCancelled @BatchDate, @RRTransDateType

--						exec otn_sp_RR_RevenueData_OnCreditSettlementTrigger @BatchDate, @RRTransDateType
		
--						exec otn_sp_RR_RevenueData_SettleUpSuspendAccount @BatchDate, @RRTransDateType


--						exec otn_sp_RR_RevenueData_OnTicketUsageTrigger @BatchDate, @RRTransDateType

--						exec otn_sp_RR_RevenueData_OnEventTrigger @BatchDate, @RRTransDateType

--						exec otn_sp_RR_RevenueData_OnTimePeriodTrigger @BatchDate, @RRTransDateType

--						exec otn_sp_RR_RevenueData_OnTicketExpiredTrigger @BatchDate, @RRTransDateType

--						exec otn_sp_RR_RevenueData_OnChangeValiditydateTrigger @BatchDate, @RRTransDateType
		

--	FETCH NEXT FROM date_Cursor INTO
--		@BatchDate

--end

--End</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_RR_RevenueData_PaymentMethodTaxDiscounts]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_RR_RevenueData_PaymentMethodTaxDiscounts</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>CREATE Procedure dbo.otn_sp_RR_RevenueData_PaymentMethodTaxDiscounts
	@BatchDate Date,
	@Transactions varchar(500),
	@Trigger int,
	@RRTransDateType integer
AS 
BEGIN
	 
	Create Table #TransactionIDs(
	TransactionId Int NOT NULL)

	DECLARE @DelimPosition INT

    SET @DelimPosition = CHARINDEX(',', @Transactions)

    WHILE @DelimPosition &gt; 0
    BEGIN
        INSERT INTO #TransactionIDs(TransactionId)
            VALUES(CAST(RTRIM(LEFT(@Transactions, @DelimPosition - 1)) AS INT))
        SET @Transactions = right(@Transactions, len(@Transactions) - @DelimPosition)

        SET @DelimPosition = CHARINDEX(',', @Transactions)
    END

	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer

	Declare @OnCreditWriteoff Integer = 9
	Declare @StartTime DateTime

	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1
	

		--	--	--Normal Sale Split out the Payments to Smaller Subset.
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])				    
						select distinct COA.COAAccountId, 
						   p.RevenueRecognitionRuleId,
						   p.RRCode,		   
						   p.RRCalcTypeWhere,
						   p.RRCalcTypeMethod,	   
						   p.COAAccountConfigId,
						   COA.COAAccountTypeId,
						   COA.Code,
						   RR_DATA_REVENUE.Transactionid as Transactionid,
						   RR_DATA_REVENUE.saleid as Saleid,
						   RR_DATA_REVENUE.Siteid as SiteID,
						   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
						   RR_DATA_REVENUE.Workstationid as Workstationid,
						   RR_DATA_REVENUE.UserGroupid as UserGroupID,
						   RR_DATA_REVENUE.UserId as userID,
						   @BatchDate,
						   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
							    else DATA_Transaction.transactiondate
						   end as TransDate,
						   0,
						   0,
						   0,
						   0,
						   100,
						   0, 	
						   (data_payment.PaymentAmount) -
						   (case when data_payment.paymentid = (select top 1 paymentid
																from data_payment
																where transactionid = RR_DATA_REVENUE.Transactionid
																	and data_payment.paymentamount &gt; (select sum(Change) *-1
																								from data_transaction
																								where data_transaction.transactionid = RR_DATA_REVENUE.Transactionid))
								then (select sum(Change) *-1
																								from data_transaction
																								where data_transaction.transactionid = RR_DATA_REVENUE.Transactionid)
								else 0
							end )
							as RevenueAmount,
							p.Accountingtype,		
						    p.RRCalcTypeTrigger,
						    p.RRPercentage,
						    p.RRDays

						from RR_DATA_REVENUE
						INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
						INNER JOIN data_payment							on data_payment.transactionid = rr_data_revenue.transactionid
						left  JOIN DATA_PaymentCard						on data_paymentcard.paymentid = data_payment.PaymentId
						left JOIN CNF_PaymentCard						on cnf_paymentcard.paymentcardid = data_paymentcard.paymentcardid
						INNER JOIN CNF_PaymentMethod					on CNF_PaymentMethod.PaymentMethodId = data_payment.PaymentMethodId
						INNER JOIN COA_CNF_Account COA					on COA.COAAccountid = ISNULL(cnf_paymentcard.coaaccountid, CNF_PaymentMethod.COAAccountid)

						INNER JOIN (select transactionid, RevenueRecognitionRuleId, RR_DATA_Revenue.RRCode, RRCalcTypeWhere, 
											RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount,  Accountingtype
											from RR_DATA_Revenue
											INNER JOIN COA_CNF_Account		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
											where COA_CNF_Account.coaAccountID = @ACCPaymentMethod
											--and RR_DATA_Revenue.RRCalcTypeTrigger = @Trigger
											and RR_DATA_REVENUE.fcalcdate = @BatchDate
										)p    on p.transactionid = 	data_payment.transactionid

					where data_payment.paymentstatus = 1
					and DATA_Transaction.TransactionType in (select transactionid
																from #TransactionIDs)
					and RR_DATA_REVENUE.fcalcdate = @BatchDate
					--and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
					AND data_payment.Transactionid not in (select distinct transactionid
												from rr_Data_Revenue
												where matrixcellid is null
												  and coaaccountid in (select distinct coaaccountid
																			from cnf_paymentmethod CP
																			where coaaccountid is not null
																			union all
																			select distinct coaaccountid
																			from cnf_paymentcard pc
																			where coaaccountid is not null
																		)
																			and transactionid is not null
												)
					AND data_payment.Transactionid in (select distinct transactionid
												from rr_Data_Revenue
												where coaaccountid in (@ACCPaymentMethod)
												)
					 AND RR_DATA_REVENUE.coaaccountid not in (@ACCPaymentMethod)


		----Normal Sale Split out the Payments to Payment Fees
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])				    
				select distinct COA.COAAccountId, 
						   p.RevenueRecognitionRuleId,
						   p.RRCode,		   
						   p.RRCalcTypeWhere,
						   p.RRCalcTypeMethod,	   
						   p.COAAccountConfigId,
						   COA.COAAccountTypeId,
						   COA.Code,
						   RR_DATA_REVENUE.Transactionid as Transactionid,
						   RR_DATA_REVENUE.saleid as Saleid,
						   RR_DATA_REVENUE.Siteid as SiteID,
						   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
						   RR_DATA_REVENUE.Workstationid as Workstationid,
						   RR_DATA_REVENUE.UserGroupid as UserGroupID,
						   RR_DATA_REVENUE.UserId as userID,
						   @BatchDate,
						   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
							    else DATA_Transaction.transactiondate
						   end as TransDate,
						   0,
						   0,
						   0,
						   0,
						   100,
						   0,  	
						   data_payment.paymentfee as RevenueAmount,
						   case when data_payment.paymentfee &gt;= 0 then 2
						        else 1
							end accountingtype,		
						   p.RRCalcTypeTrigger,
						   p.RRPercentage,
						   p.RRDays

						from RR_DATA_REVENUE
						INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
						INNER JOIN data_payment							on data_payment.transactionid = rr_data_revenue.transactionid
						left  JOIN DATA_PaymentCard						on data_paymentcard.paymentid = data_payment.PaymentId
						left JOIN CNF_PaymentCard						on cnf_paymentcard.paymentcardid = data_paymentcard.paymentcardid
						INNER JOIN CNF_PaymentMethod					on CNF_PaymentMethod.PaymentMethodId = data_payment.PaymentMethodId
						INNER JOIN COA_CNF_Account COA					on COA.COAAccountid = CNF_PaymentMethod.FeeCOAAccountId

						INNER JOIN (select transactionid, RevenueRecognitionRuleId, RR_DATA_Revenue.RRCode, RRCalcTypeWhere, 
											RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount,  Accountingtype
											from RR_DATA_Revenue
											INNER JOIN COA_CNF_Account		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
											where COA_CNF_Account.coaAccountID = @ACCPaymentMethod
										)p    on p.transactionid = 	data_payment.transactionid

					where data_payment.paymentstatus = 1
					and DATA_Transaction.TransactionType in (select transactionid
																from #TransactionIDs)
					and data_payment.paymentfee &lt;&gt; 0
					and RR_DATA_REVENUE.fcalcdate = @BatchDate
					--and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
					AND data_payment.Transactionid not in (select distinct transactionid
												from rr_Data_Revenue
												where coaaccountid in (select distinct FeeCOAAccountId
																			from cnf_paymentmethod CP
																		)
																			and transactionid is not null
												)
					AND data_payment.Transactionid in (select distinct transactionid
												from rr_Data_Revenue
												where coaaccountid in (@ACCPaymentMethod)
												)


		--	--Normal Transactions Reverse out of PaymentMethods
			INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])				    					
					select COAAccountId, 
						   Max(RevenueRecognitionRuleId),
						   Max(RRCode),		   
						   RRCalcTypeWhere,
						   RRCalcTypeMethod,	   
						   Max(COAAccountConfigId),
						   COAAccountTypeId,
						   COAAccountCode,
						   Transactionid,
						   saleid,
						   Siteid,
						   OperatingAreaId,
						   Workstationid,
						   UserGroupid,
						   UserId,
						   batchdate,
						   TransDate,
						   0,
						   0,
						   0,						
						   0,
						   0,
						   0,
						   ABS(sum(RevenueAmount)) as RevenueAmount,
						   case when accountingtype = 1 then 2
								else 1
							end Accountingtype,		
						   RRCalcTypeTrigger,
						   RRPercentage,
						   RRDays
						   from (
			select distinct rr_data_Revenue.coaaccountid as rrcoaaccountid,
								       p.COAAccountId, 
									   p.RevenueRecognitionRuleId,
									   p.RRCode,		   
									   p.RRCalcTypeWhere,
									   p.RRCalcTypeMethod,	   
									   p.COAAccountConfigId,
									   p.COAAccountTypeId,
									   p.COAAccountCode,
									   rr_data_Revenue.Transactionid Transactionid,
									   rr_data_Revenue.saleid saleid,
									   rr_data_Revenue.Siteid siteid,
									   rr_data_Revenue.OperatingAreaId OperatingAreaid,
									   rr_data_Revenue.Workstationid workstationid,
									   rr_data_Revenue.UserGroupid usergroupid,
									   rr_data_Revenue.UserId userid,
									   @BatchDate batchdate,
									   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
											else DATA_Transaction.transactiondate
									   end as TransDate,
									   rr_data_Revenue.RevenueAmount  as RevenueAmount,
								       p.Accountingtype,
									   transactiontype,		
									   p.RRCalcTypeTrigger,
									   p.RRPercentage,
									   p.RRDays
							FROM rr_data_Revenue   				        WITH (NOLOCK)
								   INNER JOIN (select saleid, transactionid, RevenueRecognitionRuleId, RR_DATA_Revenue.RRCode, RRCalcTypeWhere, Saleitemid, RR_DATA_Revenue.COAAccountId, 
													   RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount, COA_CNF_Account.COAAccountTypeId,  Accountingtype,
													   RR_DATA_Revenue.COAAccountCode
													  from RR_DATA_Revenue
														INNER JOIN COA_CNF_Account		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
													 where COA_CNF_Account.coaAccountID = @ACCPaymentMethod
													-- and rr_data_Revenue.RRCalcTypeTrigger = @Trigger
													)p								ON p.transactionid = 	rr_data_Revenue.transactionid
									INNER JOIN DATA_Transaction			on data_transaction.transactionid = rr_data_revenue.transactionid
							where RR_DATA_REVENUE.fcalcdate = @BatchDate
							  
							  and DATA_Transaction.TransactionType in (select transactionid
																from #TransactionIDs)
							  and rr_data_Revenue.coaaccountid in (select distinct coaaccountid
																	 from cnf_paymentmethod
																	 where coaaccountid is not null
																	union all
																   select distinct coaaccountid
																	 from cnf_paymentcard
																	 where coaaccountid is not null

																  )
						)r	
							group by	 COAAccountId, 		   
									   RRCalcTypeWhere,
									   RRCalcTypeMethod,	   
									   COAAccountTypeId,
									   COAAccountCode,
									   Transactionid,
									   saleid,
									   Siteid,
									   OperatingAreaId,
									   Workstationid,
									   UserGroupid,
									   UserId,
									   batchdate,
									   TransDate,					
									   Accountingtype,		
									   RRCalcTypeTrigger,
									   RRPercentage,
									   RRDays, 
									   TransactionType
							

----Normal Sale Split out the Payments to returned Checks
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])				    
				select distinct COA.COAAccountId, 
						   p.RevenueRecognitionRuleId,
						   p.RRCode,		   
						   p.RRCalcTypeWhere,
						   p.RRCalcTypeMethod,	   
						   p.COAAccountConfigId,
						   COA.COAAccountTypeId,
						   COA.Code,
						   RR_DATA_REVENUE.Transactionid as Transactionid,
						   RR_DATA_REVENUE.saleid as Saleid,
						   RR_DATA_REVENUE.Siteid as SiteID,
						   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
						   RR_DATA_REVENUE.Workstationid as Workstationid,
						   RR_DATA_REVENUE.UserGroupid as UserGroupID,
						   RR_DATA_REVENUE.UserId as userID,
						   @BatchDate,
						   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
							    else DATA_Transaction.transactiondate
						   end as TransDate,
						   0,
						   0,
						   0,
						   0,
						   100,
						   0,  	
						  ABS(data_ledger.entryAmount) as RevenueAmount,
							case when data_ledger.entryAmount &gt;= 0 then 1
								else 2
							end accountingtype,		
							p.RRCalcTypeTrigger,
							p.RRPercentage,
							p.RRDays

						from RR_DATA_REVENUE
						INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
						INNER JOIN data_payment							on data_payment.transactionid = rr_data_revenue.transactionid
						left  JOIN DATA_PaymentCard						on data_paymentcard.paymentid = data_payment.PaymentId
						left JOIN CNF_PaymentCard						on cnf_paymentcard.paymentcardid = data_paymentcard.paymentcardid
						INNER JOIN CNF_PaymentMethod					on CNF_PaymentMethod.PaymentMethodId = data_payment.PaymentMethodId
						INNER JOIN COA_CNF_Account COA					on COA.COAAccountid = CNF_PaymentMethod.returnedcheckcoaaccountid
						INNER JOIN data_ledger							ON data_ledger.transactionid = data_transaction.transactionid
						INNER JOIN cnf_ledgeraccount					ON cnf_ledgeraccount.LedgerAccountId = data_ledger.ledgeraccountid
												INNER JOIN (select transactionid, RevenueRecognitionRuleId, RR_DATA_Revenue.RRCode, RRCalcTypeWhere, 
																	RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount,  Accountingtype
																	from RR_DATA_Revenue
																	INNER JOIN COA_CNF_Account		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
																	where COA_CNF_Account.coaAccountID = @ACCPaymentMethod
																)p    on p.transactionid = 	data_payment.transactionid


						where data_payment.paymentstatus = 1
							and DATA_Transaction.TransactionType in (select transactionid
																from #TransactionIDs)
							and DATA_Transaction.tip &lt;&gt; 0
							and RR_DATA_REVENUE.fcalcdate = @BatchDate
							and systemaccounttable = 119
							and systemaccountid = 15

----Breakage for Fixed Vouchers.   The left over money.
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])				    
					select distinct COA.COAAccountId, 
						   p.RevenueRecognitionRuleId,
						   p.RRCode,		   
						   p.RRCalcTypeWhere,
						   p.RRCalcTypeMethod,	   
						   p.COAAccountConfigId,
						   COA.COAAccountTypeId,
						   COA.Code,
						   RR_DATA_REVENUE.Transactionid as Transactionid,
						   RR_DATA_REVENUE.saleid as Saleid,
						   RR_DATA_REVENUE.Siteid as SiteID,
						   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
						   RR_DATA_REVENUE.Workstationid as Workstationid,
						   RR_DATA_REVENUE.UserGroupid as UserGroupID,
						   RR_DATA_REVENUE.UserId as userID,
						   @BatchDate,
						   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
							    else DATA_Transaction.transactiondate
						   end as TransDate,
						   0,
						   0,
						   0,
						   0,
						   100,
						   0,  	
						  ABS(DATA_Transaction.Tip) as RevenueAmount,
							2 accountingtype,		
							p.RRCalcTypeTrigger,
							p.RRPercentage,
							p.RRDays

						from RR_DATA_REVENUE

							INNER JOIN data_transaction		on data_transaction.transactionid = rr_data_revenue.transactionid
							INNER JOIN DATA_Payment			on data_payment.transactionid = data_transaction.transactionid
							INNER JOIN CNF_PaymentMethod	on cnf_paymentmethod.paymentmethodid = data_payment.paymentmethodid
							INNER JOIN CNF_Driver			on cnf_driver.driverID = cnf_paymentmethod.driverid
							INNER JOIN COA_CNF_Account COA	on COA.COAAccountid = CNF_PaymentMethod.FixedVoucherCOAAccountId


							INNER JOIN (select transactionid, RevenueRecognitionRuleId, RR_DATA_Revenue.RRCode, RRCalcTypeWhere, 
																	RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount,  Accountingtype
																	from RR_DATA_Revenue
																	INNER JOIN COA_CNF_Account		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
																	where COA_CNF_Account.coaAccountID = @ACCPaymentMethod
																)p    on p.transactionid = 	data_payment.transactionid


						where data_payment.paymentstatus = 1
						  and TransactionType in (select transactionid
														from #TransactionIDs)
							and DATA_Transaction.tip &lt;&gt; 0
							and RR_DATA_REVENUE.fcalcdate = @BatchDate


				--Normal Transaction break out Tax
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])				    
						  select COAAccountId, 
						   MIN(p.RevenueRecognitionRuleId),
						   MIN(p.RRCode),		   
						   RRCalcTypeWhere,
						   RRCalcTypeMethod,	   
						   COAAccountConfigId,
						   COAAccountTypeId,
						   COACODE,
						   Transactionid,
						   saleid,
						   Siteid,
						   OperatingAreaId,
						   Workstationid,
						   UserGroupid,
						   UserId,
						   batchdate,
						   TransDate,
						   0,
						   0,
						   0,						
						   price,
						   percentage,
						   test,
						   ABS(sum(RevenueAmount)) as RevenueAmount,
				           case when TransactionType in (5, 17, 18, 20, 22, 30) and sum(RevenueAmount) &lt;= 0  then 1
						        when TransactionType in (5, 17, 18, 20, 22, 30) and sum(RevenueAmount) &lt;= 0  then 2
								when TransactionType in (7) and sum(RevenueAmount) &lt;= 0  then 1
								when TransactionType in (7) and sum(RevenueAmount) &gt; 0  then 2
								else Accountingtype
							end Accountingtype,		
						   RRCalcTypeTrigger,
						   RRPercentage,
						   RRDays
						   
						   from (
						  select distinct COA.COAAccountId, 
						   min(p.RevenueRecognitionRuleId) RevenueRecognitionRuleId,
						   min(p.rrcode) rrcode,		   
						   RR_DATA_REVENUE.RRCalcTypeWhere,
						   RR_DATA_REVENUE.RRCalcTypeMethod,	   
						   RR_DATA_REVENUE.COAAccountConfigId,
						   COA.COAAccountTypeId,
						   COA.Code COACODE,
						   RR_DATA_REVENUE.Transactionid as Transactionid,
						   RR_DATA_REVENUE.saleid as Saleid,
						   RR_DATA_REVENUE.Siteid as SiteID,
						   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
						   RR_DATA_REVENUE.Workstationid as Workstationid,
						   RR_DATA_REVENUE.UserGroupid as UserGroupID,
						   RR_DATA_REVENUE.UserId as userID,
						   @BatchDate as batchdate,
						   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
							    else DATA_Transaction.transactiondate
						   end as TransDate,
						   0 as Quantity,
						   0 as GrossAmount,
						   0 as NetAmount,
						   0 as price,
						   100 as percentage,
						   0 as test, 	
						   taxamount RevenueAmount,
						   Transactiontype,
							p.Accountingtype,					   		
						   RR_DATA_REVENUE.RRCalcTypeTrigger,
						   RR_DATA_REVENUE.RRPercentage,
						   RR_DATA_REVENUE.RRDays

					from RR_DATA_REVENUE
						INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
						INNER JOIN DATA_TransactionTax					on data_transactiontax.transactionid = data_transaction.transactionid
						INNER JOIN CNF_Tax								on cnf_tax.taxid = DATA_TransactionTax.taxid
						INNER JOIN coa_cnf_account coa					on coa.coaaccountid = cnf_tax.coaaccountid
							INNER JOIN (select saleid, transactionid, RevenueRecognitionRuleId, RR_DATA_Revenue.RRCode, RRCalcTypeWhere, Saleitemid, RR_DATA_Revenue.coaaccountid,
												RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount,  Accountingtype
												from RR_DATA_Revenue
												INNER JOIN COA_CNF_Account		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
												where COA_CNF_Account.coaAccountID = @TaxAccountID
												--and rr_data_Revenue.RRCalcTypeTrigger = @Trigger
												and RR_DATA_REVENUE.fcalcdate = @BatchDate
											)p    on p.transactionid = 	data_transactiontax.transactionid
					where RR_DATA_REVENUE.coaaccountid = 1
					and RR_DATA_REVENUE.fcalcdate = @BatchDate
					and TransactionType in (select transactionid
														from #TransactionIDs)
					AND DATA_Transaction.Transactionid not in (select distinct transactionid
																	from rr_Data_Revenue
																	where coaaccountid in (select distinct coaaccountid
																								from cnf_tax 
																							)
																	)
					group by COA.COAAccountId,    
						   RR_DATA_REVENUE.RRCalcTypeWhere,
						   RR_DATA_REVENUE.RRCalcTypeMethod,	   
						   RR_DATA_REVENUE.COAAccountConfigId,
						   COA.COAAccountTypeId,
						   COA.Code,
						   RR_DATA_REVENUE.Transactionid,
						   RR_DATA_REVENUE.saleid,
						   RR_DATA_REVENUE.Siteid,
						   RR_DATA_REVENUE.OperatingAreaId,
						   RR_DATA_REVENUE.Workstationid,
						   RR_DATA_REVENUE.UserGroupid,
						   RR_DATA_REVENUE.UserId,
						   DATA_Transaction.ftransactiondate, 
						   DATA_Transaction.transactiondate,
						   taxamount,
						   Transactiontype,
							p.Accountingtype,					   		
						   RR_DATA_REVENUE.RRCalcTypeTrigger,
						   RR_DATA_REVENUE.RRPercentage,
						   RR_DATA_REVENUE.RRDays

					)p
					where revenueamount &lt;&gt; 0
					group by COAAccountId, 	   
							RRCalcTypeWhere,
							RRCalcTypeMethod,	   
							COAAccountConfigId,
							COAAccountTypeId,
							COACODE,
							Transactionid,
							saleid,
							Siteid,
							OperatingAreaId,
							Workstationid,
							UserGroupid,
							UserId,
							TransDate,
							Accountingtype,		
							RRCalcTypeTrigger,
							RRPercentage,
							RRDays,
							price,
							percentage,
							test,
							batchdate,
							TransactionType


																									
		--	--------Reverse Tax Out
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])	
				      select  COAAccountId, 
									   RevenueRecognitionRuleId,
									   RRCode,		   
									   RRCalcTypeWhere,
									   RRCalcTypeMethod,	   
									   COAAccountConfigId,
									   COAAccountTypeId,
									   COAAccountCode,
									   Transactionid,
									   saleid,
									   siteid,
									   OperatingAreaid,
									   workstationid,
									   usergroupid,
									   userid,
									   batchdate,
									   TransDate,
									   Quantity,
									   grossamount,
									   netamount,
									   price,
									   percentage,
									   tax,
									   ABS(sum(RevenueAmount))  as RevenueAmount,
									    case when p.accountingtype = 1 then 2
											else 1
										end Accountingtype,	
									   RRCalcTypeTrigger,
									   RRPercentage,
									   RRDays
					  from (		    
				             select distinct 
								       p.COAAccountId, 
									   p.RevenueRecognitionRuleId,
									   p.RRCode,		   
									   p.RRCalcTypeWhere,
									   p.RRCalcTypeMethod,	   
									   p.COAAccountConfigId,
									   p.COAAccountTypeId,
									   p.COAAccountCode,
									   rr_data_Revenue.Transactionid Transactionid,
									   rr_data_Revenue.saleid saleid,
									   rr_data_Revenue.Siteid siteid,
									   rr_data_Revenue.OperatingAreaId OperatingAreaid,
									   rr_data_Revenue.Workstationid workstationid,
									   rr_data_Revenue.UserGroupid usergroupid,
									   rr_data_Revenue.UserId userid,
									   @BatchDate batchdate,
									   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
											else DATA_Transaction.transactiondate
									   end as TransDate,
									   rr_data_Revenue.Quantity Quantity,
									   rr_data_Revenue.GrossAmount grossamount,
									   rr_data_Revenue.NetAmount netamount,
									   0 price,
									   100 percentage,
									   0 tax,
									   rr_data_Revenue.RevenueAmount  as RevenueAmount,
									   data_transaction.transactiontype,
								       p.Accountingtype,		
									   p.RRCalcTypeTrigger,
									   p.RRPercentage,
									   p.RRDays
							FROM rr_data_Revenue   				        WITH (NOLOCK)
								   INNER JOIN (select saleid, transactionid, RevenueRecognitionRuleId, RR_DATA_Revenue.RRCode, RRCalcTypeWhere, Saleitemid, RR_DATA_Revenue.COAAccountId, 
													   RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount, COA_CNF_Account.COAAccountTypeId,  Accountingtype,
													   RR_DATA_Revenue.COAAccountCode
													  from RR_DATA_Revenue
														INNER JOIN COA_CNF_Account		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
													 where COA_CNF_Account.coaAccountID = @TaxAccountID
													)p								ON p.Transactionid = 	rr_data_Revenue.Transactionid
									INNER JOIN data_transaction						on data_transaction.transactionid = rr_data_revenue.transactionid

							where RR_DATA_REVENUE.fcalcdate = @BatchDate
							  and rr_data_Revenue.RRCalcTypeTrigger = @Trigger
							  and DATA_Transaction.TransactionType in (select transactionid
																		from #TransactionIDs)
							  and rr_data_Revenue.coaaccountid in (select distinct coaaccountid
						                                             from cnf_tax
																    where coaaccountid is not null
															      )
							)p
							group by   COAAccountId, 
									   RevenueRecognitionRuleId,
									   RRCode,		   
									   RRCalcTypeWhere,
									   RRCalcTypeMethod,	   
									   COAAccountConfigId,
									   COAAccountTypeId,
									   COAAccountCode,
									   Transactionid,
									   saleid,
									   siteid,
									   OperatingAreaid,
									   workstationid,
									   usergroupid,
									   userid,
									   batchdate,
									   TransDate,
									   Quantity,
									   grossamount,
									   netamount,
									   price,
									   percentage,
									   tax,
								       Accountingtype,		
									   RRCalcTypeTrigger,
									   RRPercentage,
									   RRDays,
									   TransactionType


		------		--Normal Transaction Break out the discounts
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[saleitemid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])
				   select COAAccountId, 
						   RevenueRecognitionRuleId,
						   RRCode,		   
						   RRCalcTypeWhere,
						   RRCalcTypeMethod,	   
						   COAAccountConfigId,
						   COAAccountTypeId,
						   Code,
						   Transactionid,
						   Saleid,
						   Saleitemid,
						   SiteID,
						   OperatingAreaID,
						   Workstationid,
						   UserGroupID,
						   userID,
						   batchdate,
						   TransDate,
						   quantity,
						   grossamount,
						   netamount,
						   price,
						   percentage,
						   remaningValues, 	
						   RevenueAmount,
						   Accountingtype,		
						   RRCalcTypeTrigger,
						   RRPercentage,
						   RRDays
				   from (				    
						select distinct 
						   COA.COAAccountId, 
						   RR_DATA_REVENUE.RevenueRecognitionRuleId,
						   RR_DATA_REVENUE.RRCode,		   
						   RR_DATA_REVENUE.RRCalcTypeWhere,
						   RR_DATA_REVENUE.RRCalcTypeMethod,	   
						   RR_DATA_REVENUE.COAAccountConfigId,
						   COA.COAAccountTypeId,
						   COA.Code,
						   RR_DATA_REVENUE.Transactionid as Transactionid,
						   RR_DATA_REVENUE.saleid as Saleid,
						   RR_DATA_REVENUE.saleitemid as saleitemid,
						   RR_DATA_REVENUE.Siteid as SiteID,
						   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
						   RR_DATA_REVENUE.Workstationid as Workstationid,
						   RR_DATA_REVENUE.UserGroupid as UserGroupID,
						   RR_DATA_REVENUE.UserId as userID,
						   @BatchDate as batchdate,
						   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
							    else DATA_Transaction.transactiondate
						   end as TransDate,
						   0 as quantity,
						   0 as grossamount,
						   0 as netamount,
						   0 as price,
						   100 as percentage,
						   0 as remaningValues, 	
						   abs(DATA_SaleItemRule.discountamount)
							as RevenueAmount,
						   p.Accountingtype,		
						   RR_DATA_REVENUE.RRCalcTypeTrigger,
						   RR_DATA_REVENUE.RRPercentage,
						   RR_DATA_REVENUE.RRDays,
						   DATA_SaleItemRule.SaleItemRuleId


					from RR_DATA_REVENUE
						--inner join rr_cnf_Product						ON ((RR_DATA_REVENUE.MATRIXCELLID = rr_cnf_Product.MATRIXCELLID) or (RR_DATA_REVENUE.MatrixSheetId = rr_cnf_Product.MatrixSheetId)) and rr_cnf_Product.Enabled = 1
						--inner join RR_CNF_RevenueRecognitionRule		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_cnf_Product.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  
						--INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
						--INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
						--INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 
						INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
						LEFT  JOIN DATA_Sale				            ON DATA_Sale.SaleID = data_transaction.SaleID
						LEFT  JOIN DATA_SaleItem			            ON DATA_SaleItem.saleitemid = RR_DATA_REVENUE.saleitemid
						LEFT JOIN DATA_SaleItemRule						ON data_saleitemrule.saleitemid = DATA_SaleItem.saleitemid	 
						LEFT JOIN CNF_PromotionItemRule					ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
						LEFT JOIN CNF_PromotionItem						ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
						LEFT JOIN CNF_Promotion							ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId	
						LEFT JOIN COA_CNF_Account	COA			        ON COA.coaaccountid = CNF_Promotion.coaaccountid
						
						
						INNER JOIN (select transactionid, RevenueRecognitionRuleId, RR_DATA_Revenue.RRCode, RRCalcTypeWhere, saleitemid,
											RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount,  Accountingtype
											from RR_DATA_Revenue
											INNER JOIN COA_CNF_Account		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
											where COA_CNF_Account.coaAccountID = @DiscountAccountID
										)p    on p.transactionid = 	DATA_Transaction.transactionid and p.saleitemid = rr_data_revenue.saleitemid



					where RR_DATA_REVENUE.coaaccountid = 1
					and DATA_Transaction.TransactionType in (select transactionid
																from #TransactionIDs)
					and RR_DATA_REVENUE.fcalcdate = @BatchDate
					--and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
					AND DATA_Transaction.Transactionid not in (select distinct transactionid
																	from rr_Data_Revenue
																	where coaaccountid in (select distinct coaaccountid
																								from CNF_Promotion
																								where coaaccountid is not null 
																							)
																	)	
					)p
					where revenueamount &lt;&gt; 0	
					  and coaaccountid is not null													
																																								
		--		--Reverse out Discounts														
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])	
				   select COAAccountId, 
						   RevenueRecognitionRuleId,
						   RRCode,		   
						   RRCalcTypeWhere,
						   RRCalcTypeMethod,	   
						   COAAccountConfigId,
						   COAAccountTypeId,
						   COAAccountCode,
						   Transactionid,
						   Saleid,
						   SiteID,
						   OperatingAreaID,
						   Workstationid,
						   UserGroupID,
						   userID,
						   batchdate,
						   TransDate,
						   quantity,
						   grossamount,
						   netamount,
						   price,
						   percentage,
						   remaningValues, 	
						   sum(RevenueAmount),
						   Accountingtype,		
						   RRCalcTypeTrigger,
						   RRPercentage,
						   RRDays
				   from (		    
				select distinct 				           
				           p.RevenueRecognitionDataId,
                           p.COAAccountId, 
						   p.RevenueRecognitionRuleId,
						   p.RRCode,		   
						   p.RRCalcTypeWhere,
						   p.RRCalcTypeMethod,	   
						   p.COAAccountConfigId,
						   p.COAAccountTypeId,
						   p.COAAccountCode,
						   rr_data_Revenue.Transactionid,
						   rr_data_Revenue.saleid,
						   rr_data_Revenue.saleitemid,
						   rr_data_Revenue.Siteid,
						   rr_data_Revenue.OperatingAreaId,
						   rr_data_Revenue.Workstationid,
						   rr_data_Revenue.UserGroupid,
						   rr_data_Revenue.UserId,
						   @BatchDate batchdate,
						   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
							    else DATA_Transaction.transactiondate
						   end as TransDate,
							0 as quantity,
						   0 as grossamount,
						   0 as netamount,
						   0 as price,
						   100 as percentage,
						   0 as remaningValues,
						   rr_data_Revenue.RevenueAmount  as RevenueAmount,
						   case when p.accountingtype = 1 then 2
					        else 1
						   end Accountingtype,
						   p.RRCalcTypeTrigger,
						   p.RRPercentage,
						   p.RRDays

						  FROM rr_data_Revenue   				        WITH (NOLOCK)
								   INNER JOIN (select saleid, transactionid, RevenueRecognitionRuleId, RR_DATA_Revenue.RRCode, RRCalcTypeWhere, Saleitemid, RR_DATA_Revenue.COAAccountId, 
													   RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount, COA_CNF_Account.COAAccountTypeId,  Accountingtype,
													   RR_DATA_Revenue.COAAccountCode, rr_data_Revenue.RevenueRecognitionDataId
													  from RR_DATA_Revenue
														INNER JOIN COA_CNF_Account		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
													 where COA_CNF_Account.coaAccountID = @DiscountAccountID
													)p								ON p.saleid = 	rr_data_Revenue.saleid  and p.saleitemid = rr_data_revenue.saleitemid
								INNER JOIN data_transaction        on data_transaction.transactionid = rr_data_revenue.transactionid

						where  rr_data_Revenue.coaaccountid in (select distinct coaaccountid
						                                         from CNF_Promotion
															  )
						 and RR_DATA_REVENUE.fcalcdate = @BatchDate
						 and DATA_Transaction.TransactionType in (select transactionid
															from #TransactionIDs)
						)p		
						
						group by  COAAccountId, 
						   RevenueRecognitionRuleId,
						   RRCode,		   
						   RRCalcTypeWhere,
						   RRCalcTypeMethod,	   
						   COAAccountConfigId,
						   COAAccountTypeId,
						   COAAccountCode,
						   Transactionid,
						   Saleid,
						   SiteID,
						   OperatingAreaID,
						   Workstationid,
						   UserGroupID,
						   userID,
						   batchdate,
						   TransDate,
						   quantity,
						   grossamount,
						   netamount,
						   price,
						   percentage,
						   remaningValues, 	
						   Accountingtype,		
						   RRCalcTypeTrigger,
						   RRPercentage,
						   RRDays																																																																																			

		
		End</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_RR_RevenueData_PaymentMethodTaxDiscounts2]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_RR_RevenueData_PaymentMethodTaxDiscounts2</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>CREATE Procedure dbo.otn_sp_RR_RevenueData_PaymentMethodTaxDiscounts2
	@BatchDate Date,
	@Transactions varchar(500),
	@Trigger int,
	@RRTransDateType Integer
AS 
BEGIN
	 
	Create Table #TransactionIDs(
	TransactionId Int NOT NULL)

	DECLARE @DelimPosition INT

    SET @DelimPosition = CHARINDEX(',', @Transactions)

    WHILE @DelimPosition &gt; 0
    BEGIN
        INSERT INTO #TransactionIDs(TransactionId)
            VALUES(CAST(RTRIM(LEFT(@Transactions, @DelimPosition - 1)) AS INT))
        SET @Transactions = right(@Transactions, len(@Transactions) - @DelimPosition)

        SET @DelimPosition = CHARINDEX(',', @Transactions)
    END


	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer

	Declare @OnCreditWriteoff Integer = 9
	Declare @StartTime DateTime

	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1
	

		--Normal Sale Split out the Payments to Smaller Subset.
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays]
				   ,[attributeids])				    
						select distinct COA.COAAccountId, 
								p.RevenueRecognitionRuleId,
								p.code,		   
								p.RRCalcTypeWhere,
								p.RRCalcTypeMethod,	   
								p.COAAccountConfigId,
								p.COAAccountTypeId,
								COA.Code,
								RR_DATA_REVENUE.Transactionid as Transactionid,
								RR_DATA_REVENUE.saleid as Saleid,
								RR_DATA_REVENUE.Siteid as SiteID,
								RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								RR_DATA_REVENUE.Workstationid as Workstationid,
								RR_DATA_REVENUE.UserGroupid as UserGroupID,
								RR_DATA_REVENUE.UserId as userID,
								@BatchDate as BatchDate,
							   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
									else DATA_Transaction.transactiondate
							   end as TransDate,
								0 as Quantity,
								0 as GrossAmount,
								0 as NetAmount,
								0 as ConfigPrice,
								100 as ConfigPercentage,
								0 RemainingValues,	
								(data_payment.PaymentAmount + data_payment.PaymentFee) - 
							   (case when data_payment.paymentid = (select top 1 paymentid
																	from data_payment
																	where transactionid = RR_DATA_REVENUE.Transactionid
																		and data_payment.paymentamount &gt; (select sum(Change) *-1
																									from data_transaction
																									where data_transaction.transactionid = RR_DATA_REVENUE.Transactionid))
									then (select sum(Change) *-1
																									from data_transaction
																									where data_transaction.transactionid = RR_DATA_REVENUE.Transactionid)
									else 0
								end )
								as RevenueAmount,
							--	p.Accountingtype,		
								case    when DATA_Transaction.TransactionType in (5, 8, 17, 18, 20, 22, 30) and p.Accountingtype = 1 then 2
										when DATA_Transaction.TransactionType in (5, 8, 17, 18, 20, 22, 30) and p.Accountingtype = 2 then 1
										when DATA_Transaction.TransactionType in (7) and (RR_DATA_REVENUE.revenueAmount) &lt;= 0  then 1
										when DATA_Transaction.TransactionType in (7) and (RR_DATA_REVENUE.revenueAmount) &gt; 0  then 2
										else p.Accountingtype
								end Accountingtype,
							   p.RRCalcTypeTrigger,
							   p.RRPercentage,
							   p.Days,
							   RR_DATA_REVENUE.attributeids

					from RR_DATA_REVENUE
									INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
									INNER JOIN (select '1' as PCOAAccountid, 
													   coa_cnf_accountConfig.Siteid, 
													   RR_CNF_RevenueRecognitionRule.Enabled, 
													   RR_CNF_RevenueRecognitionRule.FromDate, 
													   RR_CNF_RevenueRecognitionRule.ToDate,
													   COA_CNF_AccountConfig.RemainingValues,
													   coa_cnf_account.coaaccountid,
													   COA_CNF_AccountConfig.Price,
													   COA_CNF_AccountConfig.Percentage,
													   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
													   RR_CNF_RevenueRecognitionRule.code,		   
													   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
													   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
													   COA_CNF_AccountConfig.COAAccountConfigId,
													   coa_cnf_account.COAAccountTypeId,
													   coa_cnf_account.Code as accountcode,
													   coa_cnf_accountconfig.Accountingtype,
													   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
													   RR_CNF_RevenueRecognitionRule.Percentage rrPercentage,
													   RR_CNF_RevenueRecognitionRule.Days	

													from RR_CNF_RevenueRecognitionRule	
													INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
													INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid and coa_cnf_account.Enabled = 1
													INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
												where  RR_CNF_RevenueRecognitionRule.Enabled = 1
												and coa_cnf_account.coaaccountid in (@ACCPaymentMethod)) p				on p.PCOAAccountid = rr_data_revenue.coaaccountid 
							INNER JOIN data_payment							on data_payment.transactionid = rr_data_revenue.transactionid
							left  JOIN DATA_PaymentCard						on data_paymentcard.paymentid = data_payment.PaymentId
							left JOIN CNF_PaymentCard						on cnf_paymentcard.paymentcardid = data_paymentcard.paymentcardid
							INNER JOIN CNF_PaymentMethod					on CNF_PaymentMethod.PaymentMethodId = data_payment.PaymentMethodId
							INNER JOIN COA_CNF_Account COA					on COA.COAAccountid = ISNULL(cnf_paymentcard.coaaccountid, CNF_PaymentMethod.COAAccountid)


						where data_payment.paymentstatus = 1
						and DATA_Transaction.TransactionType in (select transactionid
																from #TransactionIDs)
						and RR_DATA_REVENUE.fcalcdate = @BatchDate
						and @BatchDate between p.FromDate and p.ToDate
						AND data_payment.Transactionid not in (select distinct transactionid
													from rr_Data_Revenue
													where coaaccountid in (select distinct coaaccountid
																				from cnf_paymentmethod CP
																				where coaaccountid is not null
																				union all
																				select distinct coaaccountid
																				from cnf_paymentcard pc
																				where coaaccountid is not null
																			)
													)
						AND data_payment.Transactionid in (select distinct transactionid
													from rr_Data_Revenue
													where coaaccountid in (@ACCPaymentMethod)
													)
						 AND RR_DATA_REVENUE.coaaccountid not in (@ACCPaymentMethod)


----Breakage for Fixed Vouchers.   The left over money.
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])				    
					select distinct COA.COAAccountId, 
						   p.RevenueRecognitionRuleId,
						   p.RRCode,		   
						   p.RRCalcTypeWhere,
						   p.RRCalcTypeMethod,	   
						   p.COAAccountConfigId,
						   COA.COAAccountTypeId,
						   COA.Code,
						   RR_DATA_REVENUE.Transactionid as Transactionid,
						   RR_DATA_REVENUE.saleid as Saleid,
						   RR_DATA_REVENUE.Siteid as SiteID,
						   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
						   RR_DATA_REVENUE.Workstationid as Workstationid,
						   RR_DATA_REVENUE.UserGroupid as UserGroupID,
						   RR_DATA_REVENUE.UserId as userID,
						   @BatchDate,
						   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
							    else DATA_Transaction.transactiondate
						   end as TransDate,
						   0,
						   0,
						   0,
						   0,
						   100,
						   0,  	
						  ABS(DATA_Transaction.Tip) as RevenueAmount,
							2 accountingtype,		
							p.RRCalcTypeTrigger,
							p.RRPercentage,
							p.RRDays

						from RR_DATA_REVENUE

							INNER JOIN data_transaction		on data_transaction.transactionid = rr_data_revenue.transactionid
							INNER JOIN DATA_Payment			on data_payment.transactionid = data_transaction.transactionid
							INNER JOIN CNF_PaymentMethod	on cnf_paymentmethod.paymentmethodid = data_payment.paymentmethodid
							INNER JOIN CNF_Driver			on cnf_driver.driverID = cnf_paymentmethod.driverid
							INNER JOIN COA_CNF_Account COA	on COA.COAAccountid = CNF_PaymentMethod.FixedVoucherCOAAccountId


							INNER JOIN (select transactionid, RevenueRecognitionRuleId, RR_DATA_Revenue.RRCode, RRCalcTypeWhere, 
																	RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount,  Accountingtype
																	from RR_DATA_Revenue
																	INNER JOIN COA_CNF_Account		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
																	where COA_CNF_Account.coaAccountID = @ACCPaymentMethod
																)p    on p.transactionid = 	data_payment.transactionid


						where data_payment.paymentstatus = 1
						  and TransactionType in (select transactionid
														from #TransactionIDs)
							and DATA_Transaction.tip &lt;&gt; 0
							and RR_DATA_REVENUE.fcalcdate = @BatchDate


		----Normal Sale Split out the Payments to Payment Fees
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays]
				   ,[attributeids])				    
				select distinct COA.COAAccountId, 
						   p.RevenueRecognitionRuleId,
						   p.RRCode,		   
						   p.RRCalcTypeWhere,
						   p.RRCalcTypeMethod,	   
						   p.COAAccountConfigId,
						   COA.COAAccountTypeId,
						   COA.Code,
						   RR_DATA_REVENUE.Transactionid as Transactionid,
						   RR_DATA_REVENUE.saleid as Saleid,
						   RR_DATA_REVENUE.Siteid as SiteID,
						   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
						   RR_DATA_REVENUE.Workstationid as Workstationid,
						   RR_DATA_REVENUE.UserGroupid as UserGroupID,
						   RR_DATA_REVENUE.UserId as userID,
						   @BatchDate,
						   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
							    else DATA_Transaction.transactiondate
						   end as TransDate,
						   0,
						   0,
						   0,
						   0,
						   100,
						   0,  	
						   data_payment.paymentfee as RevenueAmount,
						   case when data_payment.paymentfee &gt;= 0 then 2
						        else 1
							end accountingtype,		
						   p.RRCalcTypeTrigger,
						   p.RRPercentage,
						   p.RRDays,
						   RR_DATA_REVENUE.AttributeIDs

						from RR_DATA_REVENUE
						inner join rr_cnf_Product						ON ((RR_DATA_REVENUE.MATRIXCELLID = rr_cnf_Product.MATRIXCELLID) 
                                            or (RR_DATA_REVENUE.MatrixSheetId = rr_cnf_Product.MatrixSheetId)
											or (rr_cnf_product.Attributeid in (select top 1 Attributeid
																				from rr_cnf_product
																				where Attributeid in (select Value
																										from dbo.split((select rr.Attributeids
																														from rr_data_revenue rr
																														where rr.revenuerecognitiondataid = RR_DATA_REVENUE.revenuerecognitiondataid), '.')
																										)
																			)
												))
											and rr_cnf_Product.Enabled = 1
						inner join RR_CNF_RevenueRecognitionRule		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_cnf_Product.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  
						INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
						INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
						INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 
						INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
						INNER JOIN data_payment							on data_payment.transactionid = rr_data_revenue.transactionid
						left  JOIN DATA_PaymentCard						on data_paymentcard.paymentid = data_payment.PaymentId
						left JOIN CNF_PaymentCard						on cnf_paymentcard.paymentcardid = data_paymentcard.paymentcardid
						INNER JOIN CNF_PaymentMethod					on CNF_PaymentMethod.PaymentMethodId = data_payment.PaymentMethodId
						INNER JOIN COA_CNF_Account COA					on COA.COAAccountid = CNF_PaymentMethod.FeeCOAAccountId

						INNER JOIN (select transactionid, RevenueRecognitionRuleId, RR_DATA_Revenue.RRCode, RRCalcTypeWhere, 
											RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount,  Accountingtype
											from RR_DATA_Revenue
											INNER JOIN COA_CNF_Account		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
											where COA_CNF_Account.coaAccountID = @ACCPaymentMethod
										)p    on p.transactionid = 	data_payment.transactionid

					where data_payment.paymentstatus = 1
					and DATA_Transaction.TransactionType in (select transactionid
																from #TransactionIDs)
					and data_payment.paymentfee &lt;&gt; 0
					and RR_DATA_REVENUE.fcalcdate = @BatchDate
					and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
					AND data_payment.Transactionid not in (select distinct transactionid
												from rr_Data_Revenue
												where coaaccountid in (select distinct FeeCOAAccountId
																			from cnf_paymentmethod CP
																		)
												)
					AND data_payment.Transactionid in (select distinct transactionid
												from rr_Data_Revenue
												where coaaccountid in (@ACCPaymentMethod)
												)


							


		--	--Normal Transactions Reverse out of PaymentMethods
			INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays]
				   ,[AttributeIDs])				    					
				   select COAAccountId, 
						   Max(RevenueRecognitionRuleId),
						   Max(RRCode),		   
						   RRCalcTypeWhere,
						   RRCalcTypeMethod,	   
						   Max(COAAccountConfigId),
						   COAAccountTypeId,
						   COAAccountCode,
						   Transactionid,
						   saleid,
						   Siteid,
						   OperatingAreaId,
						   Workstationid,
						   UserGroupid,
						   UserId,
						   batchdate,
						   TransDate,
						   0,
						   0,
						   0,						
						   0,
						   0,
						   0,
						   sum(RevenueAmount) as RevenueAmount,
				           case when accountingtype = 1 then 2
					        else 1
						   end Accountingtype,		
						   RRCalcTypeTrigger,
						   RRPercentage,
						   RRDays,
						   AttributeIDs
						   from (
							select distinct 
								       p.COAAccountId, 
									   p.RevenueRecognitionRuleId,
									   p.RRCode,		   
									   p.RRCalcTypeWhere,
									   p.RRCalcTypeMethod,	   
									   p.COAAccountConfigId,
									  p.COAAccountTypeId,
									   p.COAAccountCode,
									   rr_data_Revenue.Transactionid Transactionid,
									   rr_data_Revenue.saleid saleid,
									   rr_data_Revenue.Siteid siteid,
									   rr_data_Revenue.OperatingAreaId OperatingAreaid,
									   rr_data_Revenue.Workstationid workstationid,
									   rr_data_Revenue.UserGroupid usergroupid,
									   rr_data_Revenue.UserId userid,
									   @BatchDate batchdate,
									   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
											else DATA_Transaction.transactiondate
									   end as TransDate,
									   rr_data_Revenue.RevenueAmount *-1  as RevenueAmount,
								       p.Accountingtype,
									   transactiontype,		
									   p.RRCalcTypeTrigger,
									   p.RRPercentage,
									   p.RRDays,
									   rr_data_Revenue.AttributeIDs
							FROM rr_data_Revenue   				        WITH (NOLOCK)
								   INNER JOIN (select saleid, transactionid, RevenueRecognitionRuleId, RR_DATA_Revenue.RRCode, RRCalcTypeWhere, Saleitemid, RR_DATA_Revenue.COAAccountId, 
													   RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount, COA_CNF_Account.COAAccountTypeId,  Accountingtype,
													   RR_DATA_Revenue.COAAccountCode
													  from RR_DATA_Revenue
														INNER JOIN COA_CNF_Account		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
													 where COA_CNF_Account.coaAccountID = @ACCPaymentMethod
													   --and rr_data_revenue.RRCalcTypeTrigger = @Trigger
													)p								ON p.transactionid = 	rr_data_Revenue.transactionid
									INNER JOIN DATA_Transaction			on data_transaction.transactionid = rr_data_revenue.transactionid
							where RR_DATA_REVENUE.fcalcdate = @BatchDate
							  and DATA_Transaction.TransactionType in (select transactionid
																from #TransactionIDs)
							  and rr_data_Revenue.coaaccountid in (select distinct coaaccountid
																	 from cnf_paymentmethod
																	 where coaaccountid is not null
																	union all
																   select distinct coaaccountid
																	 from cnf_paymentcard
																	 where coaaccountid is not null
																  )
						)r	
							group by	 COAAccountId, 		   
									   RRCalcTypeWhere,
									   RRCalcTypeMethod,	   
									   COAAccountTypeId,
									   COAAccountCode,
									   Transactionid,
									   saleid,
									   Siteid,
									   OperatingAreaId,
									   Workstationid,
									   UserGroupid,
									   UserId,
									   batchdate,
									   TransDate,					
									   Accountingtype,		
									   RRCalcTypeTrigger,
									   RRPercentage,
									   RRDays, 
									   TransactionType, 
									   AttributeIDs


----Normal Sale Split out the Payments to Payment Fees
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays]
				   ,[AttributeIDs])				    
				select distinct COA.COAAccountId, 
						   p.RevenueRecognitionRuleId,
						   p.RRCode,		   
						   p.RRCalcTypeWhere,
						   p.RRCalcTypeMethod,	   
						   p.COAAccountConfigId,
						   COA.COAAccountTypeId,
						   COA.Code,
						   RR_DATA_REVENUE.Transactionid as Transactionid,
						   RR_DATA_REVENUE.saleid as Saleid,
						   RR_DATA_REVENUE.Siteid as SiteID,
						   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
						   RR_DATA_REVENUE.Workstationid as Workstationid,
						   RR_DATA_REVENUE.UserGroupid as UserGroupID,
						   RR_DATA_REVENUE.UserId as userID,
						   @BatchDate,
						   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
							    else DATA_Transaction.transactiondate
						   end as TransDate,
						   0,
						   0,
						   0,
						   0,
						   100,
						   0,  	
						  ABS(data_ledger.entryAmount) as RevenueAmount,
							case when data_ledger.entryAmount &gt;= 0 then 1
								else 2
							end accountingtype,		
							p.RRCalcTypeTrigger,
							p.RRPercentage,
							p.RRDays,
							RR_DATA_Revenue.AttributeIDs

						from RR_DATA_REVENUE
						inner join rr_cnf_Product						ON ((RR_DATA_REVENUE.MATRIXCELLID = rr_cnf_Product.MATRIXCELLID) 
                                            or (RR_DATA_REVENUE.MatrixSheetId = rr_cnf_Product.MatrixSheetId)
											or (rr_cnf_product.Attributeid in (select top 1 Attributeid
																				from rr_cnf_product
																				where Attributeid in (select Value
																										from dbo.split((select rr.Attributeids
																														from rr_data_revenue rr
																														where rr.revenuerecognitiondataid = RR_DATA_REVENUE.revenuerecognitiondataid), '.')
																										)
																			)
												))
											and rr_cnf_Product.Enabled = 1
						inner join RR_CNF_RevenueRecognitionRule		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_cnf_Product.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  

						INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
						INNER JOIN data_payment							on data_payment.transactionid = rr_data_revenue.transactionid
						left  JOIN DATA_PaymentCard						on data_paymentcard.paymentid = data_payment.PaymentId
						left JOIN CNF_PaymentCard						on cnf_paymentcard.paymentcardid = data_paymentcard.paymentcardid
						INNER JOIN CNF_PaymentMethod					on CNF_PaymentMethod.PaymentMethodId = data_payment.PaymentMethodId
						INNER JOIN COA_CNF_Account COA					on COA.COAAccountid = CNF_PaymentMethod.returnedcheckcoaaccountid
						INNER JOIN data_ledger							ON data_ledger.transactionid = data_transaction.transactionid
						INNER JOIN cnf_ledgeraccount					ON cnf_ledgeraccount.LedgerAccountId = data_ledger.ledgeraccountid
												INNER JOIN (select transactionid, RevenueRecognitionRuleId, RR_DATA_Revenue.RRCode, RRCalcTypeWhere, 
																	RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount,  Accountingtype
																	from RR_DATA_Revenue
																	INNER JOIN COA_CNF_Account		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
																	where COA_CNF_Account.coaAccountID = @ACCPaymentMethod
																)p    on p.transactionid = 	data_payment.transactionid


						where data_payment.paymentstatus = 1
							and DATA_Transaction.TransactionType in (select transactionid
																from #TransactionIDs)
							and DATA_Transaction.tip &lt;&gt; 0
							and RR_DATA_REVENUE.fcalcdate = @BatchDate
							and systemaccounttable = 119
							and systemaccountid = 15
							and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
							
																			
		End</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_RR_RevenueData_OnMoneyCardLoad]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_RR_RevenueData_OnMoneyCardLoad</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>CREATE Procedure dbo.otn_sp_RR_RevenueData_OnMoneyCardLoad
	@BatchDate Date,
	@RRTransDateType Integer
AS 
BEGIN
	
	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer
	Declare @OnMoneyCardCashOut Integer = 10

	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1


		BEGIN

			--Normal Transaction No Remaining Values
			INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[Saleitemid]
				   ,[MatrixCellid]
				   ,[MatrixCellCode]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays]
				   ,[AttributeIDs])
				   select *
				   from(
						select distinct coa_cnf_account.COAAccountId, 
								   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
								   RR_CNF_RevenueRecognitionRule.code,		   
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
								   COA_CNF_AccountConfig.COAAccountConfigId,
								   coa_cnf_account.COAAccountTypeId,
								   coa_cnf_account.Code as AccountCode,
								   RR_DATA_REVENUE.Transactionid as Transactionid,
								   RR_DATA_REVENUE.saleid as Saleid,
								   RR_DATA_REVENUE.SaleitemID as SaleitemID,
								   RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								   RR_DATA_REVENUE.MatrixcellCode as MatrixCode,
								   RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								   RR_DATA_REVENUE.Siteid as SiteID,
								   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								   RR_DATA_REVENUE.Workstationid as Workstationid,
								   RR_DATA_REVENUE.UserGroupid as UserGroupID,
								   RR_DATA_REVENUE.UserId as userID,
								   @BatchDate as BatchDate,
								   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
								        else DATA_Transaction.transactiondate
								   end as TransDate,
								   RR_DATA_REVENUE.Quantity as Quantity,
								   RR_DATA_REVENUE.GrossAmount as GrossAmount,
								   RR_DATA_REVENUE.NetAmount as NetAmount,
								   COA_CNF_AccountConfig.Price as ConfigPrice,
								   COA_CNF_AccountConfig.Percentage as ConfigPercentage,
								   COA_CNF_AccountConfig.RemainingValues,																		
									Case when COA_CNF_AccountConfig.Price &gt; 0 then (COA_CNF_AccountConfig.Price * RR_DATA_REVENUE.Quantity) 
										 else (ISNULL(((ABS((select (unitrecharge * Quantity)
															   from data_saleitem
															  where saleitemid = RR_DATA_REVENUE.saleitemid
										))) * COA_CNF_AccountConfig.Percentage/100), 0))																		                                                                                                                                                                                              
									end  as RevenueAmount,

								   case when TransactionType in (5, 17, 18, 20, 22, 30) and COA_CNF_AccountConfig.Accountingtype = 1 then 2
								        when TransactionType in (5, 17, 18, 20, 22, 30) and COA_CNF_AccountConfig.Accountingtype = 2 then 1
										when TransactionType in (7) and rr_data_revenue.RevenueAmount &lt; 0 and COA_CNF_AccountConfig.Accountingtype = 2 then 1
								        else COA_CNF_AccountConfig.Accountingtype
									end Accountingtype,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
								   RR_CNF_RevenueRecognitionRule.Percentage,
								   RR_CNF_RevenueRecognitionRule.Days,
								   RR_DATA_REVENUE.AttributeIDs

							from RR_DATA_REVENUE
									inner join rr_cnf_Product						ON ((RR_DATA_REVENUE.MATRIXCELLID = rr_cnf_Product.MATRIXCELLID) 
                                                      or (RR_DATA_REVENUE.MatrixSheetId = rr_cnf_Product.MatrixSheetId)
													  or (rr_cnf_product.Attributeid in (select top 1 Attributeid
																							from rr_cnf_product
																							where Attributeid in (select Value
																													from dbo.split((select rr.Attributeids
																																	from rr_data_revenue rr
																																	where rr.revenuerecognitiondataid = RR_DATA_REVENUE.revenuerecognitiondataid), '.')
																												   )
																					    )
															))
													  and rr_cnf_Product.Enabled = 1
									inner join RR_CNF_RevenueRecognitionRule		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_cnf_Product.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  
									INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
									INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
									INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 
									INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid

							where RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger IN (@OnMoneyCardCashOut)

							  and RR_CNF_RevenueRecognitionRule.Enabled = 1
							  and coa_cnf_account.Enabled = 1
							  and COA_CNF_AccountConfig.Enabled = 1
							  and ((TransactionType in (10, 20, 18, 22)) or (RR_DATA_REVENUE.transactionid in (select transactionid
																									 from data_transaction
																										Inner join data_saleitem   on data_saleitem.saleid = data_transaction.saleid
																									where data_transaction.transactiontype in (14, 16)
																									  and data_saleitem.unitrecharge &lt;&gt; 0
																								 )
																))
							  and ((coa_cnf_accountConfig.Siteid = RR_DATA_REVENUE.SiteId) or (coa_cnf_accountConfig.Siteid is null))
							  and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
							  and COA_CNF_AccountConfig.RemainingValues &lt;&gt; 1
							  and RR_DATA_REVENUE.fcalcdate = @BatchDate
							  and RR_DATA_REVENUE.coaaccountid = @suspendid
						
					)p
					where RevenueAmount &lt;&gt; 0

				--Normal Transaction with Remaining Values
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[Saleitemid]
				   ,[MatrixCellid]
				   ,[MatrixCellCode]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays]
				   ,[AttributeIDs])
				   select *
				   from(
						select distinct coa_cnf_account.COAAccountId, 
								   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
								   RR_CNF_RevenueRecognitionRule.code,		   
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
								   COA_CNF_AccountConfig.COAAccountConfigId,
								   coa_cnf_account.COAAccountTypeId,
								   coa_cnf_account.Code as AccountCode,
								   RR_DATA_REVENUE.Transactionid as Transactionid,
								   RR_DATA_REVENUE.saleid as Saleid,
								   RR_DATA_REVENUE.SaleitemID as SaleitemID,
								   RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								   RR_DATA_REVENUE.MatrixcellCode as MatrixCode,
								   RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								   RR_DATA_REVENUE.Siteid as SiteID,
								   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								   RR_DATA_REVENUE.Workstationid as Workstationid,
								   RR_DATA_REVENUE.UserGroupid as UserGroupID,
								   RR_DATA_REVENUE.UserId as userID,
								   @BatchDate as BatchDate,
								   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
								        else DATA_Transaction.transactiondate
								   end as TransDate,
								   RR_DATA_REVENUE.Quantity as Quantity,
								   RR_DATA_REVENUE.GrossAmount as GrossAmount,
								   RR_DATA_REVENUE.NetAmount as NetAmount,
								   COA_CNF_AccountConfig.Price as ConfigPrice,
								   COA_CNF_AccountConfig.Percentage as ConfigPercentage,
								   COA_CNF_AccountConfig.RemainingValues,							 
								   ISNULL((RR_DATA_REVENUE.RevenueAmount - (select ISNULL(sum(revenueamount), 0)
								                            from RR_DATA_Revenue rr
												              where rr.saleitemid = RR_DATA_REVENUE.SaleitemID
												        and rr.COAAccountid not in (@SuspendID, @ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)
												 )
									), 0)
									as RevenueAmount,
								   case when TransactionType in (5, 17, 18, 20, 22, 30) and COA_CNF_AccountConfig.Accountingtype = 1 then 2
								        when TransactionType in (5, 17, 18, 20, 22, 30) and COA_CNF_AccountConfig.Accountingtype = 2 then 1
										when TransactionType in (7) and rr_data_revenue.RevenueAmount &lt; 0 and COA_CNF_AccountConfig.Accountingtype = 2 then 1
								        else COA_CNF_AccountConfig.Accountingtype
									end Accountingtype,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
								   RR_CNF_RevenueRecognitionRule.Percentage,
								   RR_CNF_RevenueRecognitionRule.Days,
								   RR_DATA_REVENUE.AttributeIDs

						from RR_DATA_REVENUE
									inner join rr_cnf_Product						ON ((RR_DATA_REVENUE.MATRIXCELLID = rr_cnf_Product.MATRIXCELLID) 
                                                      or (RR_DATA_REVENUE.MatrixSheetId = rr_cnf_Product.MatrixSheetId)
													  or (rr_cnf_product.Attributeid in (select top 1 Attributeid
																							from rr_cnf_product
																							where Attributeid in (select Value
																													from dbo.split((select rr.Attributeids
																																	from rr_data_revenue rr
																																	where rr.revenuerecognitiondataid = RR_DATA_REVENUE.revenuerecognitiondataid), '.')
																												   )
																					    )
															))
													  and rr_cnf_Product.Enabled = 1
								inner join RR_CNF_RevenueRecognitionRule		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_cnf_Product.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  
								INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
								INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
								INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 
								INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid

							where RR_CNF_RevenueRecognitionRule.Enabled = 1
							  and coa_cnf_account.Enabled = 1
							  and COA_CNF_AccountConfig.Enabled = 1
							  and TransactionType in (10, 20, 18, 22)
							  and ((coa_cnf_accountConfig.Siteid = RR_DATA_REVENUE.SiteId) or (coa_cnf_accountConfig.Siteid is null))
							  and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger IN (@OnMoneyCardCashOut)
							  and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
							  and COA_CNF_AccountConfig.RemainingValues = 1
							  and RR_DATA_REVENUE.fcalcdate = @BatchDate
							  and RR_DATA_REVENUE.coaaccountid = @suspendid
					)p
					where RevenueAmount &lt;&gt; 0

		
		exec otn_sp_RR_RevenueData_PaymentMethodTaxDiscounts @BatchDate, '10,', @OnMoneyCardCashOut, @RRTransDateType									

	end

END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dchen</ADDEDBY><SQLVERSION>2379</SQLVERSION><RMTRACKLINK>72691</RMTRACKLINK><REASON>Adding a flag on renew to select the specific product for Installment Billing Auto Renewal

Table Created: CNF_MatrixCell_Renew</REASON><TABLENAMES>CNF_MatrixCell_Renew=RenewId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                  AND  TABLE_NAME = 'CNF_MatrixCell_Renew'))

BEGIN
Create table [CNF_MatrixCell_Renew]
(
	[RenewId] Integer Identity(1,1) NOT NULL, UNIQUE ([RenewId]),
	[MatrixCellId] Integer NOT NULL,
	[RenewMatrixCellId] Integer NOT NULL,
	[FlexAutoRenew] Smallint Default 0 NULL,
Primary Key ([RenewId])
) 
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>2378</SQLVERSION><RMTRACKLINK>72843</RMTRACKLINK><REASON>Added 'TaxesInDownPayment' and TaxInDownPaymentAmount' 
columns to DATA_PaymentFlex</REASON><TABLENAMES>DATA_PaymentFlex=PaymentId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'TaxesInDownPayment' AND
                Object_ID  = Object_ID(N'DATA_PaymentFlex'))
BEGIN
  ALTER TABLE DATA_PaymentFlex 
  ADD TaxesInDownPayment smallint NULL,
      TaxInDownPaymentAmount Float NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>2377</SQLVERSION><RMTRACKLINK>72842</RMTRACKLINK><REASON>Removed 'FeeValueType' and 'FeeValue' from CNF_FlexContractFee</REASON><TABLENAMES>CNF_FlexContractFee=FlexContractFeeId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'FeeValueType' AND
                Object_ID  = Object_ID(N'CNF_FlexContractFee'))
BEGIN
  ALTER TABLE CNF_FlexContractFee 
  DROP COLUMN FeeValueType,
       FeeValue 
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>2376</SQLVERSION><RMTRACKLINK>74982</RMTRACKLINK><REASON>Added new column 'TermsAndConditions' to CNF_FlexContract</REASON><TABLENAMES>CNF_FlexContract=FlexContractId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'TermsAndConditions' AND
                Object_ID  = Object_ID(N'CNF_FlexContract'))
BEGIN
  ALTER TABLE CNF_FlexContract 
  ADD TermsAndConditions NText NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>2375</SQLVERSION><RMTRACKLINK>72840</RMTRACKLINK><REASON>Added new column called 'AutoRenewCancelled' to DATA_PaymentFlex</REASON><TABLENAMES>DATA_PaymentFlex=PaymentId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'AutoRenewCancelled' AND
                Object_ID  = Object_ID(N'DATA_PaymentFlex'))
BEGIN
  ALTER TABLE DATA_PaymentFlex 
  ADD AutoRenewCancelled smallint NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>2374</SQLVERSION><RMTRACKLINK>BOS-66</RMTRACKLINK><REASON>Added 'enabled' field to CNF_FlexPlanTemplate</REASON><TABLENAMES>CNF_FlexPlanTemplate=FlexPlanTemplateId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Enabled' AND
                Object_ID  = Object_ID(N'CNF_FlexPlanTemplate'))
BEGIN
  ALTER TABLE CNF_FlexPlanTemplate 
  ADD Enabled smallint NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>2373</SQLVERSION><RMTRACKLINK>72842</RMTRACKLINK><REASON>Added 3 new columns to CNF_FlexContractFee:
1)FeeType
2)FeeValueType
3)FeeValue

Changed 3 fields from 'not null' to null:
1)PromotionId
2)IncludedInDp
3)Refundable</REASON><TABLENAMES>CNF_FlexContractFee=FlexContractFeeId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'FeeType' AND
                Object_ID  = Object_ID(N'CNF_FlexContractFee'))
BEGIN
  ALTER TABLE CNF_FlexContractFee 
  ADD FeeType smallint NULL,
      FeeValueType smallint NULL,
      FeeValue Float NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>ALTER TABLE CNF_FlexContractFee
ALTER COLUMN PromotionId Integer NULL</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>ALTER TABLE CNF_FlexContractFee
ALTER COLUMN IncludedInDp smallint NULL</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>ALTER TABLE CNF_FlexContractFee
ALTER COLUMN Refundable smallint NULL</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>2372</SQLVERSION><RMTRACKLINK>72766</RMTRACKLINK><REASON>COA- Revenue Recognition rule for Trigger Ticket Expiration does not see expired tickets</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_RR_RevenueData_OnTicketExpiredTrigger]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_RR_RevenueData_OnTicketExpiredTrigger</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>
CREATE Procedure dbo.otn_sp_RR_RevenueData_OnTicketExpiredTrigger
	@BatchDate Date,
	@RRTransDateType Integer
AS 
BEGIN

	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer
	Declare @TicketExpiredTrigger Integer = 3	

	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1

	BEGIN
		--Normal TicketExpired No Remaining Value
			INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[Ticketid]
				   ,[MatrixCellid]
				   ,[MatrixCellCode]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				   ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays]
				   ,[AttributeIDs])
				   select *
				   from(
				   select COA_CNF_AccountConfig.COAAccountId, 
												   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
												   RR_CNF_RevenueRecognitionRule.code,		   
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
												   COA_CNF_AccountConfig.COAAccountConfigId,
												   coa_cnf_account.COAAccountTypeId,
												   coa_cnf_account.Code as AccountCode,
												   p.Ticketid as Ticketid,
												   p.Matrixcellid as Matrixcell,
												   p.Code as MatrixCode,
												   p.MatrixSheetId as MatrixSheetID,
												   p.Siteid as SiteID,
												   @BatchDate as BatchDate,
												   p.ActiveTo,
												   1 as Quantity,
												   0 as GrossAmount,
												   0 as NetAmount,
												   COA_CNF_AccountConfig.Price as ConfigPrice,
												   COA_CNF_AccountConfig.Percentage as ConfigPercentage,
												   COA_CNF_AccountConfig.RemainingValues,									   
							case when p.netprice &gt; 0 then
								case when (select ISNULL(sum(round(RevenueAmount/rr_data_revenue.Quantity, 2)), 0)
											from rr_data_revenue 
											where rr_data_revenue.accountingtype = 1
											and ((rr_data_revenue.ticketid = p.TicketID)
													or (rr_data_revenue.saleitemid in (select saleitemid
																						from data_saleitem2Ticket
																					where data_saleitem2ticket.ticketid = p.TicketID)
																					))
											and rr_data_revenue.coaaccountid in (select coa_cnf_accountconfig.COAAccountId
																			from coa_cnf_accountconfig
																			where coa_cnf_accountconfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																				and coa_cnf_accountconfig.accountingtype = 1)) &gt; 0 
										and (p.NetPrice - (select ISNULL(sum(round(RevenueAmount/rr_data_revenue.Quantity, 2)), 0)
															from rr_data_revenue 
															where rr_data_revenue.accountingtype = 1
															and ((rr_data_revenue.ticketid = p.TicketID)
																	or (rr_data_revenue.saleitemid in (select saleitemid
																										from data_saleitem2Ticket
																									where data_saleitem2ticket.ticketid = p.TicketID)
																									))
															and rr_data_revenue.coaaccountid in (select coa_cnf_accountconfig.COAAccountId
																							from coa_cnf_accountconfig
																							where coa_cnf_accountconfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																								and coa_cnf_accountconfig.accountingtype = 1)))	&gt; 0
										THEN Case when COA_CNF_AccountConfig.Price &gt; 0 then (COA_CNF_AccountConfig.Price)
												  else (p.NetPrice - (select ISNULL(sum(round(RevenueAmount/rr_data_revenue.Quantity, 2)), 0)
																									from rr_data_revenue 
																									where rr_data_revenue.accountingtype = 1
																									and ((rr_data_revenue.ticketid = p.TicketID)
																											or (rr_data_revenue.saleitemid in (select saleitemid
																																				from data_saleitem2Ticket
																																			where data_saleitem2ticket.ticketid = p.TicketID)
																																			))
																									and rr_data_revenue.coaaccountid in (select coa_cnf_accountconfig.COAAccountId
																																	from coa_cnf_accountconfig
																																	where coa_cnf_accountconfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																																		and coa_cnf_accountconfig.accountingtype = 1))) * COA_CNF_AccountConfig.Percentage/100

												end
										when (select ISNULL(sum(round(RevenueAmount/rr_data_revenue.Quantity, 2)), 0)
																	from rr_data_revenue 
																	where rr_data_revenue.accountingtype = 1
																	and ((rr_data_revenue.ticketid = p.TicketID)
																			or (rr_data_revenue.saleitemid in (select saleitemid
																												from data_saleitem2Ticket
																											where data_saleitem2ticket.ticketid = p.TicketID)
																											))
																	and rr_data_revenue.coaaccountid in (select coa_cnf_accountconfig.COAAccountId
																									from coa_cnf_accountconfig
																									where coa_cnf_accountconfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																										and coa_cnf_accountconfig.accountingtype = 1)) &gt; 0 
											and (p.NetPrice - (select ISNULL(sum(round(RevenueAmount/rr_data_revenue.Quantity, 2)), 0)
															from rr_data_revenue 
															where rr_data_revenue.accountingtype = 1
															and ((rr_data_revenue.ticketid = p.TicketID)
																	or (rr_data_revenue.saleitemid in (select saleitemid
																										from data_saleitem2Ticket
																									where data_saleitem2ticket.ticketid = p.TicketID)
																									))
															and rr_data_revenue.coaaccountid in (select coa_cnf_accountconfig.COAAccountId
																							from coa_cnf_accountconfig
																							where coa_cnf_accountconfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																								and coa_cnf_accountconfig.accountingtype = 1)))	= 0
										   THEN Case when COA_CNF_AccountConfig.Price &gt; 0 then (COA_CNF_AccountConfig.Price)
													 else NetPrice - (select ISNULL(sum(round(RevenueAmount/rr_data_revenue.Quantity, 2)), 0)
																	from rr_data_revenue 
																	where rr_data_revenue.accountingtype = 2
																	and ((rr_data_revenue.ticketid = p.TicketID)
																			or (rr_data_revenue.saleitemid in (select saleitemid
																												from data_saleitem2Ticket
																											where data_saleitem2ticket.ticketid = p.TicketID)
																											))
																	and rr_data_revenue.coaaccountid in (select coa_cnf_accountconfig.COAAccountId
																									from coa_cnf_accountconfig
																									where coa_cnf_accountconfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																										and coa_cnf_accountconfig.accountingtype = 1)) * COA_CNF_AccountConfig.Percentage/100
											END

										when (select ISNULL(sum(round(RevenueAmount/rr_data_revenue.Quantity, 2)), 0)
																	from rr_data_revenue 
																	where rr_data_revenue.accountingtype = 1
																	and ((rr_data_revenue.ticketid = p.TicketID)
																			or (rr_data_revenue.saleitemid in (select saleitemid
																												from data_saleitem2Ticket
																											where data_saleitem2ticket.ticketid = p.TicketID)
																											))
																	and rr_data_revenue.coaaccountid in (select coa_cnf_accountconfig.COAAccountId
																									from coa_cnf_accountconfig
																									where coa_cnf_accountconfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																										and coa_cnf_accountconfig.accountingtype = 1)) = 0 
										 and (select ISNULL(sum(round(RevenueAmount/rr_data_revenue.Quantity, 2)), 0)
																	from rr_data_revenue 
																	where rr_data_revenue.accountingtype = 2
																	and ((rr_data_revenue.ticketid = p.TicketID)
																			or (rr_data_revenue.saleitemid in (select saleitemid
																												from data_saleitem2Ticket
																											where data_saleitem2ticket.ticketid = p.TicketID)
																											))
																	and rr_data_revenue.coaaccountid in (select coa_cnf_accountconfig.COAAccountId
																									from coa_cnf_accountconfig
																									where coa_cnf_accountconfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																										and coa_cnf_accountconfig.accountingtype = 1)) &gt; 0
										   THEN Case when COA_CNF_AccountConfig.Price &gt; 0 then (COA_CNF_AccountConfig.Price)
													 else (select ISNULL(sum(round(RevenueAmount/rr_data_revenue.Quantity, 2)), 0)
																	from rr_data_revenue 
																	where rr_data_revenue.accountingtype = 2
																	and ((rr_data_revenue.ticketid = p.TicketID)
																			or (rr_data_revenue.saleitemid in (select saleitemid
																												from data_saleitem2Ticket
																											where data_saleitem2ticket.ticketid = p.TicketID)
																											))
																	and rr_data_revenue.coaaccountid in (select coa_cnf_accountconfig.COAAccountId
																									from coa_cnf_accountconfig
																									where coa_cnf_accountconfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																										and coa_cnf_accountconfig.accountingtype = 1)) * COA_CNF_AccountConfig.Percentage/100
											END
											else 0							
											end 
											else Case when COA_CNF_AccountConfig.Price &gt; 0 then (COA_CNF_AccountConfig.Price)											
											       else (select ABS(ISNULL(sum(data_ledger.entryamount), 0))
														from data_ticket DT
															INNER JOIN data_ledger					on data_ledger.ticketid = DT.ticketid
														where DT.ticketid = p.TicketID
														group by data_ledger.ticketid) * COA_CNF_AccountConfig.Percentage/100
													END
											end as revenueamount,
									
							COA_CNF_AccountConfig.AccountingType,
							RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
												   RR_CNF_RevenueRecognitionRule.Percentage,
												   RR_CNF_RevenueRecognitionRule.Days,
												   p.AttributeIDs

				  from RR_CNF_RevenueRecognitionRule
					   INNER JOIN RR_CNF_Product						ON RR_CNF_Product.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
					   INNER JOIN COA_CNF_AccountConfig					ON COA_CNF_AccountConfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId 
					   INNER JOIN COA_CNF_Account						on coa_cnf_account.COAAccountId = COA_CNF_AccountConfig.coaaccountid and  COA_CNF_Account.enabled = 1
					   INNER JOIN (select	distinct CNF_MatrixCell.matrixcellid, DATA_Ticket.price, DATA_Ticket.rawprice, DATA_Ticket.ticketid, CNF_MatrixCell.AttributeSetId, AttributeIDs,
					                                 CNF_MatrixCell.Code, MatrixSheetId, DATA_Ticket.siteid, DAta_Ticket.ActiveTo, (data_ticket.price - data_ticket.taxes) NetPrice
														from DATA_Ticket
															INNER JOIN CNF_MatrixCell					on cnf_matrixcell.matrixcellid = data_ticket.matrixcellid
															INNER JOIN CNF_AttributeSet					on cnf_attributeset.AttributeSetId = CNF_MatrixCell.AttributeSetId
										
														where VoidType = 0
															and cast(data_ticket.activeto as date) = @batchdate
									)p  on						((p.matrixcellid   = rr_cnf_product.matrixcellid) or(p.matrixsheetid = rr_cnf_product.matrixsheetid)
																	or (rr_cnf_product.Attributeid in (select Value
																										from dbo.split((select Attributeids
																														from CNF_AttributeSet
																														where CNF_AttributeSet.AttributeSetId = p.AttributeSetId), '.')
																										)
																					    
															))
				where RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @TicketExpiredTrigger
				  and rr_cnf_revenuerecognitionRule.Enabled = 1
				  and COA_CNF_AccountConfig.Enabled = 1
				  and COA_CNF_AccountConfig.RemainingValues &lt;&gt; 1
				)p
				where RevenueAmount &lt;&gt; 0 



		--Normal TicketExpired with Remaining Value
			INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[Ticketid]
				   ,[MatrixCellid]
				   ,[MatrixCellCode]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				   ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays]
				   ,[AttributeIDs])
				   select *
				   from(
				   select COA_CNF_AccountConfig.COAAccountId, 
												   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
												   RR_CNF_RevenueRecognitionRule.code,		   
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
												   COA_CNF_AccountConfig.COAAccountConfigId,
												   coa_cnf_account.COAAccountTypeId,
												   coa_cnf_account.Code as AccountCode,
												   p.Ticketid as Ticketid,
												   p.Matrixcellid as Matrixcell,
												   p.Code as MatrixCode,
												   p.MatrixSheetId as MatrixSheetID,
												   p.Siteid as SiteID,
												   @BatchDate as BatchDate,
												   p.ActiveTo,
												   1 as Quantity,
												   0 as GrossAmount,
												   0 as NetAmount,
												   COA_CNF_AccountConfig.Price as ConfigPrice,
												   COA_CNF_AccountConfig.Percentage as ConfigPercentage,
												   COA_CNF_AccountConfig.RemainingValues,	
												   	case when p.netprice &gt; 0 then								   
												case when (select ISNULL(sum(round(RevenueAmount/rr_data_revenue.Quantity, 2)), 0)
													from rr_data_revenue 
													where rr_data_revenue.accountingtype = 1
													and ((rr_data_revenue.ticketid = p.TicketID)
															or (rr_data_revenue.saleitemid in (select saleitemid
																								from data_saleitem2Ticket
																							where data_saleitem2ticket.ticketid = p.TicketID)
																							))
													and rr_data_revenue.coaaccountid in (select coa_cnf_accountconfig.COAAccountId
																					from coa_cnf_accountconfig
																					where coa_cnf_accountconfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																						and coa_cnf_accountconfig.accountingtype = 1)) &gt; 0 
												and (p.NetPrice - (select ISNULL(sum(round(RevenueAmount/rr_data_revenue.Quantity, 2)), 0)
																	from rr_data_revenue 
																	where rr_data_revenue.accountingtype = 1
																	and ((rr_data_revenue.ticketid = p.TicketID)
																			or (rr_data_revenue.saleitemid in (select saleitemid
																												from data_saleitem2Ticket
																											where data_saleitem2ticket.ticketid = p.TicketID)
																											))
																	and rr_data_revenue.coaaccountid in (select coa_cnf_accountconfig.COAAccountId
																									from coa_cnf_accountconfig
																									where coa_cnf_accountconfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																										and coa_cnf_accountconfig.accountingtype = 1)))	&gt; 0
												THEN  (p.NetPrice - (select ISNULL(sum(round(RevenueAmount/rr_data_revenue.Quantity, 2)), 0)
																											from rr_data_revenue 
																											where rr_data_revenue.accountingtype = 1
																											and ((rr_data_revenue.ticketid = p.TicketID)
																													or (rr_data_revenue.saleitemid in (select saleitemid
																																						from data_saleitem2Ticket
																																					where data_saleitem2ticket.ticketid = p.TicketID)
																																					))
																											and rr_data_revenue.coaaccountid in (select coa_cnf_accountconfig.COAAccountId
																																			from coa_cnf_accountconfig
																																			where coa_cnf_accountconfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																																				and coa_cnf_accountconfig.accountingtype = 1)))
																																																								 
												when (select ISNULL(sum(round(RevenueAmount/rr_data_revenue.Quantity, 2)), 0)
																			from rr_data_revenue 
																			where rr_data_revenue.accountingtype = 1
																			and ((rr_data_revenue.ticketid = p.TicketID)
																					or (rr_data_revenue.saleitemid in (select saleitemid
																														from data_saleitem2Ticket
																													where data_saleitem2ticket.ticketid = p.TicketID)
																													))
																			and rr_data_revenue.coaaccountid in (select coa_cnf_accountconfig.COAAccountId
																											from coa_cnf_accountconfig
																											where coa_cnf_accountconfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																												and coa_cnf_accountconfig.accountingtype = 1)) &gt; 0 
													and (p.NetPrice - (select ISNULL(sum(round(RevenueAmount/rr_data_revenue.Quantity, 2)), 0)
																	from rr_data_revenue 
																	where rr_data_revenue.accountingtype = 1
																	and ((rr_data_revenue.ticketid = p.TicketID)
																			or (rr_data_revenue.saleitemid in (select saleitemid
																												from data_saleitem2Ticket
																											where data_saleitem2ticket.ticketid = p.TicketID)
																											))
																	and rr_data_revenue.coaaccountid in (select coa_cnf_accountconfig.COAAccountId
																									from coa_cnf_accountconfig
																									where coa_cnf_accountconfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																										and coa_cnf_accountconfig.accountingtype = 1)))	= 0
												   THEN Case when COA_CNF_AccountConfig.Price &gt; 0 then (COA_CNF_AccountConfig.Price)
															 else p.netprice - 	(ISNULL((select sum(RevenueAmount)
																					from rr_data_revenue 
																					where RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																					and ((rr_data_revenue.ticketid = p.Ticketid)
																									or (rr_data_revenue.saleitemid in (select saleitemid
																																		from data_saleitem2Ticket
																																	where data_saleitem2ticket.ticketid = p.Ticketid)
																																	))
																					and rr_data_revenue.accountingtype = COA_CNF_AccountConfig.accountingtype
																					and rr_data_revenue.coaaccountid in (select CC.COAAccountId
																															from coa_cnf_accountconfig CC
																															where CC.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																																and CC.accountingtype = coa_cnf_accountconfig.Accountingtype)
																				), 0))
													END

												when (select ISNULL(sum(round(RevenueAmount/rr_data_revenue.Quantity, 2)), 0)
																			from rr_data_revenue 
																			where rr_data_revenue.accountingtype = 1
																			and ((rr_data_revenue.ticketid = p.TicketID)
																					or (rr_data_revenue.saleitemid in (select saleitemid
																														from data_saleitem2Ticket
																													where data_saleitem2ticket.ticketid = p.TicketID)
																													))
																			and rr_data_revenue.coaaccountid in (select coa_cnf_accountconfig.COAAccountId
																											from coa_cnf_accountconfig
																											where coa_cnf_accountconfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																												and coa_cnf_accountconfig.accountingtype = 1)) = 0 
												 and (select ISNULL(sum(round(RevenueAmount/rr_data_revenue.Quantity, 2)), 0)
																			from rr_data_revenue 
																			where rr_data_revenue.accountingtype = 2
																			and ((rr_data_revenue.ticketid = p.TicketID)
																					or (rr_data_revenue.saleitemid in (select saleitemid
																														from data_saleitem2Ticket
																													where data_saleitem2ticket.ticketid = p.TicketID)
																													))
																			and rr_data_revenue.coaaccountid in (select coa_cnf_accountconfig.COAAccountId
																											from coa_cnf_accountconfig
																											where coa_cnf_accountconfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																												and coa_cnf_accountconfig.accountingtype = 1)) &gt; 0
												   THEN p.netprice - 	(ISNULL((select sum(RevenueAmount)
																					from rr_data_revenue 
																					where RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																					and ((rr_data_revenue.ticketid = p.Ticketid)
																									or (rr_data_revenue.saleitemid in (select saleitemid
																																		from data_saleitem2Ticket
																																	where data_saleitem2ticket.ticketid = p.Ticketid)
																																	))
																					and rr_data_revenue.accountingtype = COA_CNF_AccountConfig.accountingtype
																					and rr_data_revenue.coaaccountid in (select CC.COAAccountId
																															from coa_cnf_accountconfig CC
																															where CC.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																																and CC.accountingtype = coa_cnf_accountconfig.Accountingtype)
																				), 0))
											else 0							
											end 
											else  (select ABS(ISNULL(sum(data_ledger.entryamount), 0))
														from data_ticket DT
															INNER JOIN data_ledger					on data_ledger.ticketid = DT.ticketid
														where DT.ticketid = p.TicketID
														group by data_ledger.ticketid) - 
														(ISNULL((select sum(RevenueAmount)
																					from rr_data_revenue 
																					where RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																					and ((rr_data_revenue.ticketid = p.Ticketid)
																									or (rr_data_revenue.saleitemid in (select saleitemid
																																		from data_saleitem2Ticket
																																	where data_saleitem2ticket.ticketid = p.Ticketid)
																																	))
																					and rr_data_revenue.accountingtype = COA_CNF_AccountConfig.accountingtype
																					and rr_data_revenue.coaaccountid in (select CC.COAAccountId
																															from coa_cnf_accountconfig CC
																															where CC.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																																and CC.accountingtype = coa_cnf_accountconfig.Accountingtype)
																				), 0))
													
											end as revenueamount,
												   COA_CNF_AccountConfig.AccountingType,
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
												   RR_CNF_RevenueRecognitionRule.Percentage,
												   RR_CNF_RevenueRecognitionRule.Days,
												   p.AttributeIDs

				  from RR_CNF_RevenueRecognitionRule
					   INNER JOIN RR_CNF_Product						ON RR_CNF_Product.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
					   INNER JOIN COA_CNF_AccountConfig					ON COA_CNF_AccountConfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId 
					   INNER JOIN COA_CNF_Account						on coa_cnf_account.COAAccountId = COA_CNF_AccountConfig.coaaccountid and  COA_CNF_Account.enabled = 1
					   INNER JOIN (select	distinct CNF_MatrixCell.matrixcellid, DATA_Ticket.price, DATA_Ticket.rawprice, DATA_Ticket.ticketid, CNF_MatrixCell.AttributeSetId, AttributeIDs,
					                                 CNF_MatrixCell.Code, MatrixSheetId, DATA_Ticket.siteid, DAta_Ticket.ActiveTo, (data_ticket.price - data_ticket.taxes) NetPrice
														from DATA_Ticket
															INNER JOIN CNF_MatrixCell					on cnf_matrixcell.matrixcellid = data_ticket.matrixcellid
															INNER JOIN CNF_AttributeSet					on cnf_attributeset.AttributeSetId = CNF_MatrixCell.AttributeSetId
										
														where VoidType = 0
															and cast(data_ticket.activeto as date) = @batchdate
									)p  on						((p.matrixcellid   = rr_cnf_product.matrixcellid) or(p.matrixsheetid = rr_cnf_product.matrixsheetid)
																	or (rr_cnf_product.Attributeid in (select Value
																										from dbo.split((select Attributeids
																														from CNF_AttributeSet
																														where CNF_AttributeSet.AttributeSetId = p.AttributeSetId), '.')
																										)
																					    
															))

				where RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @TicketExpiredTrigger
				  and rr_cnf_revenuerecognitionRule.Enabled = 1
				  and COA_CNF_AccountConfig.Enabled = 1
				  and COA_CNF_AccountConfig.RemainingValues = 1
				)p
				where RevenueAmount &lt;&gt; 0 


	end
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>FABRY</ADDEDBY><SQLVERSION>2371</SQLVERSION><RMTRACKLINK>72734</RMTRACKLINK><REASON>SIAE_Event Add filed GeneraLtaRca smallint

 0 - Add field
1 - update old data
2 - Add NOT NULL

</REASON><TABLENAMES>SIAE_Event=EventId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>
IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'GeneraLtaRca' AND
                Object_ID  = Object_ID(N'SIAE_Event'))
BEGIN
  ALTER TABLE SIAE_Event 
  ADD GeneraLtaRca smallint NULL
END




</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>
UPDATE SIAE_Event
SET GeneraLtaRca = 1
WHERE GeneraLtaRca is null
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>
ALTER TABLE SIAE_Event ALTER COLUMN GeneraLtaRca smallint NOT NULL


</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>2370</SQLVERSION><RMTRACKLINK>BOS-89</RMTRACKLINK><REASON>4 new fields added to DATA_PaymentFlex: FlexPlanTemplateId, FlexPlanOption, NonFinanceableAmount, and ContractStartingDate</REASON><TABLENAMES>DATA_PaymentFlex=PaymentId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'FlexPlanTemplateId' AND
                Object_ID  = Object_ID(N'DATA_PaymentFlex'))
BEGIN
  ALTER TABLE DATA_PaymentFlex 
  ADD FlexPlanTemplateId Integer NULL,
      FlexPlanOption smallint NULL,
      NonFinanceableAmount Float NULL,
      ContractStartingDate Datetime NULL
  CONSTRAINT [fk_DATA_PaymentFlex_FlexPlanTemplateId] FOREIGN KEY([FlexPlanTemplateId])
  REFERENCES [CNF_FlexPlanTemplate] ([FlexPlanTemplateId])
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>2369</SQLVERSION><RMTRACKLINK>71708</RMTRACKLINK><REASON>Added new field 'ChangeStartingDate' to table 'CNF_FlexContract'</REASON><TABLENAMES>CNF_FlexContract=FlexContractId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'ChangeStartingDate' AND
                Object_ID  = Object_ID(N'CNF_FlexContract'))
BEGIN
  ALTER TABLE CNF_FlexContract ADD ChangeStartingDate Smallint NULL default 0
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>stefanocoluccia</ADDEDBY><SQLVERSION>2368</SQLVERSION><RMTRACKLINK>72096</RMTRACKLINK><REASON>Added column ReservationExclusive to CNF_Survey
[0] Add column ReservationExclusive </REASON><TABLENAMES>CNF_Survey=SurveyId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'ReservationExclusive' AND
                Object_ID  = Object_ID(N'CNF_Survey'))
BEGIN
  ALTER TABLE CNF_Survey 
  ADD ReservationExclusive smallint NOT NULL DEFAULT(0)
END
</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>stefanocoluccia</ADDEDBY><SQLVERSION>2367</SQLVERSION><RMTRACKLINK>72626</RMTRACKLINK><REASON>Force the field OriginalVoid = Lk_PaymentMethodRefundableType_NotRefundable for money card  payment method </REASON><TABLENAMES>CNF_PaymentMethod=PaymentMethodId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>update CNF_PaymentMethod set OriginalVoid = 3 where CNF_PaymentMethod.PaymentMethodId in 
  	(SELECT PM.PaymentMethodId from CNF_PaymentMethod as PM with(nolock)
       cross apply(
                    SELECT DriverId from CNF_Driver with(nolock) where FamilyType = 508) as DR
       where PM.DriverId = DR.DriverId)
         </SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>Emanuele Candido</ADDEDBY><SQLVERSION>2366</SQLVERSION><RMTRACKLINK>72031</RMTRACKLINK><REASON>Add Index to DATA_SurveyItem

ALTER INDEX PK__CNF_Alte__6EBEEE9BC59D2038 ON CNF_AlternativeCodes  

ALTER INDEX PK_DATA_History_Operation ON
DATA_History_Operation</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS 
  (SELECT * FROM sys.indexes WHERE name = 'IDX_DATA_SurveyItem_EntityType_EntityId' AND 
   object_id = OBJECT_ID('[dbo].[DATA_SurveyItem]'))
begin
  CREATE NONCLUSTERED INDEX [IDX_DATA_SurveyItem_EntityType_EntityId]
  ON [dbo].[DATA_SurveyItem] ([EntityType],[EntityId])
end</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>ALTER INDEX 
  PK_DATA_History_Operation ON DATA_History_Operation
SET 
  (ALLOW_PAGE_LOCKS = ON)</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>declare @pk varchar(max)
declare myCurs CURSOR 

FOR
  SELECT 
    Constraint_Name AS [Constraint]
  FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
  where
    COLUMN_NAME like '%alternativecodesid%'

open myCurs
fetch next from myCurs into @pk

while (@@FETCH_STATUS = 0)
begin
  exec('ALTER INDEX ' + @pk + ' ON CNF_AlternativeCodes SET (ALLOW_PAGE_LOCKS = ON)')
  fetch next from myCurs into @pk
end

close myCurs
deallocate myCurs</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>2365</SQLVERSION><RMTRACKLINK>72397</RMTRACKLINK><REASON>COA - MoneyCard Load trigger does not work when MoneyCard stored value is preconfigured</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_RR_RevenueData_OnTimePeriodTrigger]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_RR_RevenueData_OnTimePeriodTrigger</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>CREATE Procedure dbo.otn_sp_RR_RevenueData_OnTimePeriodTrigger
	@BatchDate Date,
	@RRTransDateType Integer
AS 
BEGIN
	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer
	Declare @OnTimePeriodTrigger Integer = 4	

	create table #RulesToRun
	(
		RRID int
	)

	Declare @TodayDayofWeek Int
	Declare @TodaySpecificDay Int
	Declare @TodayMonthlyWeek Int
	Declare @TodayMonth Int
	Declare @TodayDay Int
	Declare @TodayDaysofWeek Int

	select @TodayDayofWeek   = datePart(weekday, cast(@BatchDate as date)),
		   @TodayMonth       = datePart(mm, cast(@BatchDate as date)),
		   @TodaySpecificDay = datePart(dd, cast(@BatchDate as date)),
		   @TodayMonthlyWeek = datediff(week, dateadd(week, datediff(week, 0, dateadd(month, datediff(month, 0, cast(@BatchDate as date)), 0)), 0), getdate() - 1) + 1

	if @TodayDaysofWeek = 6 
	   SET @TodayDaysofWeek = 1

	insert into #RulesToRun
	select	distinct RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
		from RR_CNF_RevenueRecognitionRuleSchedule
			INNER JOIN RR_CNF_RevenueRecognitionRule					ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRuleSchedule.RevenueRecognitionRuleId

	where RR_CNF_RevenueRecognitionRule.Enabled = 1
	  and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
	  and ((PeriodOption = 1)
			  or ((PeriodOption = 2) and (((@TodayDayofWeek = 1) and (ActiveSunday = 1))
											or ((@TodayDayofWeek = 2) and (ActiveMonday = 1))
											or ((@TodayDayofWeek = 3) and (ActiveTuesday = 1))
											or ((@TodayDayofWeek = 4) and (ActiveWednesday = 1))
											or ((@TodayDayofWeek = 5) and (ActiveThursday = 1))
											or ((@TodayDayofWeek = 6) and (ActiveFriday = 1))
											or ((@TodayDayofWeek = 6) and (ActiveFriday = 1))
											or ((@TodayDayofWeek = 7) and (ActiveSaturday = 1))
										)))
			 or ((PeriodOption = 3) and ((SpecificDay = @TodaySpecificDay) 
										  or ((WeekOption = @TodayMonthlyWeek and (((@TodayDayofWeek = 1) and (ActiveSunday = 1))
																					or ((@TodayDayofWeek = 2) and (ActiveMonday = 1))
																					or ((@TodayDayofWeek = 3) and (ActiveTuesday = 1))
																					or ((@TodayDayofWeek = 4) and (ActiveWednesday = 1))
																					or ((@TodayDayofWeek = 5) and (ActiveThursday = 1))
																					or ((@TodayDayofWeek = 6) and (ActiveFriday = 1))
																					or ((@TodayDayofWeek = 6) and (ActiveFriday = 1))
																					or ((@TodayDayofWeek = 7) and (ActiveSaturday = 1))
																					or (LastDayOptionWeek = 1))
																				))))  
			 or ((PeriodOption = 4) and (((SpecificDay = @TodaySpecificDay) and (MonthOption = @TodayMonth))  
										   or ((WeekOption = @TodayMonthlyWeek and (((@TodayDayofWeek = 1) and (ActiveSunday = 1))
																					or ((@TodayDayofWeek = 2) and (ActiveMonday = 1))
																					or ((@TodayDayofWeek = 3) and (ActiveTuesday = 1))
																					or ((@TodayDayofWeek = 4) and (ActiveWednesday = 1))
																					or ((@TodayDayofWeek = 5) and (ActiveThursday = 1))
																					or ((@TodayDayofWeek = 6) and (ActiveFriday = 1))
																					or ((@TodayDayofWeek = 6) and (ActiveFriday = 1))
																					or ((@TodayDayofWeek = 7) and (ActiveSaturday = 1))
																					or (LastDayOptionWeek = 1))
																				)))
																				and (MonthOption = @TodayMonth))



			INSERT INTO [dbo].[RR_DATA_Revenue]
						   ([COAAccountId]
						   ,[RevenueRecognitionRuleId]
						   ,[RRCode]
						   ,[RRCalcTypeWhere]
						   ,[RRCalcTypeMethod]
						   ,[COAAccountConfigId]
						   ,[COAAccountType]
						   ,[COAAccountCode]
						   ,[SaleId]
						   ,[Ticketid]
						   ,[MatrixCellid]
						   ,[MatrixCellCode]
						   ,[MatrixSheetid]
						   ,[SiteId]
						   ,[OperatingAreaId]
						   ,[WorkstationId]
						   ,[Usergroupid]
						   ,[UserId]
						   ,[FCalcDate]
						   ,[FRevenueDate]
						   ,[Quantity]
						   ,[GrossAmount]
						   ,[NetAmount]
						   ,[Price]
						   ,[Percentage]
						   ,[RemaningValues]
						   ,[RevenueAmount]
						   ,[AccountingType]
						   ,[RRCalcTypeTrigger]
						   ,[RRPercentage]			
						   ,[RRDays]
						   ,[AttributeIDs]
						   )
						   select *
						   from (
							select distinct p.COAAccountId, 
								   p.RevenueRecognitionRuleId,
								   p.RRcode,		   
								   p.RRCalcTypeWhere,
								   p.RRCalcTypeMethod,	   
								   p.COAAccountConfigId,
								   p.COAAccountTypeId,
								   p.AccountCode as AccountCode,
								   RR_DATA_REVENUE.saleid as Saleid,
								   ISNULL(rdata.Ticketid, DATA_SaleItem2Ticket.Ticketid) TicketID, 
								   RR_DATA_REVENUE.Matrixcellid,
								   RR_DATA_REVENUE.MatrixcellCode,
								   RR_DATA_REVENUE.MatrixSheetId,
								   RR_DATA_REVENUE.Siteid,
								   RR_DATA_REVENUE.OperatingAreaId,
								   RR_DATA_REVENUE.Workstationid,
								   RR_DATA_REVENUE.UserGroupid,
								   RR_DATA_REVENUE.UserId as userID,
								   @BatchDate as BatchDate,
								   @BatchDate as TransDate,
								   RR_DATA_REVENUE.Quantity as Quantity,
								   RR_DATA_REVENUE.GrossAmount as GrossAmount,
								   RR_DATA_REVENUE.NetAmount as NetAmount,
								   p.Price as ConfigPrice,
								   p.Percentage as ConfigPercentage,
								   p.RemainingValues,																		
								  round(Case when p.Price &gt; 0 then (p.Price) 
									   else case when ((((DATA_Ticket.Price - DATA_Ticket.taxes) - ISNULL(rdata.TotalUsed, 0)) &gt; 0) and ((DATA_Ticket.Price - DATA_Ticket.taxes) - ISNULL(rdata.TotalUsed, 0)) &gt;= ((((DATA_Ticket.Price - DATA_Ticket.taxes) * p.RRPercentage)/100 * p.Percentage)/100)) 
										              then ((((DATA_Ticket.Price - DATA_Ticket.taxes) * p.RRPercentage)/100 * p.Percentage)/100)
									              else (((DATA_Ticket.Price - DATA_Ticket.taxes) - ISNULL(rdata.TotalUsed, 0)) * p.Percentage)/100
								            end
							       end, 2) as RevenueAmount,
								   p.Accountingtype,
								   p.RRCalcTypeTrigger,
								   p.RRPercentage,
								   p.Days,
								   RR_DATA_REVENUE.AttributeIDs

							from RR_DATA_REVENUE
								INNER JOIN DATA_SaleItem							ON data_saleitem.SaleItemId		   = rr_data_revenue.saleitemid
								INNER JOIN DATA_SaleItem2Ticket						on data_saleitem2ticket.Saleitemid = data_saleitem.saleitemid
								INNER JOIN DATA_Ticket								on data_ticket.ticketid = data_saleitem2ticket.ticketid
								INNER JOIN (  
										select RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleid, 
										RR_CNF_RevenueRecognitionRule.Code as RRCode,
										RR_CNF_RevenueRecognitionRule.Days,
										RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
										RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,
										FromDate,
										ToDate,
										RR_CNF_RevenueRecognitionRule.rrCalcTypeTrigger,
										RR_CNF_RevenueRecognitionRule.Percentage as RRPercentage,
										COA_CNF_AccountConfig.CoaAccountid,
										COA_CNF_AccountConfig.AccountingType,
										COA_CNF_AccountConfig.Price,
										COA_CNF_AccountConfig.Percentage,
										COA_CNF_AccountConfig.RemainingValues,
										COA_CNF_AccountConfig.SiteID,
										coa_cnf_account.code as AccountCode,
										COA_CNF_AccountType.Code as AccountTypeCode,
										COA_CNF_AccountType.COAAccountTypeId,
										rr_cnf_Product.MatrixcellID,
										rr_cnf_Product.matrixsheetID,
										COA_CNF_AccountConfig.COAAccountConfigId,
										rr_cnf_Product.AttributeId

								from RR_CNF_RevenueRecognitionRule
									inner join rr_cnf_Product						ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_cnf_product.RevenueRecognitionRuleId and rr_cnf_Product.Enabled = 1		
									INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
									INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
									INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 

								where COA_CNF_AccountConfig.RemainingValues &lt;&gt; 1
								  and RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId in (select RRID 
								                                                                   from #RulesToRun)

									)p   ON ((RR_DATA_REVENUE.MATRIXCELLID = p.MATRIXCELLID) or (RR_DATA_REVENUE.MatrixSheetId = p.MatrixSheetId)
										or (p.Attributeid in (select Value
																								from dbo.split((select Attributeids
																												from RR_DATA_REVENUE rr
																												where rr.RevenueRecognitionDataId = rr_data_revenue.RevenueRecognitionDataId), '.')
																								)
																					    
													))

                                   LEFT JOIN (select ticketid, AttributeIDs, coaaccountid, AccountingType, sum(revenueamount) as TotalUsed
												from rr_data_revenue
												where ticketid is not null
												group by ticketid, AccountingType, coaaccountid, AttributeIDs
												)rdata									ON rdata.ticketid = ISNULL(RR_DATA_REVENUE.ticketid, DATA_SaleItem2Ticket.ticketid)	and rdata.AccountingType = p.AccountingType 
												                                           and rdata.coaaccountid = p.coaaccountid
					where data_ticket.FEncodeDate &lt;= @BatchDate
					  and data_ticket.voidtype = 0
					)p
					where Round(RevenueAmount, 12) &lt;&gt; 0 


					INSERT INTO [dbo].[RR_DATA_Revenue]
						   ([COAAccountId]
						   ,[RevenueRecognitionRuleId]
						   ,[RRCode]
						   ,[RRCalcTypeWhere]
						   ,[RRCalcTypeMethod]
						   ,[COAAccountConfigId]
						   ,[COAAccountType]
						   ,[COAAccountCode]
						   ,[SaleId]
						   ,[Ticketid]
						   ,[MatrixCellid]
						   ,[MatrixCellCode]
						   ,[MatrixSheetid]
						   ,[SiteId]
						   ,[OperatingAreaId]
						   ,[WorkstationId]
						   ,[Usergroupid]
						   ,[UserId]
						   ,[FCalcDate]
						   ,[FRevenueDate]
						   ,[Quantity]
						   ,[GrossAmount]
						   ,[NetAmount]
						   ,[Price]
						   ,[Percentage]
						   ,[RemaningValues]
						   ,[RevenueAmount]
						   ,[AccountingType]
						   ,[RRCalcTypeTrigger]
						   ,[RRPercentage]			
						   ,[RRDays]
						   ,[AttributeIDs]
						   )
						   select *
						   from (
							select distinct p.COAAccountId, 
								   p.RevenueRecognitionRuleId,
								   p.RRcode,		   
								   p.RRCalcTypeWhere,
								   p.RRCalcTypeMethod,	   
								   p.COAAccountConfigId,
								   p.COAAccountTypeId,
								   p.AccountCode as AccountCode,
								   RR_DATA_REVENUE.saleid as Saleid,
								   ISNULL(rdata.Ticketid, DATA_SaleItem2Ticket.Ticketid) as ticketID, 
								   RR_DATA_REVENUE.Matrixcellid,
								   RR_DATA_REVENUE.MatrixcellCode,
								   RR_DATA_REVENUE.MatrixSheetId,
								   RR_DATA_REVENUE.Siteid,
								   RR_DATA_REVENUE.OperatingAreaId,
								   RR_DATA_REVENUE.Workstationid,
								   RR_DATA_REVENUE.UserGroupid,
								   RR_DATA_REVENUE.UserId as userID,
								   @BatchDate as BatchDate,
								   @BatchDate as TransDate,
								   RR_DATA_REVENUE.Quantity as Quantity,
								   RR_DATA_REVENUE.GrossAmount as GrossAmount,
								   RR_DATA_REVENUE.NetAmount as NetAmount,
								   p.Price as ConfigPrice,
								   p.Percentage as ConfigPercentage,
								   p.RemainingValues,																		
								  round(case when ((((DATA_Ticket.Price - DATA_Ticket.taxes) - ISNULL(TotalUsed, 0)) &gt; 0) and ((
																					(((DATA_Ticket.Price - DATA_Ticket.taxes) *  p.rrPercentage)/100) -  
																						((
																						(((DATA_Ticket.Price - DATA_Ticket.taxes) *  p.rrPercentage)/100) * (select sum(percentage)
																																							from coa_cnf_accountconfig AC
																																							where AC.revenuerecognitionruleid = p.RevenueRecognitionRuleId
																																							and ac.accountingtype = p.accountingtype
																																							)
																						)/100)) &lt;= ((DATA_Ticket.Price - DATA_Ticket.taxes) - ISNULL(TotalUsed, 0))))

														then 
														((((DATA_Ticket.Price - DATA_Ticket.taxes) *  p.rrPercentage)/100) -  ((((DATA_Ticket.Price - DATA_Ticket.taxes) *  p.RRPercentage)/100) * (select sum(percentage)
																																from coa_cnf_accountconfig AC
																																where AC.revenuerecognitionruleid = p.RevenueRecognitionRuleId
																																and ac.accountingtype = p.accountingtype
																																))/100)
													else (DATA_Ticket.Price - DATA_Ticket.taxes) - TotalUsed
												end, 2) as RevenueAmount,
								   p.Accountingtype,
								   p.RRCalcTypeTrigger,
								   p.RRPercentage,
								   p.Days,
								   RR_DATA_REVENUE.AttributeIDs

							from RR_DATA_REVENUE
								INNER JOIN DATA_SaleItem							ON data_saleitem.SaleItemId		   = rr_data_revenue.saleitemid
								INNER JOIN DATA_SaleItem2Ticket						on data_saleitem2ticket.Saleitemid = data_saleitem.saleitemid
								INNER JOIN DATA_Ticket								on data_ticket.ticketid = data_saleitem2ticket.ticketid
								INNER JOIN (  
										select  RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleid, 
										RR_CNF_RevenueRecognitionRule.Code as RRCode,
										RR_CNF_RevenueRecognitionRule.Days,
										RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
										RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,
										FromDate,
										ToDate,
										RR_CNF_RevenueRecognitionRule.rrCalcTypeTrigger,
										RR_CNF_RevenueRecognitionRule.Percentage as RRPercentage,
										COA_CNF_AccountConfig.CoaAccountid,
										COA_CNF_AccountConfig.AccountingType,
										COA_CNF_AccountConfig.Price,
										COA_CNF_AccountConfig.Percentage,
										COA_CNF_AccountConfig.RemainingValues,
										COA_CNF_AccountConfig.SiteID,
										coa_cnf_account.code as AccountCode,
										COA_CNF_AccountType.Code as AccountTypeCode,
										COA_CNF_AccountType.COAAccountTypeId,
										rr_cnf_Product.MatrixcellID,
										rr_cnf_Product.matrixsheetID,
										COA_CNF_AccountConfig.COAAccountConfigId,
										rr_cnf_Product.AttributeID

								from RR_CNF_RevenueRecognitionRule
									inner join rr_cnf_Product						ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_cnf_product.RevenueRecognitionRuleId and rr_cnf_Product.Enabled = 1		
									INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
									INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
									INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 

								where COA_CNF_AccountConfig.RemainingValues = 1
								  and RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId in (select RRID 
								                                                                   from #RulesToRun)

								)p   ON ((RR_DATA_REVENUE.MATRIXCELLID = p.MATRIXCELLID) or (RR_DATA_REVENUE.MatrixSheetId = p.MatrixSheetId)
										or (p.Attributeid in (select Value
																								from dbo.split((select Attributeids
																												from RR_DATA_REVENUE rr
																												where rr.RevenueRecognitionDataId = rr_data_revenue.RevenueRecognitionDataId), '.')
																								)
																					    
													))
                                   LEFT JOIN (select ticketid, AttributeIDs, coaaccountid, AccountingType, sum(revenueamount) as TotalUsed
												from rr_data_revenue
												where ticketid is not null
												group by ticketid, AccountingType, coaaccountid, AttributeIDs
												)rdata									ON rdata.ticketid = ISNULL(RR_DATA_REVENUE.ticketid, DATA_SaleItem2Ticket.ticketid)	and rdata.AccountingType = p.AccountingType 
												                                           and rdata.coaaccountid = p.coaaccountid
								where data_ticket.FEncodeDate &lt;= @BatchDate
								  and data_ticket.voidtype = 0
								)r
								where Round(RevenueAmount, 12) &lt;&gt; 0 

END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_RR_RevenueData_PaymentMethodTaxDiscounts]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_RR_RevenueData_PaymentMethodTaxDiscounts</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>CREATE Procedure dbo.otn_sp_RR_RevenueData_PaymentMethodTaxDiscounts
	@BatchDate Date,
	@Transactions varchar(500),
	@Trigger int,
	@RRTransDateType integer
AS 
BEGIN
	 
	Create Table #TransactionIDs(
	TransactionId Int NOT NULL)

	DECLARE @DelimPosition INT

    SET @DelimPosition = CHARINDEX(',', @Transactions)

    WHILE @DelimPosition &gt; 0
    BEGIN
        INSERT INTO #TransactionIDs(TransactionId)
            VALUES(CAST(RTRIM(LEFT(@Transactions, @DelimPosition - 1)) AS INT))
        SET @Transactions = right(@Transactions, len(@Transactions) - @DelimPosition)

        SET @DelimPosition = CHARINDEX(',', @Transactions)
    END

	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer

	Declare @OnCreditWriteoff Integer = 9
	Declare @StartTime DateTime

	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1
	

		--	--	--Normal Sale Split out the Payments to Smaller Subset.
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])				    
						select distinct COA.COAAccountId, 
						   p.RevenueRecognitionRuleId,
						   p.RRCode,		   
						   p.RRCalcTypeWhere,
						   p.RRCalcTypeMethod,	   
						   p.COAAccountConfigId,
						   COA.COAAccountTypeId,
						   COA.Code,
						   RR_DATA_REVENUE.Transactionid as Transactionid,
						   RR_DATA_REVENUE.saleid as Saleid,
						   RR_DATA_REVENUE.Siteid as SiteID,
						   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
						   RR_DATA_REVENUE.Workstationid as Workstationid,
						   RR_DATA_REVENUE.UserGroupid as UserGroupID,
						   RR_DATA_REVENUE.UserId as userID,
						   @BatchDate,
						   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
							    else DATA_Transaction.transactiondate
						   end as TransDate,
						   0,
						   0,
						   0,
						   0,
						   100,
						   0, 	
						   ABS ((data_payment.PaymentAmount) -
						   (case when data_payment.paymentid = (select top 1 paymentid
																from data_payment
																where transactionid = RR_DATA_REVENUE.Transactionid
																	and data_payment.paymentamount &gt; (select sum(Change) *-1
																								from data_transaction
																								where data_transaction.transactionid = RR_DATA_REVENUE.Transactionid))
								then (select sum(Change) *-1
																								from data_transaction
																								where data_transaction.transactionid = RR_DATA_REVENUE.Transactionid)
								else 0
							end ))
							as RevenueAmount,
							p.Accountingtype,		
						    p.RRCalcTypeTrigger,
						    p.RRPercentage,
						    p.RRDays

						from RR_DATA_REVENUE
						INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
						INNER JOIN data_payment							on data_payment.transactionid = rr_data_revenue.transactionid
						left  JOIN DATA_PaymentCard						on data_paymentcard.paymentid = data_payment.PaymentId
						left JOIN CNF_PaymentCard						on cnf_paymentcard.paymentcardid = data_paymentcard.paymentcardid
						INNER JOIN CNF_PaymentMethod					on CNF_PaymentMethod.PaymentMethodId = data_payment.PaymentMethodId
						INNER JOIN COA_CNF_Account COA					on COA.COAAccountid = ISNULL(cnf_paymentcard.coaaccountid, CNF_PaymentMethod.COAAccountid)

						INNER JOIN (select transactionid, RevenueRecognitionRuleId, RR_DATA_Revenue.RRCode, RRCalcTypeWhere, 
											RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount,  Accountingtype
											from RR_DATA_Revenue
											INNER JOIN COA_CNF_Account		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
											where COA_CNF_Account.coaAccountID = @ACCPaymentMethod
											--and RR_DATA_Revenue.RRCalcTypeTrigger = @Trigger
											and RR_DATA_REVENUE.fcalcdate = @BatchDate
										)p    on p.transactionid = 	data_payment.transactionid

					where data_payment.paymentstatus = 1
					and DATA_Transaction.TransactionType in (select transactionid
																from #TransactionIDs)
					and RR_DATA_REVENUE.fcalcdate = @BatchDate
					--and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
					AND data_payment.Transactionid not in (select distinct transactionid
												from rr_Data_Revenue
												where matrixcellid is null
												  and coaaccountid in (select distinct coaaccountid
																			from cnf_paymentmethod CP
																			where coaaccountid is not null
																			union all
																			select distinct coaaccountid
																			from cnf_paymentcard pc
																			where coaaccountid is not null
																		)
																			and transactionid is not null
												)
					AND data_payment.Transactionid in (select distinct transactionid
												from rr_Data_Revenue
												where coaaccountid in (@ACCPaymentMethod)
												)
					 AND RR_DATA_REVENUE.coaaccountid not in (@ACCPaymentMethod)


		----Normal Sale Split out the Payments to Payment Fees
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])				    
				select distinct COA.COAAccountId, 
						   p.RevenueRecognitionRuleId,
						   p.RRCode,		   
						   p.RRCalcTypeWhere,
						   p.RRCalcTypeMethod,	   
						   p.COAAccountConfigId,
						   COA.COAAccountTypeId,
						   COA.Code,
						   RR_DATA_REVENUE.Transactionid as Transactionid,
						   RR_DATA_REVENUE.saleid as Saleid,
						   RR_DATA_REVENUE.Siteid as SiteID,
						   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
						   RR_DATA_REVENUE.Workstationid as Workstationid,
						   RR_DATA_REVENUE.UserGroupid as UserGroupID,
						   RR_DATA_REVENUE.UserId as userID,
						   @BatchDate,
						   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
							    else DATA_Transaction.transactiondate
						   end as TransDate,
						   0,
						   0,
						   0,
						   0,
						   100,
						   0,  	
						   data_payment.paymentfee as RevenueAmount,
						   case when data_payment.paymentfee &gt;= 0 then 2
						        else 1
							end accountingtype,		
						   p.RRCalcTypeTrigger,
						   p.RRPercentage,
						   p.RRDays

						from RR_DATA_REVENUE
						INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
						INNER JOIN data_payment							on data_payment.transactionid = rr_data_revenue.transactionid
						left  JOIN DATA_PaymentCard						on data_paymentcard.paymentid = data_payment.PaymentId
						left JOIN CNF_PaymentCard						on cnf_paymentcard.paymentcardid = data_paymentcard.paymentcardid
						INNER JOIN CNF_PaymentMethod					on CNF_PaymentMethod.PaymentMethodId = data_payment.PaymentMethodId
						INNER JOIN COA_CNF_Account COA					on COA.COAAccountid = CNF_PaymentMethod.FeeCOAAccountId

						INNER JOIN (select transactionid, RevenueRecognitionRuleId, RR_DATA_Revenue.RRCode, RRCalcTypeWhere, 
											RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount,  Accountingtype
											from RR_DATA_Revenue
											INNER JOIN COA_CNF_Account		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
											where COA_CNF_Account.coaAccountID = @ACCPaymentMethod
										)p    on p.transactionid = 	data_payment.transactionid

					where data_payment.paymentstatus = 1
					and DATA_Transaction.TransactionType in (select transactionid
																from #TransactionIDs)
					and data_payment.paymentfee &lt;&gt; 0
					and RR_DATA_REVENUE.fcalcdate = @BatchDate
					--and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
					AND data_payment.Transactionid not in (select distinct transactionid
												from rr_Data_Revenue
												where coaaccountid in (select distinct FeeCOAAccountId
																			from cnf_paymentmethod CP
																		)
																			and transactionid is not null
												)
					AND data_payment.Transactionid in (select distinct transactionid
												from rr_Data_Revenue
												where coaaccountid in (@ACCPaymentMethod)
												)


		--	--Normal Transactions Reverse out of PaymentMethods
			INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])				    					
					select COAAccountId, 
						   Max(RevenueRecognitionRuleId),
						   Max(RRCode),		   
						   RRCalcTypeWhere,
						   RRCalcTypeMethod,	   
						   Max(COAAccountConfigId),
						   COAAccountTypeId,
						   COAAccountCode,
						   Transactionid,
						   saleid,
						   Siteid,
						   OperatingAreaId,
						   Workstationid,
						   UserGroupid,
						   UserId,
						   batchdate,
						   TransDate,
						   0,
						   0,
						   0,						
						   0,
						   0,
						   0,
						   ABS(sum(RevenueAmount)) as RevenueAmount,
						   case when accountingtype = 1 then 2
								else 1
							end Accountingtype,		
						   RRCalcTypeTrigger,
						   RRPercentage,
						   RRDays
						   from (
			select distinct rr_data_Revenue.coaaccountid as rrcoaaccountid,
								       p.COAAccountId, 
									   p.RevenueRecognitionRuleId,
									   p.RRCode,		   
									   p.RRCalcTypeWhere,
									   p.RRCalcTypeMethod,	   
									   p.COAAccountConfigId,
									   p.COAAccountTypeId,
									   p.COAAccountCode,
									   rr_data_Revenue.Transactionid Transactionid,
									   rr_data_Revenue.saleid saleid,
									   rr_data_Revenue.Siteid siteid,
									   rr_data_Revenue.OperatingAreaId OperatingAreaid,
									   rr_data_Revenue.Workstationid workstationid,
									   rr_data_Revenue.UserGroupid usergroupid,
									   rr_data_Revenue.UserId userid,
									   @BatchDate batchdate,
									   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
											else DATA_Transaction.transactiondate
									   end as TransDate,
									   rr_data_Revenue.RevenueAmount  as RevenueAmount,
								       p.Accountingtype,
									   transactiontype,		
									   p.RRCalcTypeTrigger,
									   p.RRPercentage,
									   p.RRDays
							FROM rr_data_Revenue   				        WITH (NOLOCK)
								   INNER JOIN (select saleid, transactionid, RevenueRecognitionRuleId, RR_DATA_Revenue.RRCode, RRCalcTypeWhere, Saleitemid, RR_DATA_Revenue.COAAccountId, 
													   RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount, COA_CNF_Account.COAAccountTypeId,  Accountingtype,
													   RR_DATA_Revenue.COAAccountCode
													  from RR_DATA_Revenue
														INNER JOIN COA_CNF_Account		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
													 where COA_CNF_Account.coaAccountID = @ACCPaymentMethod
													-- and rr_data_Revenue.RRCalcTypeTrigger = @Trigger
													)p								ON p.transactionid = 	rr_data_Revenue.transactionid
									INNER JOIN DATA_Transaction			on data_transaction.transactionid = rr_data_revenue.transactionid
							where RR_DATA_REVENUE.fcalcdate = @BatchDate
							  
							  and DATA_Transaction.TransactionType in (select transactionid
																from #TransactionIDs)
							  and rr_data_Revenue.coaaccountid in (select distinct coaaccountid
																	 from cnf_paymentmethod
																	 where coaaccountid is not null
																	union all
																   select distinct coaaccountid
																	 from cnf_paymentcard
																	 where coaaccountid is not null

																  )
						)r	
							group by	 COAAccountId, 		   
									   RRCalcTypeWhere,
									   RRCalcTypeMethod,	   
									   COAAccountTypeId,
									   COAAccountCode,
									   Transactionid,
									   saleid,
									   Siteid,
									   OperatingAreaId,
									   Workstationid,
									   UserGroupid,
									   UserId,
									   batchdate,
									   TransDate,					
									   Accountingtype,		
									   RRCalcTypeTrigger,
									   RRPercentage,
									   RRDays, 
									   TransactionType
							

----Normal Sale Split out the Payments to returned Checks
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])				    
				select distinct COA.COAAccountId, 
						   p.RevenueRecognitionRuleId,
						   p.RRCode,		   
						   p.RRCalcTypeWhere,
						   p.RRCalcTypeMethod,	   
						   p.COAAccountConfigId,
						   COA.COAAccountTypeId,
						   COA.Code,
						   RR_DATA_REVENUE.Transactionid as Transactionid,
						   RR_DATA_REVENUE.saleid as Saleid,
						   RR_DATA_REVENUE.Siteid as SiteID,
						   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
						   RR_DATA_REVENUE.Workstationid as Workstationid,
						   RR_DATA_REVENUE.UserGroupid as UserGroupID,
						   RR_DATA_REVENUE.UserId as userID,
						   @BatchDate,
						   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
							    else DATA_Transaction.transactiondate
						   end as TransDate,
						   0,
						   0,
						   0,
						   0,
						   100,
						   0,  	
						  ABS(data_ledger.entryAmount) as RevenueAmount,
							case when data_ledger.entryAmount &gt;= 0 then 1
								else 2
							end accountingtype,		
							p.RRCalcTypeTrigger,
							p.RRPercentage,
							p.RRDays

						from RR_DATA_REVENUE
						INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
						INNER JOIN data_payment							on data_payment.transactionid = rr_data_revenue.transactionid
						left  JOIN DATA_PaymentCard						on data_paymentcard.paymentid = data_payment.PaymentId
						left JOIN CNF_PaymentCard						on cnf_paymentcard.paymentcardid = data_paymentcard.paymentcardid
						INNER JOIN CNF_PaymentMethod					on CNF_PaymentMethod.PaymentMethodId = data_payment.PaymentMethodId
						INNER JOIN COA_CNF_Account COA					on COA.COAAccountid = CNF_PaymentMethod.returnedcheckcoaaccountid
						INNER JOIN data_ledger							ON data_ledger.transactionid = data_transaction.transactionid
						INNER JOIN cnf_ledgeraccount					ON cnf_ledgeraccount.LedgerAccountId = data_ledger.ledgeraccountid
												INNER JOIN (select transactionid, RevenueRecognitionRuleId, RR_DATA_Revenue.RRCode, RRCalcTypeWhere, 
																	RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount,  Accountingtype
																	from RR_DATA_Revenue
																	INNER JOIN COA_CNF_Account		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
																	where COA_CNF_Account.coaAccountID = @ACCPaymentMethod
																)p    on p.transactionid = 	data_payment.transactionid


						where data_payment.paymentstatus = 1
							and DATA_Transaction.TransactionType in (select transactionid
																from #TransactionIDs)
							and DATA_Transaction.tip &lt;&gt; 0
							and RR_DATA_REVENUE.fcalcdate = @BatchDate
							and systemaccounttable = 119
							and systemaccountid = 15

----Breakage for Fixed Vouchers.   The left over money.
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])				    
					select distinct COA.COAAccountId, 
						   p.RevenueRecognitionRuleId,
						   p.RRCode,		   
						   p.RRCalcTypeWhere,
						   p.RRCalcTypeMethod,	   
						   p.COAAccountConfigId,
						   COA.COAAccountTypeId,
						   COA.Code,
						   RR_DATA_REVENUE.Transactionid as Transactionid,
						   RR_DATA_REVENUE.saleid as Saleid,
						   RR_DATA_REVENUE.Siteid as SiteID,
						   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
						   RR_DATA_REVENUE.Workstationid as Workstationid,
						   RR_DATA_REVENUE.UserGroupid as UserGroupID,
						   RR_DATA_REVENUE.UserId as userID,
						   @BatchDate,
						   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
							    else DATA_Transaction.transactiondate
						   end as TransDate,
						   0,
						   0,
						   0,
						   0,
						   100,
						   0,  	
						  ABS(DATA_Transaction.Tip) as RevenueAmount,
							2 accountingtype,		
							p.RRCalcTypeTrigger,
							p.RRPercentage,
							p.RRDays

						from RR_DATA_REVENUE

							INNER JOIN data_transaction		on data_transaction.transactionid = rr_data_revenue.transactionid
							INNER JOIN DATA_Payment			on data_payment.transactionid = data_transaction.transactionid
							INNER JOIN CNF_PaymentMethod	on cnf_paymentmethod.paymentmethodid = data_payment.paymentmethodid
							INNER JOIN CNF_Driver			on cnf_driver.driverID = cnf_paymentmethod.driverid
							INNER JOIN COA_CNF_Account COA	on COA.COAAccountid = CNF_PaymentMethod.FixedVoucherCOAAccountId


							INNER JOIN (select transactionid, RevenueRecognitionRuleId, RR_DATA_Revenue.RRCode, RRCalcTypeWhere, 
																	RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount,  Accountingtype
																	from RR_DATA_Revenue
																	INNER JOIN COA_CNF_Account		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
																	where COA_CNF_Account.coaAccountID = @ACCPaymentMethod
																)p    on p.transactionid = 	data_payment.transactionid


						where data_payment.paymentstatus = 1
						  and TransactionType in (select transactionid
														from #TransactionIDs)
							and DATA_Transaction.tip &lt;&gt; 0
							and RR_DATA_REVENUE.fcalcdate = @BatchDate


				--Normal Transaction break out Tax
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])				    
						  select COAAccountId, 
						   MIN(p.RevenueRecognitionRuleId),
						   MIN(p.RRCode),		   
						   RRCalcTypeWhere,
						   RRCalcTypeMethod,	   
						   COAAccountConfigId,
						   COAAccountTypeId,
						   COACODE,
						   Transactionid,
						   saleid,
						   Siteid,
						   OperatingAreaId,
						   Workstationid,
						   UserGroupid,
						   UserId,
						   batchdate,
						   TransDate,
						   0,
						   0,
						   0,						
						   price,
						   percentage,
						   test,
						   ABS(sum(RevenueAmount)) as RevenueAmount,
				           case when TransactionType in (5, 17, 18, 20, 22, 30) and sum(RevenueAmount) &lt;= 0  then 1
						        when TransactionType in (5, 17, 18, 20, 22, 30) and sum(RevenueAmount) &lt;= 0  then 2
								when TransactionType in (7) and sum(RevenueAmount) &lt;= 0  then 1
								when TransactionType in (7) and sum(RevenueAmount) &gt; 0  then 2
								else Accountingtype
							end Accountingtype,		
						   RRCalcTypeTrigger,
						   RRPercentage,
						   RRDays
						   
						   from (
						  select distinct COA.COAAccountId, 
						   min(p.RevenueRecognitionRuleId) RevenueRecognitionRuleId,
						   min(p.rrcode) rrcode,		   
						   RR_DATA_REVENUE.RRCalcTypeWhere,
						   RR_DATA_REVENUE.RRCalcTypeMethod,	   
						   RR_DATA_REVENUE.COAAccountConfigId,
						   COA.COAAccountTypeId,
						   COA.Code COACODE,
						   RR_DATA_REVENUE.Transactionid as Transactionid,
						   RR_DATA_REVENUE.saleid as Saleid,
						   RR_DATA_REVENUE.Siteid as SiteID,
						   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
						   RR_DATA_REVENUE.Workstationid as Workstationid,
						   RR_DATA_REVENUE.UserGroupid as UserGroupID,
						   RR_DATA_REVENUE.UserId as userID,
						   @BatchDate as batchdate,
						   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
							    else DATA_Transaction.transactiondate
						   end as TransDate,
						   0 as Quantity,
						   0 as GrossAmount,
						   0 as NetAmount,
						   0 as price,
						   100 as percentage,
						   0 as test, 	
						   taxamount RevenueAmount,
						   Transactiontype,
							p.Accountingtype,					   		
						   RR_DATA_REVENUE.RRCalcTypeTrigger,
						   RR_DATA_REVENUE.RRPercentage,
						   RR_DATA_REVENUE.RRDays

					from RR_DATA_REVENUE
						INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
						INNER JOIN DATA_TransactionTax					on data_transactiontax.transactionid = data_transaction.transactionid
						INNER JOIN CNF_Tax								on cnf_tax.taxid = DATA_TransactionTax.taxid
						INNER JOIN coa_cnf_account coa					on coa.coaaccountid = cnf_tax.coaaccountid
							INNER JOIN (select saleid, transactionid, RevenueRecognitionRuleId, RR_DATA_Revenue.RRCode, RRCalcTypeWhere, Saleitemid, RR_DATA_Revenue.coaaccountid,
												RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount,  Accountingtype
												from RR_DATA_Revenue
												INNER JOIN COA_CNF_Account		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
												where COA_CNF_Account.coaAccountID = @TaxAccountID
												--and rr_data_Revenue.RRCalcTypeTrigger = @Trigger
												and RR_DATA_REVENUE.fcalcdate = @BatchDate
											)p    on p.transactionid = 	data_transactiontax.transactionid
					where RR_DATA_REVENUE.coaaccountid = 1
					and RR_DATA_REVENUE.fcalcdate = @BatchDate
					and TransactionType in (select transactionid
														from #TransactionIDs)
					AND DATA_Transaction.Transactionid not in (select distinct transactionid
																	from rr_Data_Revenue
																	where coaaccountid in (select distinct coaaccountid
																								from cnf_tax 
																							)
																	)
					group by COA.COAAccountId,    
						   RR_DATA_REVENUE.RRCalcTypeWhere,
						   RR_DATA_REVENUE.RRCalcTypeMethod,	   
						   RR_DATA_REVENUE.COAAccountConfigId,
						   COA.COAAccountTypeId,
						   COA.Code,
						   RR_DATA_REVENUE.Transactionid,
						   RR_DATA_REVENUE.saleid,
						   RR_DATA_REVENUE.Siteid,
						   RR_DATA_REVENUE.OperatingAreaId,
						   RR_DATA_REVENUE.Workstationid,
						   RR_DATA_REVENUE.UserGroupid,
						   RR_DATA_REVENUE.UserId,
						   DATA_Transaction.ftransactiondate, 
						   DATA_Transaction.transactiondate,
						   taxamount,
						   Transactiontype,
							p.Accountingtype,					   		
						   RR_DATA_REVENUE.RRCalcTypeTrigger,
						   RR_DATA_REVENUE.RRPercentage,
						   RR_DATA_REVENUE.RRDays

					)p
					where revenueamount &lt;&gt; 0
					group by COAAccountId, 	   
							RRCalcTypeWhere,
							RRCalcTypeMethod,	   
							COAAccountConfigId,
							COAAccountTypeId,
							COACODE,
							Transactionid,
							saleid,
							Siteid,
							OperatingAreaId,
							Workstationid,
							UserGroupid,
							UserId,
							TransDate,
							Accountingtype,		
							RRCalcTypeTrigger,
							RRPercentage,
							RRDays,
							price,
							percentage,
							test,
							batchdate,
							TransactionType


																									
		--	--------Reverse Tax Out
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])	
				      select  COAAccountId, 
									   RevenueRecognitionRuleId,
									   RRCode,		   
									   RRCalcTypeWhere,
									   RRCalcTypeMethod,	   
									   COAAccountConfigId,
									   COAAccountTypeId,
									   COAAccountCode,
									   Transactionid,
									   saleid,
									   siteid,
									   OperatingAreaid,
									   workstationid,
									   usergroupid,
									   userid,
									   batchdate,
									   TransDate,
									   Quantity,
									   grossamount,
									   netamount,
									   price,
									   percentage,
									   tax,
									   ABS(sum(RevenueAmount))  as RevenueAmount,
									    case when p.accountingtype = 1 then 2
											else 1
										end Accountingtype,	
									   RRCalcTypeTrigger,
									   RRPercentage,
									   RRDays
					  from (		    
				             select distinct 
								       p.COAAccountId, 
									   p.RevenueRecognitionRuleId,
									   p.RRCode,		   
									   p.RRCalcTypeWhere,
									   p.RRCalcTypeMethod,	   
									   p.COAAccountConfigId,
									   p.COAAccountTypeId,
									   p.COAAccountCode,
									   rr_data_Revenue.Transactionid Transactionid,
									   rr_data_Revenue.saleid saleid,
									   rr_data_Revenue.Siteid siteid,
									   rr_data_Revenue.OperatingAreaId OperatingAreaid,
									   rr_data_Revenue.Workstationid workstationid,
									   rr_data_Revenue.UserGroupid usergroupid,
									   rr_data_Revenue.UserId userid,
									   @BatchDate batchdate,
									   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
											else DATA_Transaction.transactiondate
									   end as TransDate,
									   rr_data_Revenue.Quantity Quantity,
									   rr_data_Revenue.GrossAmount grossamount,
									   rr_data_Revenue.NetAmount netamount,
									   0 price,
									   100 percentage,
									   0 tax,
									   rr_data_Revenue.RevenueAmount  as RevenueAmount,
									   data_transaction.transactiontype,
								       p.Accountingtype,		
									   p.RRCalcTypeTrigger,
									   p.RRPercentage,
									   p.RRDays
							FROM rr_data_Revenue   				        WITH (NOLOCK)
								   INNER JOIN (select saleid, transactionid, RevenueRecognitionRuleId, RR_DATA_Revenue.RRCode, RRCalcTypeWhere, Saleitemid, RR_DATA_Revenue.COAAccountId, 
													   RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount, COA_CNF_Account.COAAccountTypeId,  Accountingtype,
													   RR_DATA_Revenue.COAAccountCode
													  from RR_DATA_Revenue
														INNER JOIN COA_CNF_Account		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
													 where COA_CNF_Account.coaAccountID = @TaxAccountID
													)p								ON p.Transactionid = 	rr_data_Revenue.Transactionid
									INNER JOIN data_transaction						on data_transaction.transactionid = rr_data_revenue.transactionid

							where RR_DATA_REVENUE.fcalcdate = @BatchDate
							  and rr_data_Revenue.RRCalcTypeTrigger = @Trigger
							  and DATA_Transaction.TransactionType in (select transactionid
																		from #TransactionIDs)
							  and rr_data_Revenue.coaaccountid in (select distinct coaaccountid
						                                             from cnf_tax
																    where coaaccountid is not null
															      )
							)p
							group by   COAAccountId, 
									   RevenueRecognitionRuleId,
									   RRCode,		   
									   RRCalcTypeWhere,
									   RRCalcTypeMethod,	   
									   COAAccountConfigId,
									   COAAccountTypeId,
									   COAAccountCode,
									   Transactionid,
									   saleid,
									   siteid,
									   OperatingAreaid,
									   workstationid,
									   usergroupid,
									   userid,
									   batchdate,
									   TransDate,
									   Quantity,
									   grossamount,
									   netamount,
									   price,
									   percentage,
									   tax,
								       Accountingtype,		
									   RRCalcTypeTrigger,
									   RRPercentage,
									   RRDays,
									   TransactionType


		------		--Normal Transaction Break out the discounts
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[saleitemid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])
				   select COAAccountId, 
						   RevenueRecognitionRuleId,
						   RRCode,		   
						   RRCalcTypeWhere,
						   RRCalcTypeMethod,	   
						   COAAccountConfigId,
						   COAAccountTypeId,
						   Code,
						   Transactionid,
						   Saleid,
						   Saleitemid,
						   SiteID,
						   OperatingAreaID,
						   Workstationid,
						   UserGroupID,
						   userID,
						   batchdate,
						   TransDate,
						   quantity,
						   grossamount,
						   netamount,
						   price,
						   percentage,
						   remaningValues, 	
						   RevenueAmount,
						   Accountingtype,		
						   RRCalcTypeTrigger,
						   RRPercentage,
						   RRDays
				   from (				    
						select distinct 
						   COA.COAAccountId, 
						   RR_DATA_REVENUE.RevenueRecognitionRuleId,
						   RR_DATA_REVENUE.RRCode,		   
						   RR_DATA_REVENUE.RRCalcTypeWhere,
						   RR_DATA_REVENUE.RRCalcTypeMethod,	   
						   RR_DATA_REVENUE.COAAccountConfigId,
						   COA.COAAccountTypeId,
						   COA.Code,
						   RR_DATA_REVENUE.Transactionid as Transactionid,
						   RR_DATA_REVENUE.saleid as Saleid,
						   RR_DATA_REVENUE.saleitemid as saleitemid,
						   RR_DATA_REVENUE.Siteid as SiteID,
						   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
						   RR_DATA_REVENUE.Workstationid as Workstationid,
						   RR_DATA_REVENUE.UserGroupid as UserGroupID,
						   RR_DATA_REVENUE.UserId as userID,
						   @BatchDate as batchdate,
						   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
							    else DATA_Transaction.transactiondate
						   end as TransDate,
						   0 as quantity,
						   0 as grossamount,
						   0 as netamount,
						   0 as price,
						   100 as percentage,
						   0 as remaningValues, 	
						   abs(DATA_SaleItemRule.discountamount)
							as RevenueAmount,
						   p.Accountingtype,		
						   RR_DATA_REVENUE.RRCalcTypeTrigger,
						   RR_DATA_REVENUE.RRPercentage,
						   RR_DATA_REVENUE.RRDays,
						   DATA_SaleItemRule.SaleItemRuleId


					from RR_DATA_REVENUE
						--inner join rr_cnf_Product						ON ((RR_DATA_REVENUE.MATRIXCELLID = rr_cnf_Product.MATRIXCELLID) or (RR_DATA_REVENUE.MatrixSheetId = rr_cnf_Product.MatrixSheetId)) and rr_cnf_Product.Enabled = 1
						--inner join RR_CNF_RevenueRecognitionRule		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_cnf_Product.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  
						--INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
						--INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
						--INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 
						INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
						LEFT  JOIN DATA_Sale				            ON DATA_Sale.SaleID = data_transaction.SaleID
						LEFT  JOIN DATA_SaleItem			            ON DATA_SaleItem.saleitemid = RR_DATA_REVENUE.saleitemid
						LEFT JOIN DATA_SaleItemRule						ON data_saleitemrule.saleitemid = DATA_SaleItem.saleitemid	 
						LEFT JOIN CNF_PromotionItemRule					ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
						LEFT JOIN CNF_PromotionItem						ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
						LEFT JOIN CNF_Promotion							ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId	
						LEFT JOIN COA_CNF_Account	COA			        ON COA.coaaccountid = CNF_Promotion.coaaccountid
						
						
						INNER JOIN (select transactionid, RevenueRecognitionRuleId, RR_DATA_Revenue.RRCode, RRCalcTypeWhere, saleitemid,
											RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount,  Accountingtype
											from RR_DATA_Revenue
											INNER JOIN COA_CNF_Account		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
											where COA_CNF_Account.coaAccountID = @DiscountAccountID
										)p    on p.transactionid = 	DATA_Transaction.transactionid and p.saleitemid = rr_data_revenue.saleitemid



					where RR_DATA_REVENUE.coaaccountid = 1
					and DATA_Transaction.TransactionType in (select transactionid
																from #TransactionIDs)
					and RR_DATA_REVENUE.fcalcdate = @BatchDate
					--and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
					AND DATA_Transaction.Transactionid not in (select distinct transactionid
																	from rr_Data_Revenue
																	where coaaccountid in (select distinct coaaccountid
																								from CNF_Promotion
																								where coaaccountid is not null 
																							)
																	)	
					)p
					where revenueamount &lt;&gt; 0	
					  and coaaccountid is not null													
																																								
		--		--Reverse out Discounts														
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])	
				   select COAAccountId, 
						   RevenueRecognitionRuleId,
						   RRCode,		   
						   RRCalcTypeWhere,
						   RRCalcTypeMethod,	   
						   COAAccountConfigId,
						   COAAccountTypeId,
						   COAAccountCode,
						   Transactionid,
						   Saleid,
						   SiteID,
						   OperatingAreaID,
						   Workstationid,
						   UserGroupID,
						   userID,
						   batchdate,
						   TransDate,
						   quantity,
						   grossamount,
						   netamount,
						   price,
						   percentage,
						   remaningValues, 	
						   sum(RevenueAmount),
						   Accountingtype,		
						   RRCalcTypeTrigger,
						   RRPercentage,
						   RRDays
				   from (		    
				select distinct 				           
				           p.RevenueRecognitionDataId,
                           p.COAAccountId, 
						   p.RevenueRecognitionRuleId,
						   p.RRCode,		   
						   p.RRCalcTypeWhere,
						   p.RRCalcTypeMethod,	   
						   p.COAAccountConfigId,
						   p.COAAccountTypeId,
						   p.COAAccountCode,
						   rr_data_Revenue.Transactionid,
						   rr_data_Revenue.saleid,
						   rr_data_Revenue.saleitemid,
						   rr_data_Revenue.Siteid,
						   rr_data_Revenue.OperatingAreaId,
						   rr_data_Revenue.Workstationid,
						   rr_data_Revenue.UserGroupid,
						   rr_data_Revenue.UserId,
						   @BatchDate batchdate,
						   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
							    else DATA_Transaction.transactiondate
						   end as TransDate,
							0 as quantity,
						   0 as grossamount,
						   0 as netamount,
						   0 as price,
						   100 as percentage,
						   0 as remaningValues,
						   rr_data_Revenue.RevenueAmount  as RevenueAmount,
						   case when p.accountingtype = 1 then 2
					        else 1
						   end Accountingtype,
						   p.RRCalcTypeTrigger,
						   p.RRPercentage,
						   p.RRDays

						  FROM rr_data_Revenue   				        WITH (NOLOCK)
								   INNER JOIN (select saleid, transactionid, RevenueRecognitionRuleId, RR_DATA_Revenue.RRCode, RRCalcTypeWhere, Saleitemid, RR_DATA_Revenue.COAAccountId, 
													   RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount, COA_CNF_Account.COAAccountTypeId,  Accountingtype,
													   RR_DATA_Revenue.COAAccountCode, rr_data_Revenue.RevenueRecognitionDataId
													  from RR_DATA_Revenue
														INNER JOIN COA_CNF_Account		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
													 where COA_CNF_Account.coaAccountID = @DiscountAccountID
													)p								ON p.saleid = 	rr_data_Revenue.saleid  and p.saleitemid = rr_data_revenue.saleitemid
								INNER JOIN data_transaction        on data_transaction.transactionid = rr_data_revenue.transactionid

						where  rr_data_Revenue.coaaccountid in (select distinct coaaccountid
						                                         from CNF_Promotion
															  )
						 and RR_DATA_REVENUE.fcalcdate = @BatchDate
						 and DATA_Transaction.TransactionType in (select transactionid
															from #TransactionIDs)
						)p		
						
						group by  COAAccountId, 
						   RevenueRecognitionRuleId,
						   RRCode,		   
						   RRCalcTypeWhere,
						   RRCalcTypeMethod,	   
						   COAAccountConfigId,
						   COAAccountTypeId,
						   COAAccountCode,
						   Transactionid,
						   Saleid,
						   SiteID,
						   OperatingAreaID,
						   Workstationid,
						   UserGroupID,
						   userID,
						   batchdate,
						   TransDate,
						   quantity,
						   grossamount,
						   netamount,
						   price,
						   percentage,
						   remaningValues, 	
						   Accountingtype,		
						   RRCalcTypeTrigger,
						   RRPercentage,
						   RRDays																																																																																			

		
		End</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_RR_RevenueData_OnMoneyCardLoad]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_RR_RevenueData_OnMoneyCardLoad</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>CREATE Procedure dbo.otn_sp_RR_RevenueData_OnMoneyCardLoad
	@BatchDate Date,
	@RRTransDateType Integer
AS 
BEGIN
	
	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer
	Declare @OnMoneyCardCashOut Integer = 10

	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1


		BEGIN

			--Normal Transaction No Remaining Values
			INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[Saleitemid]
				   ,[MatrixCellid]
				   ,[MatrixCellCode]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays]
				   ,[AttributeIDs])
				   select *
				   from(
						select distinct coa_cnf_account.COAAccountId, 
								   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
								   RR_CNF_RevenueRecognitionRule.code,		   
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
								   COA_CNF_AccountConfig.COAAccountConfigId,
								   coa_cnf_account.COAAccountTypeId,
								   coa_cnf_account.Code as AccountCode,
								   RR_DATA_REVENUE.Transactionid as Transactionid,
								   RR_DATA_REVENUE.saleid as Saleid,
								   RR_DATA_REVENUE.SaleitemID as SaleitemID,
								   RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								   RR_DATA_REVENUE.MatrixcellCode as MatrixCode,
								   RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								   RR_DATA_REVENUE.Siteid as SiteID,
								   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								   RR_DATA_REVENUE.Workstationid as Workstationid,
								   RR_DATA_REVENUE.UserGroupid as UserGroupID,
								   RR_DATA_REVENUE.UserId as userID,
								   @BatchDate as BatchDate,
								   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
								        else DATA_Transaction.transactiondate
								   end as TransDate,
								   RR_DATA_REVENUE.Quantity as Quantity,
								   RR_DATA_REVENUE.GrossAmount as GrossAmount,
								   RR_DATA_REVENUE.NetAmount as NetAmount,
								   COA_CNF_AccountConfig.Price as ConfigPrice,
								   COA_CNF_AccountConfig.Percentage as ConfigPercentage,
								   COA_CNF_AccountConfig.RemainingValues,																		
									Case when COA_CNF_AccountConfig.Price &gt; 0 then (COA_CNF_AccountConfig.Price * RR_DATA_REVENUE.Quantity) 
										 else (ISNULL(((ABS((select (unitrecharge * Quantity)
															   from data_saleitem
															  where saleitemid = RR_DATA_REVENUE.saleitemid
										))) * COA_CNF_AccountConfig.Percentage/100), 0))																		                                                                                                                                                                                              
									end  as RevenueAmount,

								   case when TransactionType in (5, 17, 18, 20, 22, 30) and COA_CNF_AccountConfig.Accountingtype = 1 then 2
								        when TransactionType in (5, 17, 18, 20, 22, 30) and COA_CNF_AccountConfig.Accountingtype = 2 then 1
										when TransactionType in (7) and rr_data_revenue.RevenueAmount &lt; 0 and COA_CNF_AccountConfig.Accountingtype = 2 then 1
								        else COA_CNF_AccountConfig.Accountingtype
									end Accountingtype,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
								   RR_CNF_RevenueRecognitionRule.Percentage,
								   RR_CNF_RevenueRecognitionRule.Days,
								   RR_DATA_REVENUE.AttributeIDs

							from RR_DATA_REVENUE
									inner join rr_cnf_Product						ON ((RR_DATA_REVENUE.MATRIXCELLID = rr_cnf_Product.MATRIXCELLID) 
                                                      or (RR_DATA_REVENUE.MatrixSheetId = rr_cnf_Product.MatrixSheetId)
													  or (rr_cnf_product.Attributeid in (select top 1 Attributeid
																							from rr_cnf_product
																							where Attributeid in (select Value
																													from dbo.split((select rr.Attributeids
																																	from rr_data_revenue rr
																																	where rr.revenuerecognitiondataid = RR_DATA_REVENUE.revenuerecognitiondataid), '.')
																												   )
																					    )
															))
													  and rr_cnf_Product.Enabled = 1
									inner join RR_CNF_RevenueRecognitionRule		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_cnf_Product.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  
									INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
									INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
									INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 
									INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid

							where RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger IN (@OnMoneyCardCashOut)

							  and RR_CNF_RevenueRecognitionRule.Enabled = 1
							  and coa_cnf_account.Enabled = 1
							  and COA_CNF_AccountConfig.Enabled = 1
							  and ((TransactionType in (10, 20, 18, 22)) or (RR_DATA_REVENUE.transactionid in (select transactionid
																									 from data_transaction
																										Inner join data_saleitem   on data_saleitem.saleid = data_transaction.saleid
																									where data_transaction.transactiontype in (14)
																									  and data_saleitem.unitrecharge &lt;&gt; 0
																								 )
																))
							  and ((coa_cnf_accountConfig.Siteid = RR_DATA_REVENUE.SiteId) or (coa_cnf_accountConfig.Siteid is null))
							  and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
							  and COA_CNF_AccountConfig.RemainingValues &lt;&gt; 1
							  and RR_DATA_REVENUE.fcalcdate = @BatchDate
							  and RR_DATA_REVENUE.coaaccountid = @suspendid
						
					)p
					where RevenueAmount &lt;&gt; 0

				--Normal Transaction with Remaining Values
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[Saleitemid]
				   ,[MatrixCellid]
				   ,[MatrixCellCode]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays]
				   ,[AttributeIDs])
				   select *
				   from(
						select distinct coa_cnf_account.COAAccountId, 
								   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
								   RR_CNF_RevenueRecognitionRule.code,		   
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
								   COA_CNF_AccountConfig.COAAccountConfigId,
								   coa_cnf_account.COAAccountTypeId,
								   coa_cnf_account.Code as AccountCode,
								   RR_DATA_REVENUE.Transactionid as Transactionid,
								   RR_DATA_REVENUE.saleid as Saleid,
								   RR_DATA_REVENUE.SaleitemID as SaleitemID,
								   RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								   RR_DATA_REVENUE.MatrixcellCode as MatrixCode,
								   RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								   RR_DATA_REVENUE.Siteid as SiteID,
								   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								   RR_DATA_REVENUE.Workstationid as Workstationid,
								   RR_DATA_REVENUE.UserGroupid as UserGroupID,
								   RR_DATA_REVENUE.UserId as userID,
								   @BatchDate as BatchDate,
								   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
								        else DATA_Transaction.transactiondate
								   end as TransDate,
								   RR_DATA_REVENUE.Quantity as Quantity,
								   RR_DATA_REVENUE.GrossAmount as GrossAmount,
								   RR_DATA_REVENUE.NetAmount as NetAmount,
								   COA_CNF_AccountConfig.Price as ConfigPrice,
								   COA_CNF_AccountConfig.Percentage as ConfigPercentage,
								   COA_CNF_AccountConfig.RemainingValues,							 
								   ISNULL((RR_DATA_REVENUE.RevenueAmount - (select ISNULL(sum(revenueamount), 0)
								                            from RR_DATA_Revenue rr
												              where rr.saleitemid = RR_DATA_REVENUE.SaleitemID
												        and rr.COAAccountid not in (@SuspendID, @ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)
												 )
									), 0)
									as RevenueAmount,
								   case when TransactionType in (5, 17, 18, 20, 22, 30) and COA_CNF_AccountConfig.Accountingtype = 1 then 2
								        when TransactionType in (5, 17, 18, 20, 22, 30) and COA_CNF_AccountConfig.Accountingtype = 2 then 1
										when TransactionType in (7) and rr_data_revenue.RevenueAmount &lt; 0 and COA_CNF_AccountConfig.Accountingtype = 2 then 1
								        else COA_CNF_AccountConfig.Accountingtype
									end Accountingtype,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
								   RR_CNF_RevenueRecognitionRule.Percentage,
								   RR_CNF_RevenueRecognitionRule.Days,
								   RR_DATA_REVENUE.AttributeIDs

						from RR_DATA_REVENUE
									inner join rr_cnf_Product						ON ((RR_DATA_REVENUE.MATRIXCELLID = rr_cnf_Product.MATRIXCELLID) 
                                                      or (RR_DATA_REVENUE.MatrixSheetId = rr_cnf_Product.MatrixSheetId)
													  or (rr_cnf_product.Attributeid in (select top 1 Attributeid
																							from rr_cnf_product
																							where Attributeid in (select Value
																													from dbo.split((select rr.Attributeids
																																	from rr_data_revenue rr
																																	where rr.revenuerecognitiondataid = RR_DATA_REVENUE.revenuerecognitiondataid), '.')
																												   )
																					    )
															))
													  and rr_cnf_Product.Enabled = 1
								inner join RR_CNF_RevenueRecognitionRule		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_cnf_Product.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  
								INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
								INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
								INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 
								INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid

							where RR_CNF_RevenueRecognitionRule.Enabled = 1
							  and coa_cnf_account.Enabled = 1
							  and COA_CNF_AccountConfig.Enabled = 1
							  and TransactionType in (10, 20, 18, 22)
							  and ((coa_cnf_accountConfig.Siteid = RR_DATA_REVENUE.SiteId) or (coa_cnf_accountConfig.Siteid is null))
							  and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger IN (@OnMoneyCardCashOut)
							  and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
							  and COA_CNF_AccountConfig.RemainingValues = 1
							  and RR_DATA_REVENUE.fcalcdate = @BatchDate
							  and RR_DATA_REVENUE.coaaccountid = @suspendid
					)p
					where RevenueAmount &lt;&gt; 0

		
		exec otn_sp_RR_RevenueData_PaymentMethodTaxDiscounts @BatchDate, '10,', @OnMoneyCardCashOut, @RRTransDateType									

	end

END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_RR_RevenueData_batchJob]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_RR_RevenueData_batchJob</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>CREATE Procedure dbo.otn_sp_RR_RevenueData_batchJob	 
	@FromDate Date,
	@ToDate Date
AS 
BEGIN

	delete from rr_data_revenue
	where fcalcdate between @FromDate and @ToDate

	Declare @BatchDate Date
	Declare @RRTransDateType Integer

	Declare @SuspendRRRId Integer
	Declare @SuspendCOAAccountId Integer
	Declare @SuspendRRRCode varchar(10)
	Declare @SuspendRRCalcTypeTrigger Integer
	Declare @SuspendRRCalcTypeWhere Integer
	Declare @SuspendRRCalcTypeMethod Integer
	Declare @SuspendCOAAccountConfigId Integer
	Declare @SuspendCOAAccountTypeId Integer
	Declare @SuspendCOAAccountCode varchar(10)
	Declare @SuspendPercentage float
	Declare @SuspendDays Integer
	Declare @SuspendPrice float
	Declare @SuspendCOAAccount_Percentage Float
	Declare @SuspendRemainingValues Integer
	Declare @SuspendRRCOAAccountingType Integer
	Declare @SuspendAccountingType Integer

	Declare @PaymentRRRId Integer
	Declare @PaymentCOAAccountId Integer
	Declare @PaymentRRRCode varchar(10)
	Declare @PaymentRRCalcTypeTrigger Integer
	Declare @PaymentRRCalcTypeWhere Integer
	Declare @PaymentRRCalcTypeMethod Integer
	Declare @PaymentCOAAccountConfigId Integer
	Declare @PaymentCOAAccountTypeId Integer
	Declare @PaymentCOAAccountCode varchar(10)
	Declare @PaymentPercentage float
	Declare @PaymentDays Integer
	Declare @PaymentPrice float
	Declare @PaymentCOAAccount_Percentage Float
	Declare @PaymentRemainingValues Integer
	Declare @PaymentRRCOAAccountingType Integer
	Declare @PaymentAccountingType Integer


	Declare @TaxRRRId Integer
	Declare @TaxCOAAccountId Integer
	Declare @TaxRRRCode varchar(10)
	Declare @TaxRRCalcTypeTrigger Integer
	Declare @TaxRRCalcTypeWhere Integer
	Declare @TaxRRCalcTypeMethod Integer
	Declare @TaxCOAAccountConfigId Integer
	Declare @TaxCOAAccountTypeId Integer
	Declare @TaxCOAAccountCode varchar(10)
	Declare @TaxPercentage float
	Declare @TaxDays Integer
	Declare @TaxPrice float
	Declare @TaxCOAAccount_Percentage Float
	Declare @TaxRemainingValues Integer
	Declare @TaxRRCOAAccountingType Integer
	Declare @TaxAccountingType Integer


	Declare @DiscountRRRId Integer
	Declare @DiscountCOAAccountId Integer
	Declare @DiscountRRRCode varchar(10)
	Declare @DiscountRRCalcTypeTrigger Integer
	Declare @DiscountRRCalcTypeWhere Integer
	Declare @DiscountRRCalcTypeMethod Integer
	Declare @DiscountCOAAccountConfigId Integer
	Declare @DiscountCOAAccountTypeId Integer
	Declare @DiscountCOAAccountCode varchar(10)
	Declare @DiscountPercentage float
	Declare @DiscountDays Integer
	Declare @DiscountPrice float
	Declare @DiscountCOAAccount_Percentage Float
	Declare @DiscountRemainingValues Integer
	Declare @DiscountRRCOAAccountingType Integer
	Declare @DiscountAccountingType Integer

	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer

	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1


	select @RRTransDateType = RRTransDateType
      from cnf_system

--Begin Move Transactions to Suspend Account
	select TOP 1 @SuspendRRRId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
			@SuspendRRRCode = RR_CNF_RevenueRecognitionRule.code,
			@SuspendRRCalcTypeTrigger = RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
			@SuspendRRCalcTypeWhere = RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
			@SuspendRRCalcTypeMethod = RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
			@SuspendCOAAccountConfigId = COA_CNF_AccountConfig.COAAccountConfigId,
			@SuspendCOAAccountTypeId = COA_CNF_AccountType.COAAccountTypeId,
			@SuspendCOAAccountId = coa_cnf_account.COAAccountId,
			@SuspendPercentage = RR_CNF_RevenueRecognitionRule.Percentage,
			@SuspendDays = RR_CNF_RevenueRecognitionRule.Days,
			@SuspendPrice = COA_CNF_AccountConfig.Price,
			@SuspendCOAAccount_Percentage = COA_CNF_AccountConfig.Percentage,
			@SuspendRemainingValues = COA_CNF_AccountConfig.RemainingValues,
			@SuspendCOAAccountCode = coa_cnf_account.Code,
			@SuspendRRCOAAccountingType = COA_CNF_AccountConfig.AccountingType
	from coa_cnf_account
		INNER JOIN COA_CNF_AccountType				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
		INNER JOIN COA_CNF_AccountConfig			on COA_CNF_AccountConfig.COAAccountId = coa_cnf_account.COAAccountId
		INNER JOIN RR_CNF_RevenueRecognitionRule	on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId
	where coa_cnf_account.COAAccountID = @SuspendID
	 order by RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId

	select TOP 1 @PaymentRRRId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
			@PaymentRRRCode = RR_CNF_RevenueRecognitionRule.code,
			@PaymentRRCalcTypeTrigger = RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
			@PaymentRRCalcTypeWhere = RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
			@PaymentRRCalcTypeMethod = RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
			@PaymentCOAAccountConfigId = COA_CNF_AccountConfig.COAAccountConfigId,
			@PaymentCOAAccountTypeId = COA_CNF_AccountType.COAAccountTypeId,
			@PaymentCOAAccountId = coa_cnf_account.COAAccountId,
			@PaymentPercentage = RR_CNF_RevenueRecognitionRule.Percentage,
			@PaymentDays = RR_CNF_RevenueRecognitionRule.Days,
			@PaymentPrice = COA_CNF_AccountConfig.Price,
			@PaymentCOAAccount_Percentage = COA_CNF_AccountConfig.Percentage,
			@PaymentRemainingValues = COA_CNF_AccountConfig.RemainingValues,
			@PaymentCOAAccountCode = coa_cnf_account.Code,
			@PaymentRRCOAAccountingType = COA_CNF_AccountConfig.AccountingType
	from coa_cnf_account
		INNER JOIN COA_CNF_AccountType				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
		INNER JOIN COA_CNF_AccountConfig			on COA_CNF_AccountConfig.COAAccountId = coa_cnf_account.COAAccountId
		INNER JOIN RR_CNF_RevenueRecognitionRule	on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId
	where coa_cnf_account.COAAccountID = @ACCPaymentMethod
	 order by RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId

	select TOP 1 @TaxRRRId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
			@TaxRRRCode = RR_CNF_RevenueRecognitionRule.code,
			@TaxRRCalcTypeTrigger = RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
			@TaxRRCalcTypeWhere = RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
			@TaxRRCalcTypeMethod = RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
			@TaxCOAAccountConfigId = COA_CNF_AccountConfig.COAAccountConfigId,
			@TaxCOAAccountTypeId = COA_CNF_AccountType.COAAccountTypeId,
			@TaxCOAAccountId = coa_cnf_account.COAAccountId,
			@TaxPercentage = RR_CNF_RevenueRecognitionRule.Percentage,
			@TaxDays = RR_CNF_RevenueRecognitionRule.Days,
			@TaxPrice = COA_CNF_AccountConfig.Price,
			@TaxCOAAccount_Percentage = COA_CNF_AccountConfig.Percentage,
			@TaxRemainingValues = COA_CNF_AccountConfig.RemainingValues,
			@TaxCOAAccountCode = coa_cnf_account.Code,
			@TaxRRCOAAccountingType = COA_CNF_AccountConfig.AccountingType
	from coa_cnf_account
		INNER JOIN COA_CNF_AccountType				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
		INNER JOIN COA_CNF_AccountConfig			on COA_CNF_AccountConfig.COAAccountId = coa_cnf_account.COAAccountId
		INNER JOIN RR_CNF_RevenueRecognitionRule	on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId
	where coa_cnf_account.COAAccountID = @TaxAccountID
	 order by RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId

	select TOP 1 @DiscountRRRId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
			@DiscountRRRCode = RR_CNF_RevenueRecognitionRule.code,
			@DiscountRRCalcTypeTrigger = RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
			@DiscountRRCalcTypeWhere = RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
			@DiscountRRCalcTypeMethod = RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
			@DiscountCOAAccountConfigId = COA_CNF_AccountConfig.COAAccountConfigId,
			@DiscountCOAAccountTypeId = COA_CNF_AccountType.COAAccountTypeId,
			@DiscountCOAAccountId = coa_cnf_account.COAAccountId,
			@DiscountPercentage = RR_CNF_RevenueRecognitionRule.Percentage,
			@DiscountDays = RR_CNF_RevenueRecognitionRule.Days,
			@DiscountPrice = COA_CNF_AccountConfig.Price,
			@DiscountCOAAccount_Percentage = COA_CNF_AccountConfig.Percentage,
			@DiscountRemainingValues = COA_CNF_AccountConfig.RemainingValues,
			@DiscountCOAAccountCode = coa_cnf_account.Code,
			@DiscountRRCOAAccountingType = COA_CNF_AccountConfig.AccountingType
	from coa_cnf_account
		INNER JOIN COA_CNF_AccountType				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
		INNER JOIN COA_CNF_AccountConfig			on COA_CNF_AccountConfig.COAAccountId = coa_cnf_account.COAAccountId
		INNER JOIN RR_CNF_RevenueRecognitionRule	on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId
	where coa_cnf_account.COAAccountID = @DiscountAccountID
	 order by RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId

	Declare @Temp table (BatchDate date)

	;with dates_CTE (date) as (
			select @FromDate 
		Union ALL
			select DATEADD(day, 1, date)
			from dates_CTE
			where date &lt; @ToDate
	) 
	INSERT INTO @Temp (
	BatchDate
	) 
	select *
	from dates_CTE 

	DECLARE date_Cursor CURSOR LOCAL FOR
				select * from @Temp

	OPEN date_Cursor

	FETCH NEXT FROM date_Cursor INTO
		@BatchDate

	WHILE @@FETCH_STATUS = 0
	BEGIN

				INSERT INTO [dbo].[RR_DATA_Revenue]
								([COAAccountId]
								,[RevenueRecognitionRuleId]
								,[RRCode]
								,[RRCalcTypeWhere]
								,[RRCalcTypeMethod]
								,[COAAccountConfigId]
								,[COAAccountType]
								,[COAAccountCode]
								,[TransactionId]
								,[SaleId]
								,[SaleItemId]
								,[MatrixCellId]
								,[MatrixCellCode]
								,[MatrixSheetID]
								,[SiteId]
								,[OperatingAreaId]
								,[WorkstationId]
								,[UserGroupId]
								,[UserId]
								,[FCalcDate]
								,[FRevenueDate]
								,[Quantity]
								,[UnitAmount]
								,[GrossAmount]
								,[NetAmount]
								,[Price]
								,[Percentage]
								,[RemaningValues]
								,[RevenueAmount]
								,[AccountingType]
								,[RRCalcTypeTrigger]
								,[RRPercentage]
								,[RRDays]
								,[AttributeIDS])
						select @SuspendCOAAccountId,
								@SuspendRRRId,
								@SuspendRRRCode,
								@SuspendRRCalcTypeWhere,
								@SuspendRRCalcTypeMethod,
								@SuspendCOAAccountConfigId,
								@SuspendCOAAccountTypeId,
								@SuspendCOAAccountCode,
								data_transaction.transactionid, 
								data_transaction.saleid,
								DATA_TransactionItem.saleitemid,
								DATA_SaleItem.Matrixcellid,
								CNF_MatrixCell.Code,
								CNF_MatrixCell.MatrixSheetid,
								data_transaction.Siteid,
								data_transaction.OperatingAreaId,
								data_transaction.Workstationid,
								data_transaction.UserGroupid,
								data_transaction.UserId,
								@BatchDate,
								CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
									 else data_transaction.TransactionDate
								end TransactionDate,
								Coalesce(DATA_TransactionItem.Quantity, 1),
								DATA_SaleItem.UnitPrice,
								case when isnull(DATA_TransactionItem.TotalAmount, 0) &lt;&gt; 0 then DATA_TransactionItem.TotalAmount
									when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
									else DATA_Sale.TotalAmount
								end,
								case when isnull((DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes)
									when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
									else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
								end as NetAmount,
								@SuspendPrice,
								@SuspendCOAAccount_Percentage,
								@SuspendRemainingValues,
								case    when (data_saleitem.ProductTaxType &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice ) * DATA_SaleItem.Quantity)
										when (data_saleitem.ProductTaxType = 1) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice - DATA_SaleItem.unittaxes) * DATA_SaleItem.Quantity)
										when (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 then 0				
										when isnull((data_transaction.TotalAmount), 0) &lt;&gt; 0 then data_transaction.TotalAmount
										when isnull((DATA_Sale.TotalAmount), 0) &lt;&gt; 0 then DATA_Sale.TotalAmount
										else (data_transaction.Revenue)
								end,
								case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
										when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
										when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 1
										when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 2
										else @SuspendRRCOAAccountingType
								end Accountingtype,
								@SuspendRRCalcTypeTrigger,
								@SuspendPercentage,
								@SuspendDays,
								CNF_AttributeSet.Attributeids
	   
						from DATA_Sale
							inner join data_transaction			on data_transaction.TransactionId = DATA_Sale.PaidTransactionId
							left join DATA_TransactionItem		on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
							left join DATA_SaleItem			    on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
							left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
							left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

						where DATA_Sale.Paid = 1
							and data_transaction.transactiontype in (14)
							and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
							   OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
							and data_transaction.transactionid in (select transactionid
																	from data_payment
																	where PaymentStatus = 1
																	and PaymentAmount &lt;&gt; 0
																)

				INSERT INTO [dbo].[RR_DATA_Revenue]
								([COAAccountId]
								,[RevenueRecognitionRuleId]
								,[RRCode]
								,[RRCalcTypeWhere]
								,[RRCalcTypeMethod]
								,[COAAccountConfigId]
								,[COAAccountType]
								,[COAAccountCode]
								,[TransactionId]
								,[SaleId]
								,[SaleItemId]
								,[MatrixCellId]
								,[MatrixCellCode]
								,[MatrixSheetID]
								,[SiteId]
								,[OperatingAreaId]
								,[WorkstationId]
								,[UserGroupId]
								,[UserId]
								,[FCalcDate]
								,[FRevenueDate]
								,[Quantity]
								,[UnitAmount]
								,[GrossAmount]
								,[NetAmount]
								,[Price]
								,[Percentage]
								,[RemaningValues]
								,[RevenueAmount]
								,[AccountingType]
								,[RRCalcTypeTrigger]
								,[RRPercentage]
								,[RRDays]
								,[AttributeIDS])
						select @SuspendCOAAccountId,
								@SuspendRRRId,
								@SuspendRRRCode,
								@SuspendRRCalcTypeWhere,
								@SuspendRRCalcTypeMethod,
								@SuspendCOAAccountConfigId,
								@SuspendCOAAccountTypeId,
								@SuspendCOAAccountCode,
								data_transaction.transactionid, 
								data_transaction.saleid,
								DATA_TransactionItem.saleitemid,
								DATA_SaleItem.Matrixcellid,
								CNF_MatrixCell.Code,
								CNF_MatrixCell.MatrixSheetid,
								data_transaction.Siteid,
								data_transaction.OperatingAreaId,
								data_transaction.Workstationid,
								data_transaction.UserGroupid,
								data_transaction.UserId,
								@BatchDate,
								CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
									 else data_transaction.TransactionDate
								end TransactionDate,
								Coalesce(DATA_TransactionItem.Quantity, 1),
								DATA_SaleItem.UnitPrice,
								case when isnull(DATA_TransactionItem.TotalAmount, 0) &lt;&gt; 0 then DATA_TransactionItem.TotalAmount
									when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
									else DATA_Sale.TotalAmount
								end,
								case when isnull((DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes)
									when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
									else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
								end as NetAmount,
								@SuspendPrice,
								@SuspendCOAAccount_Percentage,
								@SuspendRemainingValues,
								DATA_SaleItem.UnitRecharge * data_saleitem.Quantity,
								case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
										when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
										when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 1
										when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 2
										else @SuspendRRCOAAccountingType
								end Accountingtype,
								@SuspendRRCalcTypeTrigger,
								@SuspendPercentage,
								@SuspendDays,
								CNF_AttributeSet.Attributeids
	   
						from DATA_Sale
							inner join data_transaction			on data_transaction.TransactionId = DATA_Sale.PaidTransactionId
							left join DATA_TransactionItem		on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
							left join DATA_SaleItem			    on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
							left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
							left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

		where DATA_Sale.Paid = 1
			and data_transaction.transactiontype in (14, 16, 39)
			and DATA_SaleItem.UnitRecharge &lt;&gt; 0
			and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
			   OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
			and data_transaction.transactionid in (select transactionid
													from data_payment
													where PaymentStatus = 1
													and PaymentAmount &lt;&gt; 0
												)

					INSERT INTO [dbo].[RR_DATA_Revenue]
								([COAAccountId]
								,[RevenueRecognitionRuleId]
								,[RRCode]
								,[RRCalcTypeWhere]
								,[RRCalcTypeMethod]
								,[COAAccountConfigId]
								,[COAAccountType]
								,[COAAccountCode]
								,[TransactionId]
								,[SaleId]
								,[SaleItemId]
								,[MatrixCellId]
								,[MatrixCellCode]
								,[MatrixSheetID]
								,[SiteId]
								,[OperatingAreaId]
								,[WorkstationId]
								,[UserGroupId]
								,[UserId]
								,[FCalcDate]
								,[FRevenueDate]
								,[Quantity]
								,[UnitAmount]
								,[GrossAmount]
								,[NetAmount]
								,[Price]
								,[Percentage]
								,[RemaningValues]
								,[RevenueAmount]
								,[AccountingType]
								,[RRCalcTypeTrigger]
								,[RRPercentage]
								,[RRDays]
								,[AttributeIDS])
						select @SuspendCOAAccountId,
								@SuspendRRRId,
								@SuspendRRRCode,
								@SuspendRRCalcTypeWhere,
								@SuspendRRCalcTypeMethod,
								@SuspendCOAAccountConfigId,
								@SuspendCOAAccountTypeId,
								@SuspendCOAAccountCode,
								data_transaction.transactionid, 
								data_transaction.saleid,
								DATA_TransactionItem.saleitemid,
								DATA_SaleItem.Matrixcellid,
								CNF_MatrixCell.Code,
								CNF_MatrixCell.MatrixSheetid,
								data_transaction.Siteid,
								data_transaction.OperatingAreaId,
								data_transaction.Workstationid,
								data_transaction.UserGroupid,
								data_transaction.UserId,
								@BatchDate,
								CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
									 else data_transaction.TransactionDate
								end TransactionDate,
								Coalesce(DATA_TransactionItem.Quantity, 1),
								DATA_SaleItem.UnitPrice,
								case when isnull(DATA_TransactionItem.TotalAmount, 0) &lt;&gt; 0 then DATA_TransactionItem.TotalAmount
									when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
									else DATA_Sale.TotalAmount
								end,
								case when isnull((DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes)
									when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
									else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
								end as NetAmount,
								@SuspendPrice,
								@SuspendCOAAccount_Percentage,
								@SuspendRemainingValues,
								case    when (data_saleitem.ProductTaxType &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) 
												  and (isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0) 
													   and (((select discountamount from data_saleitemrule where saleitemid = DATA_SaleItem.saleitemid) &gt; 0) and (data_transaction.transactiontype in (7, 20, 22)))							
											then ((DATA_SaleItem.UnitRawPrice + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)

				        when (data_saleitem.ProductTaxType &lt;&gt; 1) and (data_transaction.transactiontype in (18, 20, 22)) and (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitRawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitRawPrice  + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)
						when (data_saleitem.ProductTaxType = 1) and (data_transaction.transactiontype in (18, 20, 22)) and isnull((DATA_SaleItem.UnitRawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitRawPrice - DATA_SaleItem.unittaxes + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)

										when (data_saleitem.ProductTaxType &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice  + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)
										when (data_saleitem.ProductTaxType = 1) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice - DATA_SaleItem.unittaxes + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)

										when (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 and data_saleitem.unitRecharge = 0 then 0
										when (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 and data_saleitem.unitRecharge &lt;&gt; 0 then data_saleitem.unitRecharge
										when isnull((data_transaction.TotalAmount), 0) &lt;&gt; 0 then data_transaction.TotalAmount
										when isnull((DATA_Sale.TotalAmount), 0) &lt;&gt; 0 then DATA_Sale.TotalAmount
										else (data_transaction.Revenue)
								end,
								case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
										when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
										when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 1
										when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 2
										else @SuspendRRCOAAccountingType
								end Accountingtype,
								@SuspendRRCalcTypeTrigger,
								@SuspendPercentage,
								@SuspendDays,
								CNF_AttributeSet.Attributeids
	   
						from DATA_Sale
							inner join data_transaction			on data_transaction.TransactionId = ISNULL(data_sale.voidtransactionid, DATA_Sale.PaidTransactionId)
							left join DATA_TransactionItem		on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
							left join DATA_SaleItem			    on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
							left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
							left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

						where DATA_Sale.Paid = 1
							and data_transaction.transactiontype not in (6, 8, 10, 12, 14, 16, 42, 43, 31, 39, 48, 49, 52, 46, 47)
							and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
							   OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
							and data_transaction.transactionid in (select transactionid
																	from data_payment
																	where PaymentStatus = 1
																	and PaymentAmount &lt;&gt; 0
																)

						INSERT INTO [dbo].[RR_DATA_Revenue]
										([COAAccountId]
										,[RevenueRecognitionRuleId]
										,[RRCode]
										,[RRCalcTypeWhere]
										,[RRCalcTypeMethod]
										,[COAAccountConfigId]
										,[COAAccountType]
										,[COAAccountCode]
										,[TransactionId]
										,[SaleId]
										,[SiteId]
										,[OperatingAreaId]
										,[WorkstationId]
										,[UserGroupId]
										,[UserId]
										,[FCalcDate]
										,[FRevenueDate]
										,[Quantity]
										,[GrossAmount]
										,[NetAmount]
										,[Price]
										,[Percentage]
										,[RemaningValues]
										,[RevenueAmount]
										,[AccountingType]
										,[RRCalcTypeTrigger]
										,[RRPercentage]
										,[RRDays])
								select @SuspendCOAAccountId,
										@SuspendRRRId,
										@SuspendRRRCode,
										@SuspendRRCalcTypeWhere,
										@SuspendRRCalcTypeMethod,
										@SuspendCOAAccountConfigId,
										@SuspendCOAAccountTypeId,
										@SuspendCOAAccountCode,
										data_transaction.transactionid, 
										data_transaction.saleid,
										data_transaction.Siteid,
										data_transaction.OperatingAreaId,
										data_transaction.Workstationid,
										data_transaction.UserGroupid,
										data_transaction.UserId,
										@BatchDate,
										CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
											 else data_transaction.TransactionDate
										end TransactionDate,
										0 Quantity,
										data_transaction.revenue TotalAmount,
										data_transaction.revenue NetAmount,
										@SuspendPrice,
										@SuspendCOAAccount_Percentage,
										@SuspendRemainingValues,
										p.Amount,
										@SuspendRRCOAAccountingType,
										@SuspendRRCalcTypeTrigger,
										@SuspendPercentage,
										@SuspendDays
	   
						from DATA_Sale
							inner join data_transaction			on data_transaction.saleid = data_sale.saleid
							left  join  (select settletransactionid, sum(data_payment.paymentamount) as amount
											from data_paymentcredit
												INNER JOIN DATA_Payment						on data_payment.paymentid = data_paymentcredit.paymentid
												INNER JOIN DATA_Transaction					on data_transaction.transactionid = data_paymentcredit.SettleTransactionId
											where ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
												  OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
											group by settletransactionid)p					on p.SettleTransactionId = data_transaction.transactionid

						where DATA_Sale.Paid = 1
							and data_transaction.transactiontype in (6)
							and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
							   OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))


					INSERT INTO [dbo].[RR_DATA_Revenue]
								([COAAccountId]
								,[RevenueRecognitionRuleId]
								,[RRCode]
								,[RRCalcTypeWhere]
								,[RRCalcTypeMethod]
								,[COAAccountConfigId]
								,[COAAccountType]
								,[COAAccountCode]
								,[TransactionId]
								,[SaleId]
								,[SaleItemId]
								,[MatrixCellId]
								,[MatrixCellCode]
								,[MatrixSheetID]
								,[SiteId]
								,[OperatingAreaId]
								,[WorkstationId]
								,[UserGroupId]
								,[UserId]
								,[FCalcDate]
								,[FRevenueDate]
								,[Quantity]
								,[UnitAmount]
								,[GrossAmount]
								,[NetAmount]
								,[Price]
								,[Percentage]
								,[RemaningValues]
								,[RevenueAmount]
								,[AccountingType]
								,[RRCalcTypeTrigger]
								,[RRPercentage]
								,[RRDays]
								,[AttributeIDS])
						select @SuspendCOAAccountId,
								@SuspendRRRId,
								@SuspendRRRCode,
								@SuspendRRCalcTypeWhere,
								@SuspendRRCalcTypeMethod,
								@SuspendCOAAccountConfigId,
								@SuspendCOAAccountTypeId,
								@SuspendCOAAccountCode,
								data_transaction.transactionid, 
								data_transaction.saleid,
								DATA_SaleItem.saleitemid,
								DATA_SaleItem.Matrixcellid,
								CNF_MatrixCell.Code,
								CNF_MatrixCell.MatrixSheetid,
								data_transaction.Siteid,
								data_transaction.OperatingAreaId,
								data_transaction.Workstationid,
								data_transaction.UserGroupid,
								data_transaction.UserId,
								@BatchDate,
								CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
									 else data_transaction.TransactionDate
								end TransactionDate,
								Coalesce(DATA_SaleItem.Quantity, 1),
								DATA_SaleItem.UnitPrice,
								case when isnull(DATA_SaleItem.TotalAmount, 0) &lt;&gt; 0 then DATA_SaleItem.TotalAmount
									when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
									else DATA_Sale.TotalAmount
								end,
								case when isnull((DATA_SaleItem.TotalAmount - DATA_SaleItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_SaleItem.TotalAmount - DATA_SaleItem.TotalTaxes)
									when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
									else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
								end as NetAmount,
								@SuspendPrice,
								@SuspendCOAAccount_Percentage,
								@SuspendRemainingValues,
								case    when (data_saleitem.ProductTaxType &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) 
												  and (isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0) 
													   and (((select discountamount from data_saleitemrule where saleitemid = DATA_SaleItem.saleitemid) &gt; 0) and (data_transaction.transactiontype in (7, 20, 22)))							
											then ((DATA_SaleItem.UnitRawPrice + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)


										when (data_saleitem.ProductTaxType &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice  + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)
										when (data_saleitem.ProductTaxType = 1) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice - DATA_SaleItem.unittaxes + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)
										when (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 then 0
										when (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 and data_saleitem.unitRecharge &lt;&gt; 0 then data_saleitem.unitRecharge
										when isnull((data_transaction.TotalAmount), 0) &lt;&gt; 0 then data_transaction.TotalAmount
										when isnull((DATA_Sale.TotalAmount), 0) &lt;&gt; 0 then DATA_Sale.TotalAmount
										else (data_transaction.Revenue)
								end,
								case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
										when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
										when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 1
										when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 2
										else @SuspendRRCOAAccountingType
								end Accountingtype,
								@SuspendRRCalcTypeTrigger,
								@SuspendPercentage,
								@SuspendDays,
								CNF_AttributeSet.Attributeids
	   
						from DATA_Sale
							inner join data_transaction			on data_transaction.saleid = data_sale.saleid
							left join DATA_SaleItem			    on DATA_SaleItem.saleid = DATA_Transaction.saleid
							left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
							left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

						where DATA_Sale.Paid = 1
							and data_transaction.transactiontype in (46, 47)
							and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
							   OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
							and data_transaction.transactionid in (select transactionid
																	from data_payment
																	where PaymentStatus = 1
																	and PaymentAmount &lt;&gt; 0
																)


					INSERT INTO [dbo].[RR_DATA_Revenue]
								([COAAccountId]
								,[RevenueRecognitionRuleId]
								,[RRCode]
								,[RRCalcTypeWhere]
								,[RRCalcTypeMethod]
								,[COAAccountConfigId]
								,[COAAccountType]
								,[COAAccountCode]
								,[TransactionId]
								,[SaleId]
								,[SaleItemId]
								,[MatrixCellId]
								,[MatrixCellCode]
								,[MatrixSheetID]
								,[SiteId]
								,[OperatingAreaId]
								,[WorkstationId]
								,[UserGroupId]
								,[UserId]
								,[FCalcDate]
								,[FRevenueDate]
								,[Quantity]
								,[UnitAmount]
								,[GrossAmount]
								,[NetAmount]
								,[Price]
								,[Percentage]
								,[RemaningValues]
								,[RevenueAmount]
								,[AccountingType]
								,[RRCalcTypeTrigger]
								,[RRPercentage]
								,[RRDays]
								,[AttributeIDS])
						select @SuspendCOAAccountId,
								@SuspendRRRId,
								@SuspendRRRCode,
								@SuspendRRCalcTypeWhere,
								@SuspendRRCalcTypeMethod,
								@SuspendCOAAccountConfigId,
								@SuspendCOAAccountTypeId,
								@SuspendCOAAccountCode,
								data_transaction.transactionid, 
								data_transaction.saleid,
								DATA_TransactionItem.saleitemid,
								DATA_SaleItem.Matrixcellid,
								CNF_MatrixCell.Code,
								CNF_MatrixCell.MatrixSheetid,
								data_transaction.Siteid,
								data_transaction.OperatingAreaId,
								data_transaction.Workstationid,
								data_transaction.UserGroupid,
								data_transaction.UserId,
								@BatchDate,
								CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
									 else data_transaction.TransactionDate
								end TransactionDate,
								Coalesce(DATA_TransactionItem.Quantity, 1),
								DATA_SaleItem.UnitPrice,
								case when isnull(DATA_TransactionItem.TotalAmount, 0) &lt;&gt; 0 then DATA_TransactionItem.TotalAmount
									when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
									else DATA_Sale.TotalAmount
								end,
								case when isnull((DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes)
									when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
									else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
								end as NetAmount,
								@SuspendPrice,
								@SuspendCOAAccount_Percentage,
								@SuspendRemainingValues,
								DATA_SaleItem.Unitrecharge,
								case    when TransactionType in (5, 17, 8, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
										when TransactionType in (5, 17, 8, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
										when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 2
										when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 1
										else @SuspendRRCOAAccountingType
								end Accountingtype,
								@SuspendRRCalcTypeTrigger,
								@SuspendPercentage,
								@SuspendDays,
								CNF_AttributeSet.Attributeids
	   
						from DATA_Sale
							inner join data_transaction			on data_transaction.TransactionId = ISNULL(data_sale.voidtransactionid, DATA_Sale.PaidTransactionId)
							left join DATA_TransactionItem		on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
							left join DATA_SaleItem			    on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
							left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
							left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

						where DATA_Sale.Paid = 1
							and data_transaction.transactiontype in (10, 42, 43, 49)
							and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
							   OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
							and data_transaction.transactionid in (select transactionid
																	from data_payment
																	where PaymentStatus = 1
																	and PaymentAmount &lt;&gt; 0
																)
			
				INSERT INTO [dbo].[RR_DATA_Revenue]
								([COAAccountId]
								,[RevenueRecognitionRuleId]
								,[RRCode]
								,[RRCalcTypeWhere]
								,[RRCalcTypeMethod]
								,[COAAccountConfigId]
								,[COAAccountType]
								,[COAAccountCode]
								,[TransactionId]
								,[SaleId]
								,[SaleItemId]
								,[MatrixCellId]
								,[MatrixCellCode]
								,[MatrixSheetID]
								,[SiteId]
								,[OperatingAreaId]
								,[WorkstationId]
								,[UserGroupId]
								,[UserId]
								,[FCalcDate]
								,[FRevenueDate]
								,[Quantity]
								,[UnitAmount]
								,[GrossAmount]
								,[NetAmount]
								,[Price]
								,[Percentage]
								,[RemaningValues]
								,[RevenueAmount]
								,[AccountingType]
								,[RRCalcTypeTrigger]
								,[RRPercentage]
								,[RRDays]
								,[AttributeIDS])
						select @SuspendCOAAccountId,
								@SuspendRRRId,
								@SuspendRRRCode,
								@SuspendRRCalcTypeWhere,
								@SuspendRRCalcTypeMethod,
								@SuspendCOAAccountConfigId,
								@SuspendCOAAccountTypeId,
								@SuspendCOAAccountCode,
								data_transaction.transactionid, 
								data_transaction.saleid,
								DATA_TransactionItem.saleitemid,
								DATA_SaleItem.Matrixcellid,
								CNF_MatrixCell.Code,
								CNF_MatrixCell.MatrixSheetid,
								data_transaction.Siteid,
								data_transaction.OperatingAreaId,
								data_transaction.Workstationid,
								data_transaction.UserGroupid,
								data_transaction.UserId,
								@BatchDate,
								CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
									 else data_transaction.TransactionDate
								end TransactionDate,
								Coalesce(DATA_TransactionItem.Quantity, 1),
								DATA_SaleItem.UnitPrice,
								case when isnull(DATA_TransactionItem.TotalAmount, 0) &lt;&gt; 0 then DATA_TransactionItem.TotalAmount
									when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
									else DATA_Sale.TotalAmount
								end,
								case when isnull((DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes)
									when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
									else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
								end as NetAmount,
								@SuspendPrice,
								@SuspendCOAAccount_Percentage,
								@SuspendRemainingValues,
								ABS(DATA_SaleItem.Unitrecharge),
								case    when TransactionType in (5, 17, 8, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
										when TransactionType in (5, 17, 8, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
										when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 2
										when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 1
										else @SuspendRRCOAAccountingType
								end Accountingtype,
								@SuspendRRCalcTypeTrigger,
								@SuspendPercentage,
								@SuspendDays,
								CNF_AttributeSet.Attributeids
	   
						from DATA_Sale
							inner join data_transaction			on data_transaction.TransactionId = ISNULL(data_sale.voidtransactionid, DATA_Sale.PaidTransactionId)
							left join DATA_TransactionItem		on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
							left join DATA_SaleItem			    on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
							left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
							left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

						where DATA_Sale.Paid = 1
							and data_transaction.transactiontype in (31, 48, 52)
							and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
							   OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
							and data_transaction.transactionid in (select transactionid
																	from data_payment
																	where PaymentStatus = 1
																	and PaymentAmount &lt;&gt; 0
																   )


					INSERT INTO [dbo].[RR_DATA_Revenue]
										([COAAccountId]
										,[RevenueRecognitionRuleId]
										,[RRCode]
										,[RRCalcTypeWhere]
										,[RRCalcTypeMethod]
										,[COAAccountConfigId]
										,[COAAccountType]
										,[COAAccountCode]
										,[TransactionId]
										,[SaleId]
										,[SaleItemId]
										,[MatrixCellId]
										,[MatrixCellCode]
										,[MatrixSheetID]
										,[SiteId]
										,[OperatingAreaId]
										,[WorkstationId]
										,[UserGroupId]
										,[UserId]
										,[FCalcDate]
										,[FRevenueDate]
										,[Quantity]
										,[UnitAmount]
										,[GrossAmount]
										,[NetAmount]
										,[Price]
										,[Percentage]
										,[RemaningValues]
										,[RevenueAmount]
										,[AccountingType]
										,[RRCalcTypeTrigger]
										,[RRPercentage]
										,[RRDays]
										,[AttributeIDS])
								select @SuspendCOAAccountId,
										@SuspendRRRId,
										@SuspendRRRCode,
										@SuspendRRCalcTypeWhere,
										@SuspendRRCalcTypeMethod,
										@SuspendCOAAccountConfigId,
										@SuspendCOAAccountTypeId,
										@SuspendCOAAccountCode,
										data_transaction.transactionid, 
										data_transaction.saleid,
										DATA_TransactionItem.saleitemid,
										DATA_SaleItem.Matrixcellid,
										CNF_MatrixCell.Code,
										CNF_MatrixCell.MatrixSheetid,
										data_transaction.Siteid,
										data_transaction.OperatingAreaId,
										data_transaction.Workstationid,
										data_transaction.UserGroupid,
										data_transaction.UserId,
										@BatchDate,
										CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
											 else data_transaction.TransactionDate
										end TransactionDate,
										Coalesce(DATA_TransactionItem.Quantity, 1),
										DATA_SaleItem.UnitPrice,
										case when isnull(DATA_TransactionItem.TotalAmount, 0) &lt;&gt; 0 then DATA_TransactionItem.TotalAmount
											when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
											else DATA_Sale.TotalAmount
										end,
										case when isnull((DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes)
											when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
											else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
										end as NetAmount,
										@SuspendPrice,
										@SuspendCOAAccount_Percentage,
										@SuspendRemainingValues,
										case when (data_saleitem.ProductTaxType &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice + DATA_SaleItem.unittaxes) * DATA_SaleItem.Quantity)
											 when (data_saleitem.ProductTaxType = 1) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice) * DATA_SaleItem.Quantity)
											 when (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 then 0
											 when isnull((data_transaction.TotalAmount), 0) &lt;&gt; 0 then data_transaction.TotalAmount
											 when isnull((DATA_Sale.TotalAmount), 0) &lt;&gt; 0 then DATA_Sale.TotalAmount
											 else (data_transaction.Revenue)
										end,
										case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
												when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
												when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 2
												when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 1
												else @SuspendRRCOAAccountingType
										end Accountingtype,
										@SuspendRRCalcTypeTrigger,
										@SuspendPercentage,
										@SuspendDays,
										CNF_AttributeSet.Attributeids
	   
								from DATA_Sale
									inner join data_transaction			on data_transaction.Saleid = DATA_Sale.Saleid
									left join DATA_TransactionItem		on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
									left join DATA_SaleItem			    on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
									left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
									left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

								where data_transaction.transactiontype in (8)
									and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
										OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
									and data_transaction.transactionid in (select transactionid
																			from data_payment
																			where PaymentStatus = 1
																			and PaymentAmount &lt;&gt; 0
																		)

							INSERT INTO [dbo].[RR_DATA_Revenue]
										([COAAccountId]
										,[RevenueRecognitionRuleId]
										,[RRCode]
										,[RRCalcTypeWhere]
										,[RRCalcTypeMethod]
										,[COAAccountConfigId]
										,[COAAccountType]
										,[COAAccountCode]
										,[TransactionId]
										,[SaleId]
										,[SiteId]
										,[OperatingAreaId]
										,[WorkstationId]
										,[UserGroupId]
										,[UserId]
										,[FCalcDate]
										,[FRevenueDate]
										,[Quantity]
										,[GrossAmount]
										,[NetAmount]
										,[Price]
										,[Percentage]
										,[RemaningValues]
										,[RevenueAmount]
										,[AccountingType]
										,[RRCalcTypeTrigger]
										,[RRPercentage]
										,[RRDays])
								select @SuspendCOAAccountId,
										@SuspendRRRId,
										@SuspendRRRCode,
										@SuspendRRCalcTypeWhere,
										@SuspendRRCalcTypeMethod,
										@SuspendCOAAccountConfigId,
										@SuspendCOAAccountTypeId,
										@SuspendCOAAccountCode,
										data_transaction.transactionid, 
										data_transaction.saleid,
										data_transaction.Siteid,
										data_transaction.OperatingAreaId,
										data_transaction.Workstationid,
										data_transaction.UserGroupid,
										data_transaction.UserId,
										@BatchDate,
										CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
											 else data_transaction.TransactionDate
										end TransactionDate,
										0 Quantity,
										data_transaction.revenue TotalAmount,
										data_transaction.revenue NetAmount,
										@SuspendPrice,
										@SuspendCOAAccount_Percentage,
										@SuspendRemainingValues,
										data_transaction.revenue,
										@SuspendRRCOAAccountingType,
										@SuspendRRCalcTypeTrigger,
										@SuspendPercentage,
										@SuspendDays
	   
								from DATA_Sale
									inner join data_transaction			on data_transaction.saleid = DATA_Sale.saleid
								where data_transaction.transactiontype = 12
									and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
										OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
									and data_transaction.transactionid in (select transactionid
																			from data_payment
																			where PaymentStatus = 1
																			and PaymentAmount &lt;&gt; 0
																		)



								INSERT INTO [dbo].[RR_DATA_Revenue]
										([COAAccountId]
										,[RevenueRecognitionRuleId]
										,[RRCode]
										,[RRCalcTypeWhere]
										,[RRCalcTypeMethod]
										,[COAAccountConfigId]
										,[COAAccountType]
										,[COAAccountCode]
										,[TransactionId]
										,[SaleId]
										,[SaleItemId]
										,[MatrixCellId]
										,[MatrixCellCode]
										,[MatrixSheetID]
										,[SiteId]
										,[OperatingAreaId]
										,[WorkstationId]
										,[UserGroupId]
										,[UserId]
										,[FCalcDate]
										,[FRevenueDate]
										,[Quantity]
										,[UnitAmount]
										,[GrossAmount]
										,[NetAmount]
										,[Price]
										,[Percentage]
										,[RemaningValues]
										,[RevenueAmount]
										,[AccountingType]
										,[RRCalcTypeTrigger]
										,[RRPercentage]
										,[RRDays]
										,[AttributeIDS])
										select *
										from (
								select @SuspendCOAAccountId as COAAccountId,
										@SuspendRRRId as RevenueRecognitionRuleId,
										@SuspendRRRCode as RRCode,
										@SuspendRRCalcTypeWhere as RRCalcTypeWhere,
										@SuspendRRCalcTypeMethod as RRCalcTypeMethod,
										@SuspendCOAAccountConfigId as COAAccountConfigId,
										@SuspendCOAAccountTypeId as COAAccountType,
										@SuspendCOAAccountCode as COAAccountCode,
										data_transaction.transactionid, 
										data_transaction.saleid,
										DATA_SaleItem.saleitemid,
										DATA_SaleItem.Matrixcellid,
										CNF_MatrixCell.Code,
										CNF_MatrixCell.MatrixSheetid,
										data_transaction.Siteid,
										data_transaction.OperatingAreaId,
										data_transaction.Workstationid,
										data_transaction.UserGroupid,
										data_transaction.UserId,
										@BatchDate as calcdate,
										CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
												else data_transaction.TransactionDate
										end TransactionDate,
										Coalesce(DATA_SaleItem.Quantity, 1) as quantity,
										DATA_SaleItem.UnitPrice,
										case when isnull(DATA_SaleItem.TotalAmount, 0) &lt;&gt; 0 then DATA_SaleItem.TotalAmount
											when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
											else DATA_Sale.TotalAmount
										end as totalamount,
										case when isnull((DATA_SaleItem.TotalAmount - DATA_SaleItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_SaleItem.TotalAmount - DATA_SaleItem.TotalTaxes)
											when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
											else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
										end as NetAmount,
										@SuspendPrice as suspendprice,
										@SuspendCOAAccount_Percentage as percentage,
										@SuspendRemainingValues as remainingValues,
										case when (data_saleitem.ProductTaxType &lt;&gt; 1) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice) * DATA_SaleItem.Quantity)
											 when (data_saleitem.ProductTaxType = 1) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice - DATA_SaleItem.unittaxes) * DATA_SaleItem.Quantity)
											 when isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 then 0
											 when isnull((data_transaction.TotalAmount), 0) &lt;&gt; 0 then data_transaction.TotalAmount
											 when isnull((DATA_Sale.TotalAmount), 0) &lt;&gt; 0 then DATA_Sale.TotalAmount
											 else (data_transaction.Revenue)
										end as Revenueamount,
										case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
												when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
												when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 2
												when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 1
												else @SuspendRRCOAAccountingType
										end Accountingtype,
										@SuspendRRCalcTypeTrigger as rrTrigger,
										@SuspendPercentage as suspercentage,
										@SuspendDays as suspendday,
										CNF_AttributeSet.Attributeids
	   
								from DATA_Sale
									inner join data_transaction			on data_transaction.TransactionId = DATA_Sale.PaidTransactionId
									left join DATA_SaleItem			    on DATA_SaleItem.SAleid = data_transaction.SAleid
									left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
									left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

								where DATA_Sale.Paid = 1
									and data_transaction.transactiontype in (16)
									and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
									 OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
									and data_transaction.transactionid in (select transactionid
																			from data_payment
																			where PaymentStatus = 1
																			--and PaymentAmount &lt;&gt; 0
																		)
									and data_transaction.transactionid not in (select distinct transactionid
																				from rr_data_Revenue
																				where transactionid is not null)
									and data_saleitem.saleitemid not in (select distinct data_saleitem.saleitemid
																	from data_saleitem
																			inner join data_transactionitem   on data_transactionitem.saleitemid = data_saleitem.saleitemid
																			inner join data_transaction       on data_transaction.transactionid = data_transactionitem.transactionid
																	where data_transaction.transactiontype in (5)
																	)
									)p  where UnitPrice &lt;&gt; 0


								INSERT INTO [dbo].[RR_DATA_Revenue]
										([COAAccountId]
										,[RevenueRecognitionRuleId]
										,[RRCode]
										,[RRCalcTypeWhere]
										,[RRCalcTypeMethod]
										,[COAAccountConfigId]
										,[COAAccountType]
										,[COAAccountCode]
										,[TransactionId]
										,[SaleId]
										,[SaleItemId]
										,[MatrixCellId]
										,[MatrixCellCode]
										,[MatrixSheetID]
										,[SiteId]
										,[OperatingAreaId]
										,[WorkstationId]
										,[UserGroupId]
										,[UserId]
										,[FCalcDate]
										,[FRevenueDate]
										,[Quantity]
										,[UnitAmount]
										,[GrossAmount]
										,[NetAmount]
										,[Price]
										,[Percentage]
										,[RemaningValues]
										,[RevenueAmount]
										,[AccountingType]
										,[RRCalcTypeTrigger]
										,[RRPercentage]
										,[RRDays]
										,[AttributeIDS])
								select @SuspendCOAAccountId,
										@SuspendRRRId,
										@SuspendRRRCode,
										@SuspendRRCalcTypeWhere,
										@SuspendRRCalcTypeMethod,
										@SuspendCOAAccountConfigId,
										@SuspendCOAAccountTypeId,
										@SuspendCOAAccountCode,
										data_transaction.transactionid, 
										data_transaction.saleid,
										DATA_TransactionItem.saleitemid,
										DATA_SaleItem.Matrixcellid,
										CNF_MatrixCell.Code,
										CNF_MatrixCell.MatrixSheetid,
										data_transaction.Siteid,
										data_transaction.OperatingAreaId,
										data_transaction.Workstationid,
										data_transaction.UserGroupid,
										data_transaction.UserId,
										@BatchDate,
										CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
											 else data_transaction.TransactionDate
										end TransactionDate,
										Coalesce(DATA_TransactionItem.Quantity, 1),
										DATA_SaleItem.UnitPrice,
										case when isnull(DATA_TransactionItem.TotalAmount, 0) &lt;&gt; 0 then DATA_TransactionItem.TotalAmount
											when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
											else DATA_Sale.TotalAmount
										end,
										case when isnull((DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes)
											when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
											else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
										end as NetAmount,
										@SuspendPrice,
										@SuspendCOAAccount_Percentage,
										@SuspendRemainingValues,
										case when isnull((DATA_TransactionItem.UnitPrice *  DATA_TransactionItem.Quantity), 0) &lt;&gt; 0 then (DATA_TransactionItem.UnitPrice *  DATA_TransactionItem.Quantity)
											when isnull((data_transaction.TotalAmount), 0) &lt;&gt; 0 then data_transaction.TotalAmount
											when isnull((DATA_Sale.TotalAmount), 0) &lt;&gt; 0 then DATA_Sale.TotalAmount
											else (data_transaction.Revenue)
										end,
										case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
												when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
												when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 2
												when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 1
												else @SuspendRRCOAAccountingType
										end Accountingtype,
										@SuspendRRCalcTypeTrigger,
										@SuspendPercentage,
										@SuspendDays,
										CNF_AttributeSet.Attributeids
	   
								from DATA_Sale
									inner join data_transaction			on data_transaction.saleid = DATA_Sale.saleid
									inner join DATA_TransactionItem		on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
									left join DATA_SaleItem			    on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
									left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
									left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

								where DATA_Sale.Paid = 1
									and data_transaction.transactiontype in (5)
									and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
									 OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
					
									and data_transaction.transactionid in (select transactionid
																			from data_payment
																			where PaymentStatus = 1
																			and PaymentAmount &lt;&gt; 0
																		)
									and data_transaction.transactionid not in (select distinct transactionid
																				from rr_data_Revenue
																				where transactionid is not null)

				--PaymentMethod
								INSERT INTO [dbo].[RR_DATA_Revenue]
												([COAAccountId]
												,[RevenueRecognitionRuleId]
												,[RRCode]
												,[RRCalcTypeWhere]
												,[RRCalcTypeMethod]
												,[COAAccountConfigId]
												,[COAAccountType]
												,[COAAccountCode]
												,[TransactionId]
												,[SaleId]
												,[SiteId]
												,[OperatingAreaId]
												,[WorkstationId]
												,[UserGroupId]
												,[UserId]
												,[FCalcDate]
												,[FRevenueDate]
												,[Quantity]
												,[GrossAmount]
												,[NetAmount]
												,[Price]
												,[Percentage]
												,[RemaningValues]
												,[RevenueAmount]
												,[AccountingType]
												,[RRCalcTypeTrigger]
												,[RRPercentage]
												,[RRDays])
												select  coaaccountid,
														RRID,
														RRCode,
														TypeWhere,
														method,
														Configid,
														AccountType,
														AccountCode,
														transactionid, 
														saleid,
														Siteid,
														OperatingAreaId,
														WorkstationID,
														UserGroupid,
														UserId,
														BatchDate,
														TransactionDate,
														Qty,
														Gross,
														net,
														price,
														percentage,
														RemaningValue,
														sum(abs(RevenueAmount)),
														Accountingtype,
														TypeTrigger,
														PaymentPercentage,
														RRDays
												from (
												select  coaaccountid,
														RRID,
														RRCode,
														TypeWhere,
														method,
														Configid,
														AccountType,
														AccountCode,
														transactionid, 
														saleid,
														Siteid,
														OperatingAreaId,
														WorkstationID,
														UserGroupid,
														UserId,
														BatchDate,
														TransactionDate,
														Qty,
														Gross,
														net,
														price,
														percentage,
														RemaningValue,
														case when Rownumber = 1 then RevenueAmount + Change
															 else RevenueAmount
														 end RevenueAmount,
														Accountingtype,
														TypeTrigger,
														PaymentPercentage,
														RRDays
												from (
												select @PaymentCOAAccountId as coaaccountid,
														@PaymentRRRId as RRID,
														@PaymentRRRCode as RRCode,
														@PaymentRRCalcTypeWhere as TypeWhere,
														@PaymentRRCalcTypeMethod as method,
														@PaymentCOAAccountConfigId as Configid,
														@PaymentCOAAccountTypeId as AccountType,
														@PaymentCOAAccountCode as AccountCode,
														data_transaction.transactionid, 
														data_transaction.saleid,
														data_transaction.Siteid,
														data_transaction.OperatingAreaId,
														data_transaction.Workstationid,
														data_transaction.UserGroupid,
														data_transaction.UserId,
														@BatchDate as BatchDate,
														CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
															 else data_transaction.TransactionDate
														end TransactionDate,
														0 as Qty,
														0 as Gross,
														0 as net,
														0 as price,
														100 as percentage,
														0 as RemaningValue,
														(data_payment.PaymentAmount) as RevenueAmount,
														case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @PaymentRRCOAAccountingType = 1 then 2
																when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @PaymentRRCOAAccountingType = 2 then 1
																when TransactionType in (7) and (data_payment.PaymentAmount + data_Payment.PaymentFee) &lt;= 0  then 2
																when TransactionType in (7) and (data_payment.PaymentAmount + data_Payment.PaymentFee) &gt; 0  then 1
																else @PaymentRRCOAAccountingType
														end Accountingtype,
														data_transaction.Change,
														@PaymentRRCalcTypeTrigger as TypeTrigger,
														@PaymentPercentage as PaymentPercentage,
														@PaymentDays as RRDays,
														Row_Number ()  OVER (PARTITION BY data_transaction.transactionid order by data_transaction.transactionid)  as Rownumber
		  
												from DATA_Sale
															INNER join data_transaction			on ((data_transaction.TransactionId = Isnull(data_sale.voidtransactionid, DATA_Sale.PaidTransactionId)) or 
																								   (data_transaction.saleid = data_sale.saleid))
															INNER JOIN DATA_Payment				on data_payment.transactionid = data_transaction.transactionid
			
												where data_payment.PaymentStatus = 1
													and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
													 OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
											)p
											)r
											group by 	coaaccountid,
														RRID,
														RRCode,
														TypeWhere,
														method,
														Configid,
														AccountType,
														AccountCode,
														transactionid, 
														saleid,
														Siteid,
														OperatingAreaId,
														Workstationid,
														UserGroupid,
														UserId,
														BatchDate,
														TransactionDate,
														Qty,
														Gross,
														net,
														price,
														percentage,
														RemaningValue,
														Accountingtype,
														TypeTrigger,
														PaymentPercentage,
														RRDays
											Having sum(abs(RevenueAmount)) &lt;&gt; 0
						



				--Tax
									INSERT INTO [dbo].[RR_DATA_Revenue]
												([COAAccountId]
												,[RevenueRecognitionRuleId]
												,[RRCode]
												,[RRCalcTypeWhere]
												,[RRCalcTypeMethod]
												,[COAAccountConfigId]
												,[COAAccountType]
												,[COAAccountCode]
												,[TransactionId]
												,[SaleId]
												,[SiteId]
												,[OperatingAreaId]
												,[WorkstationId]
												,[UserGroupId]
												,[UserId]
												,[FCalcDate]
												,[FRevenueDate]
												,[Quantity]
												,[GrossAmount]
												,[NetAmount]
												,[Price]
												,[Percentage]
												,[RemaningValues]
												,[RevenueAmount]
												,[AccountingType]
												,[RRCalcTypeTrigger]
												,[RRPercentage]
												,[RRDays])

												select  @TaxCOAAccountId,
														@TaxRRRId,
														@TaxRRRCode,
														@TaxRRCalcTypeWhere,
														@TaxRRCalcTypeMethod,
														@TaxCOAAccountConfigId,
														@TaxCOAAccountTypeId,
														@TaxCOAAccountCode,
														data_transaction.transactionid, 
														data_transaction.saleid,
														data_transaction.Siteid,
														data_transaction.OperatingAreaId,
														data_transaction.Workstationid,
														data_transaction.UserGroupid,
														data_transaction.UserId,
														@BatchDate,
														CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
															 else data_transaction.TransactionDate
														end TransactionDate,
														0,
														0,
														0,
														0,
														100,
														0,
														ABS(sum(taxamount)) RevenueAmount,
														case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @TaxRRCOAAccountingType = 1 then 2
																when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @TaxRRCOAAccountingType = 2 then 1
																when TransactionType in (7) and sum(taxamount) &lt;= 0  then 1
																when TransactionType in (7) and sum(taxamount) &gt; 0  then 2
																else @TaxRRCOAAccountingType
														end Accountingtype,
														@TaxRRCalcTypeTrigger,
														@TaxPercentage,
														@TaxDays
		   
											from Data_Sale
												INNER JOIN DATA_Transaction						on data_transaction.Saleid = Data_Sale.Saleid
												INNER JOIN DATA_TransactionTax					on data_transactiontax.transactionid = data_transaction.transactionid
												INNER JOIN CNF_Tax								on cnf_tax.taxid = DATA_TransactionTax.taxid
												--INNER JOIN coa_cnf_account coa					on coa.coaaccountid = cnf_tax.coaaccountid


											where transactiontype NOT IN (33, 45, 46, 47)
											   and Data_Sale.paid = 1
												and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
												 OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
												  and data_transaction.transactionid in (select distinct transactionid
																						   from data_payment
																						   where data_payment.paymentstatus = 1
																						)
											group by 			data_transaction.transactionid, 
																data_transaction.saleid,
																data_transaction.Siteid,
																data_transaction.OperatingAreaId,
																data_transaction.Workstationid,
																data_transaction.UserGroupid,
																data_transaction.UserId,
																Data_Transaction.TransactionDate,
																TransactionType,
																fTransactionDate


				--Discount

										INSERT INTO [dbo].[RR_DATA_Revenue]
												([COAAccountId]
												,[RevenueRecognitionRuleId]
												,[RRCode]
												,[RRCalcTypeWhere]
												,[RRCalcTypeMethod]
												,[COAAccountConfigId]
												,[COAAccountType]
												,[COAAccountCode]
												,[TransactionId]
												,[SaleId]
												,[Saleitemid]
												,[SiteId]
												,[OperatingAreaId]
												,[WorkstationId]
												,[UserGroupId]
												,[UserId]
												,[FCalcDate]
												,[FRevenueDate]
												,[Quantity]
												,[GrossAmount]
												,[NetAmount]
												,[Price]
												,[Percentage]
												,[RemaningValues]
												,[RevenueAmount]
												,[AccountingType]
												,[RRCalcTypeTrigger]
												,[RRPercentage]
												,[RRDays])

												select  @DiscountCOAAccountId,
														@DiscountRRRId,
														@DiscountRRRCode,
														@DiscountRRCalcTypeWhere,
														@DiscountRRCalcTypeMethod,
														@DiscountCOAAccountConfigId,
														@DiscountCOAAccountTypeId,
														@DiscountCOAAccountCode,
														data_transaction.transactionid, 
														data_transaction.saleid,
														p.Saleitemid,
														data_transaction.Siteid,
														data_transaction.OperatingAreaId,
														data_transaction.Workstationid,
														data_transaction.UserGroupid,
														data_transaction.UserId,
														@BatchDate,
														CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
															 else data_transaction.TransactionDate
														end TransactionDate,
														0,
														0,
														0,
														0,
														100,
														0,
														ABS(p.GLAmount) RevenueAmount,
														case    when data_transaction.TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) then 2
																when data_transaction.TransactionType in (7) and (GLAmount) &lt;= 0  then 2
																when data_transaction.TransactionType in (7) and (GLAmount) &gt; 0  then 1
																else @DiscountRRCOAAccountingType
														end Accountingtype,

														@DiscountRRCalcTypeTrigger,
														@DiscountPercentage,
														@DiscountDays
											FROM
											(
												SELECT distinct DATA_SaleItem.Saleitemid,
																DATA_Sale.saleid AS SAleid,
      															DATA_Transaction.TransactionType,
      															( SELECT top 1 transactionid
																	FROM data_transaction		WITH (NOLOCK)
																   WHERE saleid = DATA_Sale.saleid
																	AND transactiontype in (14, 16)
																	AND paid = 1
																) AS tester,

																CASE WHEN DATA_Transaction.TransactionId IN (
																											  SELECT TR.TransactionID
																												FROM DATA_Transaction TR			WITH (NOLOCK)
																													LEFT JOIN DATA_Payment DP		WITH (NOLOCK) ON TR.TransactionId = DP.TransactionId
																											  WHERE TR.SaleId = DATA_Sale.SaleId
																												AND TR.Paid = 1
																												AND DP.PaymentStatus NOT IN (0, 2, 3)
																											)
      
																			THEN DATA_Transaction.Transactionid
																	 ELSE (
																			  SELECT MIN(TR.TransactionID)
																				FROM DATA_Transaction TR				WITH (NOLOCK)
																					LEFT JOIN DATA_Payment DP			WITH (NOLOCK) ON TR.TransactionId = DP.TransactionId
																			   WHERE TR.SaleId = DATA_Sale.saleid
																				 AND TR.TransactionType = 16
																				 AND TR.Paid = 1
																				 AND DP.PaymentStatus NOT IN (0, 2, 3)
																		  )
																END Transactionid, 
																 CASE WHEN CNF_Promotion.PromotionType = 1 AND CNF_PromotionItemRule.NewProduct = 1 THEN  (CNF_MatrixCell.Price - SUM(DATA_SaleItemRule.DiscountAmount))
																	  ELSE  CASE WHEN sum(1*data_saleItemRule.DiscountAmount) &lt; 0 AND transactiontype IN(20, 22, 30, 7, 5, 46, 47) AND
																																												(SELECT Count(*) 
																																												   FROM data_transaction WITH (NOLOCK)
																																												  WHERE saleid = data_sale.saleid
																																												 ) = 1 					  					  					  										  
																					  THEN Sum(1 * DATA_SaleItemRule.DiscountAmount)
																				 WHEN sum(1*data_saleItemRule.DiscountAmount) &lt; 0 THEN	Sum(-1 * DATA_SaleItemRule.DiscountAmount)
																				 WHEN sum(1*data_saleItemRule.DiscountAmount) &gt; 0 AND transactiontype IN(20, 22, 30, 7, 5, 46, 47) THEN Sum(-1 * DATA_SaleItemRule.DiscountAmount)		            	                  
																				 ELSE sum(1*Data_SaleItemRule.DiscountAmount)
																			END
																END AS GLAmount


												FROM dbo.DATA_SaleItemRule				WITH (NOLOCK)
													LEFT JOIN dbo.CNF_PromotionItemRule WITH (NOLOCK) ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
													LEFT JOIN dbo.CNF_PromotionItem		WITH (NOLOCK) ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
													LEFT JOIN dbo.CNF_Promotion			WITH (NOLOCK) ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId
													LEFT JOIN dbo.CNF_DmgCategory		WITH (NOLOCK) ON CNF_DmgCategory.DmgCategoryId = CNF_Promotion.DmgCategoryId
													LEFT JOIN dbo.DATA_SaleItem			WITH (NOLOCK) ON DATA_SaleItem.SaleItemId = DATA_SaleItemRule.SaleItemId
													LEFT JOIN dbo.DATA_Sale				WITH (NOLOCK) ON DATA_Sale.SaleID = DATA_SaleItem.SaleID
													LEFT JOIN DATA_TransactionItem		WITH (NOLOCK) ON DATA_TransactionItem.SaleItemId = DATA_SaleItem.SaleItemId 
													LEFT JOIN DATA_Transaction			WITH (NOLOCK) ON  DATA_Transaction.TransactionId = DATA_TransactionItem.TransactionId
													LEFT JOIN CNF_MatrixCell			WITH (NOLOCK) ON CNF_MatrixCell.MatrixCellId =  DATA_SaleItem.MatrixCellId

 
												WHERE DATA_Transaction.saleid in (
																					SELECT ff.saleid 
																					  FROM DATA_Transaction ff WITH (NOLOCK) 
																						LEFT JOIN Data_Payment WITH (NOLOCK) on (ff.Transactionid = Data_Payment.Transactionid) 
																					 WHERE  ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
																						OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
																					   AND DATA_PAyment.PaymentStatus NOT in (0,2,3) 
																					   AND (TransactionType not in (12)) 
																					   AND ff.PAid = 1
																				 )  

												 AND DATA_Sale.Paid = 1
												 and transactiontype NOT IN (33, 45, 46, 47)
												 AND ((DATA_SaleItem.quantity &gt; 0) OR ((DATA_SaleItem.quantity &lt; 0) AND (transactiontype IN (20, 22, 30, 7, 5, 46, 47))))

         
												group BY DATA_SaleItem.Saleitemid,
														 DATA_Sale.saleid,
														 Data_transaction.Paid,
														 Data_Transaction.Transactionid,
														 Data_Transaction.fTransactionDate,
														 Data_Saleitem.Matrixcellid,
														 CNF_DmgCategory.DmgCategoryCode,
														 PromotionType,
														 CNF_PromotionItemRule.NewProduct,
														 CNF_MatrixCell.Price,
														 transactiontype,
														 CNF_DmgCategory.Description
											)p
												LEFT JOIN data_transaction WITH (NOLOCK) on data_transaction.transactionid = p.transactionid

											WHERE ((p.TransactionType &lt;&gt; 5) or (Tester is not null))
											  AND data_transaction.transactionid is not null


					
						--End Move Transactions to Suspend Account

						exec otn_sp_RR_RevenueData_OnDepositTrigger @BatchDate, @RRTransDateType

						exec otn_sp_RR_RevenueData_OnSaleTrigger @BatchDate, @RRTransDateType
		
						exec otn_sp_RR_RevenueData_OnMoneyCardLoad @BatchDate, @RRTransDateType

						exec otn_sp_RR_RevenueData_OnMoneyCardCashOut @BatchDate, @RRTransDateType

						exec otn_sp_RR_RevenueData_OnExternalMoneyCardCashOut @BatchDate, @RRTransDateType

						exec otn_sp_RR_RevenueData_OnExternalMoneyCardLoad @BatchDate, @RRTransDateType

						exec otn_sp_RR_RevenueData_OnCreditWriteoff @BatchDate, @RRTransDateType

						exec otn_sp_RR_RevenueData_OnMoneyRefundTrigger @BatchDate, @RRTransDateType

						exec otn_sp_RR_RevenueData_OnAdvancedPaymentTrigger @BatchDate, @RRTransDateType
		
						--exec otn_sp_RR_RevenueData_OnFlexContractPayment @BatchDate, @RRTransDateType

						--exec otn_sp_RR_RevenueData_OnFlexContractCancelled @BatchDate, @RRTransDateType

						exec otn_sp_RR_RevenueData_OnCreditSettlementTrigger @BatchDate, @RRTransDateType
		
						exec otn_sp_RR_RevenueData_SettleUpSuspendAccount @BatchDate, @RRTransDateType


						exec otn_sp_RR_RevenueData_OnTicketUsageTrigger @BatchDate, @RRTransDateType

						exec otn_sp_RR_RevenueData_OnEventTrigger @BatchDate, @RRTransDateType

						exec otn_sp_RR_RevenueData_OnTimePeriodTrigger @BatchDate, @RRTransDateType

						exec otn_sp_RR_RevenueData_OnTicketExpiredTrigger @BatchDate, @RRTransDateType

						exec otn_sp_RR_RevenueData_OnChangeValiditydateTrigger @BatchDate, @RRTransDateType
		

	FETCH NEXT FROM date_Cursor INTO
		@BatchDate

end

End</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>2364</SQLVERSION><RMTRACKLINK>BOS-66</RMTRACKLINK><REASON>Added new Foreign key 'FlexPlanTemplateId'  and new field 'FlexPlanOption' to table 'CNF_FlexContract'.</REASON><TABLENAMES>CNF_FlexPlanTemplate=FlexPlanTemplateId
CNF_FlexContract=FlexContractId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'FlexPlanTemplateId' AND
                Object_ID  = Object_ID(N'CNF_FlexContract'))
BEGIN
  ALTER TABLE CNF_FlexContract 
  ADD FlexPlanTemplateId Integer NULL,
      FlexPlanOption smallint NULL DEFAULT(0)
  CONSTRAINT [fk_CNF_FlexPlanTemplate_FlexPlanTemplateId] FOREIGN KEY([FlexPlanTemplateId])
  REFERENCES [CNF_FlexPlanTemplate] ([FlexPlanTemplateId])
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>2363</SQLVERSION><RMTRACKLINK>72531 </RMTRACKLINK><REASON>Create view for Site Information.   This information is being pulled onto reports and Receipts.</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS(select * FROM sys.views where name = 'vwSiteInformation')
	DROP View vwSiteInformation
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>CREATE view [dbo].[vwSiteInformation]
AS

SELECT   
	CNF_Site.SiteId, 
	CNF_Site.SiteName, 
	CNF_Site.SiteDescription, 
	CNF_Site.SiteAK, 
	Add1.MaskData as CompanyAddress1,
	Add2.MaskData as CompanyAddress2,
	City.MaskData as CompanyCity,
	State.MaskData as CompanyState,
	Zip.MaskData as CompanyZip,
	Country.MaskData as CompanyCountry,
	BPhone.MaskData as BusinessPhone,
	Fax.MaskData as CompanyFax,
	Web.MaskData as CompanyWebSite,
	City.MaskData + ', ' + State.MaskData + ' ' + Zip.MaskData as CityStateZip

FROM CNF_SITE
	left outer join DATA_DmgData Add1
		on Add1.fkey = CNF_Site.Siteid
		  and Add1.dmgtype = 29 and Add1.objtype = 36
	left outer join DATA_DmgData Add2
		on Add2.fkey = CNF_Site.Siteid
		  and Add2.dmgtype = 29 and Add2.objtype = 37
	left outer join DATA_DmgData City
		on City.fkey = CNF_Site.Siteid
		  and City.dmgtype = 29 and City.objtype = 38
	left outer join DATA_DmgData State
		on State.fkey = CNF_Site.Siteid
		  and State.dmgtype = 29 and State.objtype = 39
	left outer join DATA_DmgData Zip
		on Zip.fkey = CNF_Site.Siteid
		  and Zip.dmgtype = 29 and Zip.objtype = 40
	left outer join DATA_DmgData BPhone
		on BPhone.fkey = CNF_Site.Siteid
		  and BPhone.dmgtype = 29 and BPhone.objtype = 42
	left outer join DATA_DmgData Fax
		on Fax.fkey = CNF_Site.Siteid
		  and Fax.dmgtype = 29 and Fax.objtype = 44
	left outer join DATA_DmgData Web
		on Web.fkey = CNF_Site.Siteid
		  and Web.dmgtype = 29 and Web.objtype = 50
	left outer join DATA_DmgData Country
		on Country.fkey = CNF_Site.Siteid
		  and Country.dmgtype = 29 and Country.objtype = 41

</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>Emanuele Candido</ADDEDBY><SQLVERSION>2362</SQLVERSION><RMTRACKLINK>68154</RMTRACKLINK><REASON>Fix Stored procedures name generated during Offline Sync with wrong name.
Rename Stored procedure from "sp_" to "otn_sp"</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>declare @oldval varchar(max)
declare @newval varchar(max)
declare myCurs CURSOR FOR
  select pr.name
  from sys.procedures pr
	INNER JOIN sys.schemas s ON pr.schema_id = s.schema_id
  
  WHERE SUBSTRING(pr.name,1,3) = 'sp_'
    and s.name = 'dbo'

  

open myCurs
fetch next from myCurs into @oldval

while (@@FETCH_STATUS = 0)
begin
  set @newval = 'otn_' + @oldval
  IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(@newval) AND type in ('P', 'PC')) exec('drop procedure [' + @newval + ']')
  EXEC sp_rename @oldval, @newval

  fetch next from myCurs into @oldval
end

close myCurs
deallocate myCurs
</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>2361</SQLVERSION><RMTRACKLINK>72383 </RMTRACKLINK><REASON>New Indexes for GAR</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name='IDX_Transaction_TransactionDate' AND object_id = OBJECT_ID('DBO.DATA_Transaction'))
begin
	CREATE NONCLUSTERED INDEX [IDX_Transaction_TransactionDate] ON [dbo].[DATA_Transaction]
	(
		[TransactionDate] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
end
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name='IDX_Data_Sale_PaidTransactionID' AND object_id = OBJECT_ID('DBO.DATA_Sale'))
begin
	CREATE NONCLUSTERED INDEX [IDX_Data_Sale_PaidTransactionID] ON [dbo].[DATA_Sale]
	(
		[PaidTransactionID] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
end
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name='IDX_SaleItem_MatrixCellID' AND object_id = OBJECT_ID('DBO.DATA_SaleItem'))
begin
	CREATE NONCLUSTERED INDEX [IDX_SaleItem_MatrixCellID] ON [dbo].[DATA_SaleItem]
	(
		[MatrixCellID] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
end
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name='IDX_Data_Sale_PaidTransactionID_VoidTransactionID' AND object_id = OBJECT_ID('DBO.DATA_Sale'))
begin
	CREATE NONCLUSTERED INDEX [IDX_Data_Sale_PaidTransactionID_VoidTransactionID] ON [dbo].[DATA_Sale] ([Paid])
	INCLUDE ([SaleId],[PaidTransactionId],[VoidTransactionId])

	WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
end
</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>2360</SQLVERSION><RMTRACKLINK>BOS-65, BOS-66</RMTRACKLINK><REASON>Added table 'CNF_FlexPlanTemplate'
Added new fields 'AddTaxesToDownPayment ', 'RenewalSetting ',
and  'RenewalDate '  to table 'CNF_FlexContract'</REASON><TABLENAMES>CNF_FlexContract=FlexContractId
CNF_FlexPlanTemplate=FlexPlanTemplateId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                  AND  TABLE_NAME = 'CNF_FlexPlanTemplate'))

BEGIN
Create table [CNF_FlexPlanTemplate]
(
	[FlexPlanTemplateId] Integer Identity(1,1) NOT NULL,
	[Code] Nvarchar(10) NULL,
	[Name] Nvarchar(30) NULL,
	[PaymentNumber] Smallint NULL,
	[FlexPlanXML] Ntext NULL,
Primary Key ([FlexPlanTemplateId])
) 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'TaxesInDownPayment' AND
                Object_ID  = Object_ID(N'CNF_FlexContract'))
BEGIN
  ALTER TABLE CNF_FlexContract 
  ADD TaxesInDownPayment SmallInt NULL,
      RenewalSetting Smallint NULL,
      RenewalDate Datetime NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>dapicella</ADDEDBY><SQLVERSION>2359</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>Added column MobileTemplateId to CNF_MatrixCell
[0] Add column MobileTemplateId</REASON><TABLENAMES>CNF_MatrixCell=MatrixCellId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'MobileTemplateId' AND
                Object_ID  = Object_ID(N'CNF_MatrixCell'))
BEGIN
alter table CNF_MatrixCell
  add MobileTemplateId integer null
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>jlaguardia</ADDEDBY><SQLVERSION>2358</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES>CNF_FlexContract=FlexContractId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'AllowNotification' AND
                Object_ID  = Object_ID(N'CNF_FlexContract'))
BEGIN
  ALTER TABLE CNF_FlexContract ADD AllowNotification smallint NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>fulviodipalma</ADDEDBY><SQLVERSION>2357</SQLVERSION><RMTRACKLINK>71838</RMTRACKLINK><REASON>Added field ProdWebAddress</REASON><TABLENAMES>CNF_Site=SiteId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'ProdWebAddress' AND
                Object_ID  = Object_ID(N'CNF_Site'))
BEGIN
  ALTER TABLE CNF_Site ADD ProdWebAddress nvarchar(100) NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>stefanocoluccia</ADDEDBY><SQLVERSION>2356</SQLVERSION><RMTRACKLINK>72097</RMTRACKLINK><REASON>add field ApplyTaxOnZeroTicketAmount
Apply tax if ticket amount is 0 (only with tax excluded)? 0= False 1= True</REASON><TABLENAMES>CNF_Tax=TaxId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'ApplyTaxOnZeroTicketAmount' AND
                Object_ID  = Object_ID(N'CNF_Tax'))
BEGIN
  ALTER TABLE CNF_Tax ADD ApplyTaxOnZeroTicketAmount smallint NULL
END
</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>Federico Caramella</ADDEDBY><SQLVERSION>2355</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>CNF_Spacestructure
[0] Code modify length
[1] add SpaceStructureAk
[2] add DmgCategoryId
[3] add ForeignKey DmgCategoryId</REASON><TABLENAMES>CNF_SpaceStructure=SpaceStructureId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>ALTER TABLE CNF_SpaceStructure
ALTER COLUMN Code Varchar(100)</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
               WHERE Name = N'SpaceStructureAK' AND
               Object_ID = Object_ID(N'CNF_SpaceStructure'))
BEGIN
  ALTER TABLE CNF_SpaceStructure
  ADD SpaceStructureAK Varchar(32)
END

</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
               WHERE Name = N'DmgCategoryId' AND
               Object_ID = Object_ID(N'CNF_SpaceStructure'))
BEGIN
  ALTER TABLE CNF_SpaceStructure ADD DmgCategoryId int NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_SpaceStructure'
	          AND CONSTRAINT_NAME = N'fk_CNF_SpaceStructure_DmgCategoryId')
BEGIN
  ALTER TABLE CNF_SpaceStructure 
  ADD CONSTRAINT [fk_CNF_SpaceStructure_DmgCategoryId] FOREIGN KEY([DmgCategoryId])
  REFERENCES [CNF_DmgCategory] ([DmgCategoryId])
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>Programmatore</ADDEDBY><SQLVERSION>2354</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.17.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>Programmatore</ADDEDBY><SQLVERSION>2353</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.17.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>Programmatore</ADDEDBY><SQLVERSION>2352</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.17.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>Programmatore</ADDEDBY><SQLVERSION>2351</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>Programmatore</ADDEDBY><SQLVERSION>2350</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>Programmatore</ADDEDBY><SQLVERSION>2349</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>Programmatore</ADDEDBY><SQLVERSION>2348</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>Programmatore</ADDEDBY><SQLVERSION>2347</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>Programmatore</ADDEDBY><SQLVERSION>2346</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>Programmatore</ADDEDBY><SQLVERSION>2345</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>Programmatore</ADDEDBY><SQLVERSION>2344</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>Programmatore</ADDEDBY><SQLVERSION>2343</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>Programmatore</ADDEDBY><SQLVERSION>2342</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>Programmatore</ADDEDBY><SQLVERSION>2341</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>Programmatore</ADDEDBY><SQLVERSION>2340</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>Programmatore</ADDEDBY><SQLVERSION>2339</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>Programmatore</ADDEDBY><SQLVERSION>2338</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>Programmatore</ADDEDBY><SQLVERSION>2337</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>Programmatore</ADDEDBY><SQLVERSION>2336</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>Programmatore</ADDEDBY><SQLVERSION>2335</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>Programmatore</ADDEDBY><SQLVERSION>2334</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>Programmatore</ADDEDBY><SQLVERSION>2333</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>Programmatore</ADDEDBY><SQLVERSION>2332</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>Programmatore</ADDEDBY><SQLVERSION>2331</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>Programmatore</ADDEDBY><SQLVERSION>2330</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>Programmatore</ADDEDBY><SQLVERSION>2329</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.17.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>Programmatore</ADDEDBY><SQLVERSION>2328</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON></REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>Programmatore</ADDEDBY><SQLVERSION>2327</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.17.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>Programmatore</ADDEDBY><SQLVERSION>2326</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.17.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>Programmatore</ADDEDBY><SQLVERSION>2325</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.17.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON><TABLENAMES></TABLENAMES></SQLUPDATE><SQLUPDATE><ADDEDBY>dapicella</ADDEDBY><SQLVERSION>2324</SQLVERSION><RMTRACKLINK></RMTRACKLINK><REASON>CapacityLog
[0] DROP PROCEDURE otn_LOG_WSCapacity_insert
[1] CREATE PROCEDURE otn_LOG_WSCapacity_insert</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS(	SELECT * 
		FROM sys.objects 
		WHERE 
		  type = N'P' 
		  AND object_id = OBJECT_ID(N'otn_LOG_WSCapacity_insert')
		)
BEGIN
	DROP PROCEDURE otn_LOG_WSCapacity_insert
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>CREATE PROCEDURE [dbo].[otn_LOG_WSCapacity_insert]
  @LogCapacityId Integer output,
  @LogMessage XML,
  @EnvelopeCapacityId int,
  @Quantity int,
  @CapacityFunction varchar(200),
  @WorkstationId int,
  @UserId int
AS
BEGIN
	--IF 1 = 1 --ENABLED
	IF 1 = 0 --DISABLED
	BEGIN
		IF NOT (EXISTS (SELECT * 
						FROM INFORMATION_SCHEMA.TABLES 
						WHERE TABLE_SCHEMA = 'dbo' 
						AND  TABLE_NAME = 'LOG_WSCapacity'))

		BEGIN
			CREATE TABLE [dbo].[LOG_WSCapacity](
				[LogCapacityId] [int] IDENTITY(1,1) NOT NULL,
				[LogMessage] [XML] NULL,
				[EnvelopeCapacityId] [int] NULL,
				[Quantity] [int] NULL,
				[CapacityFunction] [varchar](200) NULL,
				[WorkstationId] [int] NULL,
				[UserId] [int] NULL,
				[TimeStamp] [datetime] NULL,
			 CONSTRAINT [PK_LOG_WSCapacity] PRIMARY KEY CLUSTERED 
			(
				[LogCapacityId] ASC
			)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
			) ON [PRIMARY]
		END


		INSERT INTO LOG_WSCapacity 
		(
			LogMessage,
			EnvelopeCapacityId,
			Quantity,
			CapacityFunction,
			WorkstationId,
			UserId,
			TimeStamp
		) 
		VALUES 
		(
			@LogMessage,
			@EnvelopeCapacityId,
			@Quantity,
			@CapacityFunction,
			@WorkstationId,
			@UserId,
			GETDATE()
		)

		SELECT @LogCapacityId = SCOPE_IDENTITY()
	END
	ELSE
	BEGIN
		SET @LogCapacityId = -1
	END

END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>AndreaDavanzo</ADDEDBY><SQLVERSION>2323</SQLVERSION><RMTRACKLINK>71968</RMTRACKLINK><REASON>Adding flag to force to apply rounding on void
[0] Adding column ForceRoundOnVoid</REASON><TABLENAMES>CNF_RoundingRule=RoundingRuleId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'ForceRoundOnVoid' AND
                Object_ID  = Object_ID(N'CNF_RoundingRule'))
BEGIN
  ALTER TABLE CNF_RoundingRule ADD ForceRoundOnVoid Smallint NOT NULL default 0
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>bvaeth</ADDEDBY><SQLVERSION>2322</SQLVERSION><RMTRACKLINK>71632</RMTRACKLINK><REASON>Added table 'CNF_Invoice' and 'DATA_InvoiceData'
Added a stored procedure named 'otn_sp_ui_SetInvoiceCounter</REASON><TABLENAMES>CNF_Invoice=InvoiceId
DATA_InvoiceData=InvoiceDataId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS ( SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND  TABLE_NAME = 'CNF_Invoice' )

BEGIN

Create table [CNF_Invoice]
(
	[InvoiceId] Integer Identity(1,1) NOT NULL,
	[Name] Nvarchar(50) NULL,
	[InvoiceAK] Varchar(32) NOT NULL, UNIQUE ([InvoiceAK]),
	[ValidityFrom] Datetime NULL,
	[ValidityTo] Datetime NULL,
	[Prefix] Nvarchar(10) NULL,
	[Suffix] Nvarchar(10) NULL,
	[Code] Nvarchar(10) NULL,
	[Description] Ntext NULL,
	[Enabled] Smallint NULL,
	[Section] Nvarchar(30) NULL,
	[NumberLength] Smallint NULL,
Primary Key ([InvoiceId])
) 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS ( SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND  TABLE_NAME = 'DATA_InvoiceData' )

BEGIN

Create table [DATA_InvoiceData]
(
	[InvoiceDataId] Integer Identity(1,1) NOT NULL,
	[InvoiceId] Integer NOT NULL,
	[TransactionId] Integer NOT NULL,
	[Section] Nvarchar(30) NULL,
	[Prefix] Nvarchar(10) NULL,
	[Suffix] Nvarchar(10) NULL,
	[InvoiceNumber] Nvarchar(100) NULL,
Primary Key ([InvoiceDataId])
) 
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>CREATE PROCEDURE dbo.otn_sp_ui_SetInvoiceCounter
 @CounterType smallint,
 @IdentifierAK varchar(32),
 @ReferenceTime varchar(32),
 @Counter integer ,
 @CounterUpdated integer output
AS
BEGIN

 insert into DATA_Counter (CounterType, IdentifierAK, ReferenceTime, Counter)
 
 select @CounterType, @IdentifierAK, IsNull(@ReferenceTime,'Never'), 0
 where
 0 = (select count(*) from DATA_Counter with (READCOMMITTEDLOCK, ROWLOCK) where CounterType = @CounterType and IdentifierAK = @IdentifierAK and
  IsNull(@ReferenceTime,'NEVER') = IsNull(ReferenceTime,'NEVER'))

   update DATA_Counter with (READCOMMITTEDLOCK, ROWLOCK)
   set    Counter = @Counter
   where  CounterType = @CounterType and IdentifierAK = @IdentifierAK and
		IsNull(@ReferenceTime,'NEVER') = IsNull(ReferenceTime,'NEVER') and 
		Not exists (Select 1 from DATA_InvoiceData where InvoiceId = (select InvoiceId from CNF_Invoice where InvoiceAK = @IdentifierAK))

  select @CounterUpdated = CASE WHEN @@ROWCOUNT &gt; 0 THEN 1 ELSE 0 END;
  
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'DATA_InvoiceData'
	          AND CONSTRAINT_NAME = N'fk_CNF_Invoice_InvoiceId')          
BEGIN
  ALTER TABLE DATA_InvoiceData WITH CHECK
  ADD CONSTRAINT [fk_CNF_Invoice_InvoiceId] FOREIGN KEY([InvoiceId])
  REFERENCES [CNF_Invoice] ([InvoiceId])
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'DATA_InvoiceData'
	          AND CONSTRAINT_NAME = N'fk_DATA_InvoiceData_TransactionId')          
BEGIN
  ALTER TABLE DATA_InvoiceData WITH CHECK
  ADD CONSTRAINT [fk_DATA_InvoiceData_TransactionId] FOREIGN KEY([TransactionId])
  REFERENCES [DATA_Transaction] ([TransactionId])
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>2321</SQLVERSION><RMTRACKLINK>71727</RMTRACKLINK><REASON>New script for Change Validity</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_RR_RevenueData_OnMoneyCardLoad]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_RR_RevenueData_OnMoneyCardLoad
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>CREATE Procedure dbo.otn_sp_RR_RevenueData_OnMoneyCardLoad
	@BatchDate Date,
	@RRTransDateType Integer
AS 
BEGIN
	
	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer
	Declare @OnMoneyCardCashOut Integer = 10

	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1


		BEGIN

			--Normal Transaction No Remaining Values
			INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[Saleitemid]
				   ,[MatrixCellid]
				   ,[MatrixCellCode]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays]
				   ,[AttributeIDs])
				   select *
				   from(
						select distinct coa_cnf_account.COAAccountId, 
								   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
								   RR_CNF_RevenueRecognitionRule.code,		   
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
								   COA_CNF_AccountConfig.COAAccountConfigId,
								   coa_cnf_account.COAAccountTypeId,
								   coa_cnf_account.Code as AccountCode,
								   RR_DATA_REVENUE.Transactionid as Transactionid,
								   RR_DATA_REVENUE.saleid as Saleid,
								   RR_DATA_REVENUE.SaleitemID as SaleitemID,
								   RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								   RR_DATA_REVENUE.MatrixcellCode as MatrixCode,
								   RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								   RR_DATA_REVENUE.Siteid as SiteID,
								   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								   RR_DATA_REVENUE.Workstationid as Workstationid,
								   RR_DATA_REVENUE.UserGroupid as UserGroupID,
								   RR_DATA_REVENUE.UserId as userID,
								   @BatchDate as BatchDate,
								   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
								        else DATA_Transaction.transactiondate
								   end as TransDate,
								   RR_DATA_REVENUE.Quantity as Quantity,
								   RR_DATA_REVENUE.GrossAmount as GrossAmount,
								   RR_DATA_REVENUE.NetAmount as NetAmount,
								   COA_CNF_AccountConfig.Price as ConfigPrice,
								   COA_CNF_AccountConfig.Percentage as ConfigPercentage,
								   COA_CNF_AccountConfig.RemainingValues,																		
									Case when COA_CNF_AccountConfig.Price &gt; 0 then (COA_CNF_AccountConfig.Price * RR_DATA_REVENUE.Quantity) 
										 else (ISNULL(((ABS((select (unitrecharge * Quantity)
															   from data_saleitem
															  where saleitemid = RR_DATA_REVENUE.saleitemid
										))) * COA_CNF_AccountConfig.Percentage/100), 0))																		                                                                                                                                                                                              
									end  as RevenueAmount,

								   case when TransactionType in (5, 17, 18, 20, 22, 30) and COA_CNF_AccountConfig.Accountingtype = 1 then 2
								        when TransactionType in (5, 17, 18, 20, 22, 30) and COA_CNF_AccountConfig.Accountingtype = 2 then 1
										when TransactionType in (7) and rr_data_revenue.RevenueAmount &lt; 0 and COA_CNF_AccountConfig.Accountingtype = 2 then 1
								        else COA_CNF_AccountConfig.Accountingtype
									end Accountingtype,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
								   RR_CNF_RevenueRecognitionRule.Percentage,
								   RR_CNF_RevenueRecognitionRule.Days,
								   RR_DATA_REVENUE.AttributeIDs

							from RR_DATA_REVENUE
									inner join rr_cnf_Product						ON ((RR_DATA_REVENUE.MATRIXCELLID = rr_cnf_Product.MATRIXCELLID) 
                                                      or (RR_DATA_REVENUE.MatrixSheetId = rr_cnf_Product.MatrixSheetId)
													  or (rr_cnf_product.Attributeid in (select top 1 Attributeid
																							from rr_cnf_product
																							where Attributeid in (select Value
																													from dbo.split((select rr.Attributeids
																																	from rr_data_revenue rr
																																	where rr.revenuerecognitiondataid = RR_DATA_REVENUE.revenuerecognitiondataid), '.')
																												   )
																					    )
															))
													  and rr_cnf_Product.Enabled = 1
									inner join RR_CNF_RevenueRecognitionRule		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_cnf_Product.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  
									INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
									INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
									INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 
									INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid

							where RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger IN (@OnMoneyCardCashOut)

							  and RR_CNF_RevenueRecognitionRule.Enabled = 1
							  and coa_cnf_account.Enabled = 1
							  and COA_CNF_AccountConfig.Enabled = 1
							  and ((TransactionType in (10, 20, 18, 22)) or (RR_DATA_REVENUE.transactionid in (select transactionid
																									 from data_transaction
																										Inner join data_saleitem   on data_saleitem.saleid = data_transaction.saleid
																									where data_transaction.transactiontype in (14)
																									  and data_saleitem.unitrecharge &lt;&gt; 0
																								 )
																))
							  and ((coa_cnf_accountConfig.Siteid = RR_DATA_REVENUE.SiteId) or (coa_cnf_accountConfig.Siteid is null))
							  and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
							  and COA_CNF_AccountConfig.RemainingValues &lt;&gt; 1
							  and RR_DATA_REVENUE.fcalcdate = @BatchDate
							  and RR_DATA_REVENUE.coaaccountid = @suspendid
						
					)p
					where RevenueAmount &lt;&gt; 0

				--Normal Transaction with Remaining Values
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[Saleitemid]
				   ,[MatrixCellid]
				   ,[MatrixCellCode]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays]
				   ,[AttributeIDs])
				   select *
				   from(
						select distinct coa_cnf_account.COAAccountId, 
								   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
								   RR_CNF_RevenueRecognitionRule.code,		   
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
								   COA_CNF_AccountConfig.COAAccountConfigId,
								   coa_cnf_account.COAAccountTypeId,
								   coa_cnf_account.Code as AccountCode,
								   RR_DATA_REVENUE.Transactionid as Transactionid,
								   RR_DATA_REVENUE.saleid as Saleid,
								   RR_DATA_REVENUE.SaleitemID as SaleitemID,
								   RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								   RR_DATA_REVENUE.MatrixcellCode as MatrixCode,
								   RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								   RR_DATA_REVENUE.Siteid as SiteID,
								   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								   RR_DATA_REVENUE.Workstationid as Workstationid,
								   RR_DATA_REVENUE.UserGroupid as UserGroupID,
								   RR_DATA_REVENUE.UserId as userID,
								   @BatchDate as BatchDate,
								   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
								        else DATA_Transaction.transactiondate
								   end as TransDate,
								   RR_DATA_REVENUE.Quantity as Quantity,
								   RR_DATA_REVENUE.GrossAmount as GrossAmount,
								   RR_DATA_REVENUE.NetAmount as NetAmount,
								   COA_CNF_AccountConfig.Price as ConfigPrice,
								   COA_CNF_AccountConfig.Percentage as ConfigPercentage,
								   COA_CNF_AccountConfig.RemainingValues,							 
								   ISNULL((RR_DATA_REVENUE.RevenueAmount - (select ISNULL(sum(revenueamount), 0)
								                            from RR_DATA_Revenue rr
												              where rr.saleitemid = RR_DATA_REVENUE.SaleitemID
												        and rr.COAAccountid not in (@SuspendID, @ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)
												 )
									), 0)
									as RevenueAmount,
								   case when TransactionType in (5, 17, 18, 20, 22, 30) and COA_CNF_AccountConfig.Accountingtype = 1 then 2
								        when TransactionType in (5, 17, 18, 20, 22, 30) and COA_CNF_AccountConfig.Accountingtype = 2 then 1
										when TransactionType in (7) and rr_data_revenue.RevenueAmount &lt; 0 and COA_CNF_AccountConfig.Accountingtype = 2 then 1
								        else COA_CNF_AccountConfig.Accountingtype
									end Accountingtype,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
								   RR_CNF_RevenueRecognitionRule.Percentage,
								   RR_CNF_RevenueRecognitionRule.Days,
								   RR_DATA_REVENUE.AttributeIDs

						from RR_DATA_REVENUE
									inner join rr_cnf_Product						ON ((RR_DATA_REVENUE.MATRIXCELLID = rr_cnf_Product.MATRIXCELLID) 
                                                      or (RR_DATA_REVENUE.MatrixSheetId = rr_cnf_Product.MatrixSheetId)
													  or (rr_cnf_product.Attributeid in (select top 1 Attributeid
																							from rr_cnf_product
																							where Attributeid in (select Value
																													from dbo.split((select rr.Attributeids
																																	from rr_data_revenue rr
																																	where rr.revenuerecognitiondataid = RR_DATA_REVENUE.revenuerecognitiondataid), '.')
																												   )
																					    )
															))
													  and rr_cnf_Product.Enabled = 1
								inner join RR_CNF_RevenueRecognitionRule		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_cnf_Product.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  
								INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
								INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
								INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 
								INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid

							where RR_CNF_RevenueRecognitionRule.Enabled = 1
							  and coa_cnf_account.Enabled = 1
							  and COA_CNF_AccountConfig.Enabled = 1
							  and TransactionType in (10, 20, 18, 22)
							  and ((coa_cnf_accountConfig.Siteid = RR_DATA_REVENUE.SiteId) or (coa_cnf_accountConfig.Siteid is null))
							  and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger IN (@OnMoneyCardCashOut)
							  and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
							  and COA_CNF_AccountConfig.RemainingValues = 1
							  and RR_DATA_REVENUE.fcalcdate = @BatchDate
							  and RR_DATA_REVENUE.coaaccountid = @suspendid
					)p
					where RevenueAmount &lt;&gt; 0

		
		exec otn_sp_RR_RevenueData_PaymentMethodTaxDiscounts @BatchDate, '10,', @OnMoneyCardCashOut, @RRTransDateType									

	end

END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_RR_RevenueData_OnChangeValiditydateTrigger]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_RR_RevenueData_OnChangeValiditydateTrigger
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>CREATE Procedure dbo.otn_sp_RR_RevenueData_OnChangeValiditydateTrigger
	@BatchDate Date,
	@RRTransDateType Integer
AS 
BEGIN

	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer
	Declare @ChangeValidityTrigger Integer = 18	

	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1

	BEGIN
		--Normal TicketExpired No Remaining Value
			 	INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[Ticketid]
				   ,[MatrixCellid]
				   ,[MatrixCellCode]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				   ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays]
				   ,[AttributeIDs])
				   select *
				   from(
				   select COA_CNF_AccountConfig.COAAccountId, 
												   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
												   RR_CNF_RevenueRecognitionRule.code,		   
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
												   COA_CNF_AccountConfig.COAAccountConfigId,
												   coa_cnf_account.COAAccountTypeId,
												   coa_cnf_account.Code as AccountCode,
												   p.Ticketid as Ticketid,
												   p.Matrixcellid as Matrixcell,
												   p.Code as MatrixCode,
												   p.MatrixSheetId as MatrixSheetID,
												   p.Siteid as SiteID,
												   @BatchDate as BatchDate,
												   p.ActiveTo,
												   1 as Quantity,
												   0 as GrossAmount,
												   0 as NetAmount,
												   COA_CNF_AccountConfig.Price as ConfigPrice,
												   COA_CNF_AccountConfig.Percentage as ConfigPercentage,
												   COA_CNF_AccountConfig.RemainingValues,									   
												p.RevenueAmount as revenueamount,
									
							COA_CNF_AccountConfig.AccountingType,
							RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
												   RR_CNF_RevenueRecognitionRule.Percentage,
												   RR_CNF_RevenueRecognitionRule.Days,
												   p.AttributeIDs

				  from RR_CNF_RevenueRecognitionRule
					   INNER JOIN RR_CNF_Product						ON RR_CNF_Product.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
					   INNER JOIN COA_CNF_AccountConfig					ON COA_CNF_AccountConfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId 
					   INNER JOIN COA_CNF_Account						on coa_cnf_account.COAAccountId = COA_CNF_AccountConfig.coaaccountid and  COA_CNF_Account.enabled = 1
					   INNER JOIN (select	distinct CNF_MatrixCell.matrixcellid, DATA_Ticket.price, DATA_Ticket.rawprice, DATA_Ticket.ticketid, CNF_MatrixCell.AttributeSetId, CNF_AttributeSet.AttributeIDs,
											CNF_MatrixCell.Code, CNF_MatrixCell.MatrixSheetId, DATA_Ticket.siteid, DAta_Ticket.ActiveTo, (data_ticket.price - data_ticket.taxes) NetPrice,
											OldTicket.TicketId OldTicketID, rr_data_revenue.RevenueAmount
											from DATA_Ticket
											INNER JOIN CNF_MatrixCell					on cnf_matrixcell.matrixcellid = data_ticket.matrixcellid
											INNER JOIN CNF_AttributeSet					on cnf_attributeset.AttributeSetId = CNF_MatrixCell.AttributeSetId
											INNER JOIN DATA_Transaction2Ticket			on data_transaction2ticket.ticketid = data_ticket.ticketid
											INNER JOIN DATA_Transaction					on data_transaction.transactionid = data_transaction2ticket.transactionid and DATA_Transaction.transactiontype = 115
											INNER JOIN DATA_TransactionItem				on Data_TransactionItem.transactionid = data_transaction.transactionid
											INNER JOIN data_Saleitem NewItem			on NewItem.saleitemid = Data_TransactionItem.saleitemid
											INNER JOIN data_saleitem OldItem			on OldItem.Saleitemid = NewItem.OrigSaleItemId	
											INNER JOIN data_ticket OldTicket			on OldTicket.Saleitemid = OldItem.SaleItemid
											INNER JOIN RR_DATA_Revenue					on rr_data_revenue.Ticketid = OldTicket.Ticketid													
										
											where DATA_Ticket.VoidType = 0
											and cast(data_ticket.activeto as date) = @batchDate
									)p  on						((p.matrixcellid   = rr_cnf_product.matrixcellid) or(p.matrixsheetid = rr_cnf_product.matrixsheetid)
																	or (rr_cnf_product.Attributeid in (select Value
																										from dbo.split((select Attributeids
																														from CNF_AttributeSet
																														where CNF_AttributeSet.AttributeSetId = p.AttributeSetId), '.')
																										)
																					    
															))
				where RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @ChangeValidityTrigger
				  and rr_cnf_revenuerecognitionRule.Enabled = 1
				  and COA_CNF_AccountConfig.Enabled = 1
				)p
				where RevenueAmount &lt;&gt; 0  



	end
 
END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_RR_RevenueData_batchJob]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_RR_RevenueData_batchJob
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>CREATE Procedure dbo.otn_sp_RR_RevenueData_batchJob	 
	@FromDate Date,
	@ToDate Date
AS 
BEGIN

	delete from rr_data_revenue
	where fcalcdate between @FromDate and @ToDate

	Declare @BatchDate Date
	Declare @RRTransDateType Integer

	Declare @SuspendRRRId Integer
	Declare @SuspendCOAAccountId Integer
	Declare @SuspendRRRCode varchar(10)
	Declare @SuspendRRCalcTypeTrigger Integer
	Declare @SuspendRRCalcTypeWhere Integer
	Declare @SuspendRRCalcTypeMethod Integer
	Declare @SuspendCOAAccountConfigId Integer
	Declare @SuspendCOAAccountTypeId Integer
	Declare @SuspendCOAAccountCode varchar(10)
	Declare @SuspendPercentage float
	Declare @SuspendDays Integer
	Declare @SuspendPrice float
	Declare @SuspendCOAAccount_Percentage Float
	Declare @SuspendRemainingValues Integer
	Declare @SuspendRRCOAAccountingType Integer
	Declare @SuspendAccountingType Integer

	Declare @PaymentRRRId Integer
	Declare @PaymentCOAAccountId Integer
	Declare @PaymentRRRCode varchar(10)
	Declare @PaymentRRCalcTypeTrigger Integer
	Declare @PaymentRRCalcTypeWhere Integer
	Declare @PaymentRRCalcTypeMethod Integer
	Declare @PaymentCOAAccountConfigId Integer
	Declare @PaymentCOAAccountTypeId Integer
	Declare @PaymentCOAAccountCode varchar(10)
	Declare @PaymentPercentage float
	Declare @PaymentDays Integer
	Declare @PaymentPrice float
	Declare @PaymentCOAAccount_Percentage Float
	Declare @PaymentRemainingValues Integer
	Declare @PaymentRRCOAAccountingType Integer
	Declare @PaymentAccountingType Integer


	Declare @TaxRRRId Integer
	Declare @TaxCOAAccountId Integer
	Declare @TaxRRRCode varchar(10)
	Declare @TaxRRCalcTypeTrigger Integer
	Declare @TaxRRCalcTypeWhere Integer
	Declare @TaxRRCalcTypeMethod Integer
	Declare @TaxCOAAccountConfigId Integer
	Declare @TaxCOAAccountTypeId Integer
	Declare @TaxCOAAccountCode varchar(10)
	Declare @TaxPercentage float
	Declare @TaxDays Integer
	Declare @TaxPrice float
	Declare @TaxCOAAccount_Percentage Float
	Declare @TaxRemainingValues Integer
	Declare @TaxRRCOAAccountingType Integer
	Declare @TaxAccountingType Integer


	Declare @DiscountRRRId Integer
	Declare @DiscountCOAAccountId Integer
	Declare @DiscountRRRCode varchar(10)
	Declare @DiscountRRCalcTypeTrigger Integer
	Declare @DiscountRRCalcTypeWhere Integer
	Declare @DiscountRRCalcTypeMethod Integer
	Declare @DiscountCOAAccountConfigId Integer
	Declare @DiscountCOAAccountTypeId Integer
	Declare @DiscountCOAAccountCode varchar(10)
	Declare @DiscountPercentage float
	Declare @DiscountDays Integer
	Declare @DiscountPrice float
	Declare @DiscountCOAAccount_Percentage Float
	Declare @DiscountRemainingValues Integer
	Declare @DiscountRRCOAAccountingType Integer
	Declare @DiscountAccountingType Integer

	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer

	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1


	select @RRTransDateType = RRTransDateType
      from cnf_system

--Begin Move Transactions to Suspend Account
	select TOP 1 @SuspendRRRId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
			@SuspendRRRCode = RR_CNF_RevenueRecognitionRule.code,
			@SuspendRRCalcTypeTrigger = RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
			@SuspendRRCalcTypeWhere = RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
			@SuspendRRCalcTypeMethod = RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
			@SuspendCOAAccountConfigId = COA_CNF_AccountConfig.COAAccountConfigId,
			@SuspendCOAAccountTypeId = COA_CNF_AccountType.COAAccountTypeId,
			@SuspendCOAAccountId = coa_cnf_account.COAAccountId,
			@SuspendPercentage = RR_CNF_RevenueRecognitionRule.Percentage,
			@SuspendDays = RR_CNF_RevenueRecognitionRule.Days,
			@SuspendPrice = COA_CNF_AccountConfig.Price,
			@SuspendCOAAccount_Percentage = COA_CNF_AccountConfig.Percentage,
			@SuspendRemainingValues = COA_CNF_AccountConfig.RemainingValues,
			@SuspendCOAAccountCode = coa_cnf_account.Code,
			@SuspendRRCOAAccountingType = COA_CNF_AccountConfig.AccountingType
	from coa_cnf_account
		INNER JOIN COA_CNF_AccountType				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
		INNER JOIN COA_CNF_AccountConfig			on COA_CNF_AccountConfig.COAAccountId = coa_cnf_account.COAAccountId
		INNER JOIN RR_CNF_RevenueRecognitionRule	on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId
	where coa_cnf_account.COAAccountID = @SuspendID
	 order by RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId

	select TOP 1 @PaymentRRRId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
			@PaymentRRRCode = RR_CNF_RevenueRecognitionRule.code,
			@PaymentRRCalcTypeTrigger = RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
			@PaymentRRCalcTypeWhere = RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
			@PaymentRRCalcTypeMethod = RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
			@PaymentCOAAccountConfigId = COA_CNF_AccountConfig.COAAccountConfigId,
			@PaymentCOAAccountTypeId = COA_CNF_AccountType.COAAccountTypeId,
			@PaymentCOAAccountId = coa_cnf_account.COAAccountId,
			@PaymentPercentage = RR_CNF_RevenueRecognitionRule.Percentage,
			@PaymentDays = RR_CNF_RevenueRecognitionRule.Days,
			@PaymentPrice = COA_CNF_AccountConfig.Price,
			@PaymentCOAAccount_Percentage = COA_CNF_AccountConfig.Percentage,
			@PaymentRemainingValues = COA_CNF_AccountConfig.RemainingValues,
			@PaymentCOAAccountCode = coa_cnf_account.Code,
			@PaymentRRCOAAccountingType = COA_CNF_AccountConfig.AccountingType
	from coa_cnf_account
		INNER JOIN COA_CNF_AccountType				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
		INNER JOIN COA_CNF_AccountConfig			on COA_CNF_AccountConfig.COAAccountId = coa_cnf_account.COAAccountId
		INNER JOIN RR_CNF_RevenueRecognitionRule	on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId
	where coa_cnf_account.COAAccountID = @ACCPaymentMethod
	 order by RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId

	select TOP 1 @TaxRRRId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
			@TaxRRRCode = RR_CNF_RevenueRecognitionRule.code,
			@TaxRRCalcTypeTrigger = RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
			@TaxRRCalcTypeWhere = RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
			@TaxRRCalcTypeMethod = RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
			@TaxCOAAccountConfigId = COA_CNF_AccountConfig.COAAccountConfigId,
			@TaxCOAAccountTypeId = COA_CNF_AccountType.COAAccountTypeId,
			@TaxCOAAccountId = coa_cnf_account.COAAccountId,
			@TaxPercentage = RR_CNF_RevenueRecognitionRule.Percentage,
			@TaxDays = RR_CNF_RevenueRecognitionRule.Days,
			@TaxPrice = COA_CNF_AccountConfig.Price,
			@TaxCOAAccount_Percentage = COA_CNF_AccountConfig.Percentage,
			@TaxRemainingValues = COA_CNF_AccountConfig.RemainingValues,
			@TaxCOAAccountCode = coa_cnf_account.Code,
			@TaxRRCOAAccountingType = COA_CNF_AccountConfig.AccountingType
	from coa_cnf_account
		INNER JOIN COA_CNF_AccountType				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
		INNER JOIN COA_CNF_AccountConfig			on COA_CNF_AccountConfig.COAAccountId = coa_cnf_account.COAAccountId
		INNER JOIN RR_CNF_RevenueRecognitionRule	on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId
	where coa_cnf_account.COAAccountID = @TaxAccountID
	 order by RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId

	select TOP 1 @DiscountRRRId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
			@DiscountRRRCode = RR_CNF_RevenueRecognitionRule.code,
			@DiscountRRCalcTypeTrigger = RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
			@DiscountRRCalcTypeWhere = RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
			@DiscountRRCalcTypeMethod = RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
			@DiscountCOAAccountConfigId = COA_CNF_AccountConfig.COAAccountConfigId,
			@DiscountCOAAccountTypeId = COA_CNF_AccountType.COAAccountTypeId,
			@DiscountCOAAccountId = coa_cnf_account.COAAccountId,
			@DiscountPercentage = RR_CNF_RevenueRecognitionRule.Percentage,
			@DiscountDays = RR_CNF_RevenueRecognitionRule.Days,
			@DiscountPrice = COA_CNF_AccountConfig.Price,
			@DiscountCOAAccount_Percentage = COA_CNF_AccountConfig.Percentage,
			@DiscountRemainingValues = COA_CNF_AccountConfig.RemainingValues,
			@DiscountCOAAccountCode = coa_cnf_account.Code,
			@DiscountRRCOAAccountingType = COA_CNF_AccountConfig.AccountingType
	from coa_cnf_account
		INNER JOIN COA_CNF_AccountType				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
		INNER JOIN COA_CNF_AccountConfig			on COA_CNF_AccountConfig.COAAccountId = coa_cnf_account.COAAccountId
		INNER JOIN RR_CNF_RevenueRecognitionRule	on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId
	where coa_cnf_account.COAAccountID = @DiscountAccountID
	 order by RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId

	Declare @Temp table (BatchDate date)

	;with dates_CTE (date) as (
			select @FromDate 
		Union ALL
			select DATEADD(day, 1, date)
			from dates_CTE
			where date &lt; @ToDate
	) 
	INSERT INTO @Temp (
	BatchDate
	) 
	select *
	from dates_CTE 

	DECLARE date_Cursor CURSOR LOCAL FOR
				select * from @Temp

	OPEN date_Cursor

	FETCH NEXT FROM date_Cursor INTO
		@BatchDate

	WHILE @@FETCH_STATUS = 0
	BEGIN

				INSERT INTO [dbo].[RR_DATA_Revenue]
								([COAAccountId]
								,[RevenueRecognitionRuleId]
								,[RRCode]
								,[RRCalcTypeWhere]
								,[RRCalcTypeMethod]
								,[COAAccountConfigId]
								,[COAAccountType]
								,[COAAccountCode]
								,[TransactionId]
								,[SaleId]
								,[SaleItemId]
								,[MatrixCellId]
								,[MatrixCellCode]
								,[MatrixSheetID]
								,[SiteId]
								,[OperatingAreaId]
								,[WorkstationId]
								,[UserGroupId]
								,[UserId]
								,[FCalcDate]
								,[FRevenueDate]
								,[Quantity]
								,[UnitAmount]
								,[GrossAmount]
								,[NetAmount]
								,[Price]
								,[Percentage]
								,[RemaningValues]
								,[RevenueAmount]
								,[AccountingType]
								,[RRCalcTypeTrigger]
								,[RRPercentage]
								,[RRDays]
								,[AttributeIDS])
						select @SuspendCOAAccountId,
								@SuspendRRRId,
								@SuspendRRRCode,
								@SuspendRRCalcTypeWhere,
								@SuspendRRCalcTypeMethod,
								@SuspendCOAAccountConfigId,
								@SuspendCOAAccountTypeId,
								@SuspendCOAAccountCode,
								data_transaction.transactionid, 
								data_transaction.saleid,
								DATA_TransactionItem.saleitemid,
								DATA_SaleItem.Matrixcellid,
								CNF_MatrixCell.Code,
								CNF_MatrixCell.MatrixSheetid,
								data_transaction.Siteid,
								data_transaction.OperatingAreaId,
								data_transaction.Workstationid,
								data_transaction.UserGroupid,
								data_transaction.UserId,
								@BatchDate,
								CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
									 else data_transaction.TransactionDate
								end TransactionDate,
								Coalesce(DATA_TransactionItem.Quantity, 1),
								DATA_SaleItem.UnitPrice,
								case when isnull(DATA_TransactionItem.TotalAmount, 0) &lt;&gt; 0 then DATA_TransactionItem.TotalAmount
									when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
									else DATA_Sale.TotalAmount
								end,
								case when isnull((DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes)
									when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
									else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
								end as NetAmount,
								@SuspendPrice,
								@SuspendCOAAccount_Percentage,
								@SuspendRemainingValues,
								case    when (data_saleitem.ProductTaxType &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice ) * DATA_SaleItem.Quantity)
										when (data_saleitem.ProductTaxType = 1) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice - DATA_SaleItem.unittaxes) * DATA_SaleItem.Quantity)
										when (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 then 0				
										when isnull((data_transaction.TotalAmount), 0) &lt;&gt; 0 then data_transaction.TotalAmount
										when isnull((DATA_Sale.TotalAmount), 0) &lt;&gt; 0 then DATA_Sale.TotalAmount
										else (data_transaction.Revenue)
								end,
								case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
										when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
										when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 1
										when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 2
										else @SuspendRRCOAAccountingType
								end Accountingtype,
								@SuspendRRCalcTypeTrigger,
								@SuspendPercentage,
								@SuspendDays,
								CNF_AttributeSet.Attributeids
	   
						from DATA_Sale
							inner join data_transaction			on data_transaction.TransactionId = DATA_Sale.PaidTransactionId
							left join DATA_TransactionItem		on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
							left join DATA_SaleItem			    on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
							left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
							left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

						where DATA_Sale.Paid = 1
							and data_transaction.transactiontype in (14)
							and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
							   OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
							and data_transaction.transactionid in (select transactionid
																	from data_payment
																	where PaymentStatus = 1
																	and PaymentAmount &lt;&gt; 0
																)

				INSERT INTO [dbo].[RR_DATA_Revenue]
								([COAAccountId]
								,[RevenueRecognitionRuleId]
								,[RRCode]
								,[RRCalcTypeWhere]
								,[RRCalcTypeMethod]
								,[COAAccountConfigId]
								,[COAAccountType]
								,[COAAccountCode]
								,[TransactionId]
								,[SaleId]
								,[SaleItemId]
								,[MatrixCellId]
								,[MatrixCellCode]
								,[MatrixSheetID]
								,[SiteId]
								,[OperatingAreaId]
								,[WorkstationId]
								,[UserGroupId]
								,[UserId]
								,[FCalcDate]
								,[FRevenueDate]
								,[Quantity]
								,[UnitAmount]
								,[GrossAmount]
								,[NetAmount]
								,[Price]
								,[Percentage]
								,[RemaningValues]
								,[RevenueAmount]
								,[AccountingType]
								,[RRCalcTypeTrigger]
								,[RRPercentage]
								,[RRDays]
								,[AttributeIDS])
						select @SuspendCOAAccountId,
								@SuspendRRRId,
								@SuspendRRRCode,
								@SuspendRRCalcTypeWhere,
								@SuspendRRCalcTypeMethod,
								@SuspendCOAAccountConfigId,
								@SuspendCOAAccountTypeId,
								@SuspendCOAAccountCode,
								data_transaction.transactionid, 
								data_transaction.saleid,
								DATA_TransactionItem.saleitemid,
								DATA_SaleItem.Matrixcellid,
								CNF_MatrixCell.Code,
								CNF_MatrixCell.MatrixSheetid,
								data_transaction.Siteid,
								data_transaction.OperatingAreaId,
								data_transaction.Workstationid,
								data_transaction.UserGroupid,
								data_transaction.UserId,
								@BatchDate,
								CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
									 else data_transaction.TransactionDate
								end TransactionDate,
								Coalesce(DATA_TransactionItem.Quantity, 1),
								DATA_SaleItem.UnitPrice,
								case when isnull(DATA_TransactionItem.TotalAmount, 0) &lt;&gt; 0 then DATA_TransactionItem.TotalAmount
									when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
									else DATA_Sale.TotalAmount
								end,
								case when isnull((DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes)
									when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
									else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
								end as NetAmount,
								@SuspendPrice,
								@SuspendCOAAccount_Percentage,
								@SuspendRemainingValues,
								DATA_SaleItem.UnitRecharge * data_saleitem.Quantity,
								case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
										when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
										when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 1
										when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 2
										else @SuspendRRCOAAccountingType
								end Accountingtype,
								@SuspendRRCalcTypeTrigger,
								@SuspendPercentage,
								@SuspendDays,
								CNF_AttributeSet.Attributeids
	   
						from DATA_Sale
							inner join data_transaction			on data_transaction.TransactionId = DATA_Sale.PaidTransactionId
							left join DATA_TransactionItem		on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
							left join DATA_SaleItem			    on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
							left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
							left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

		where DATA_Sale.Paid = 1
			and data_transaction.transactiontype in (14, 16, 39)
			and DATA_SaleItem.UnitRecharge &lt;&gt; 0
			and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
			   OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
			and data_transaction.transactionid in (select transactionid
													from data_payment
													where PaymentStatus = 1
													and PaymentAmount &lt;&gt; 0
												)

					INSERT INTO [dbo].[RR_DATA_Revenue]
								([COAAccountId]
								,[RevenueRecognitionRuleId]
								,[RRCode]
								,[RRCalcTypeWhere]
								,[RRCalcTypeMethod]
								,[COAAccountConfigId]
								,[COAAccountType]
								,[COAAccountCode]
								,[TransactionId]
								,[SaleId]
								,[SaleItemId]
								,[MatrixCellId]
								,[MatrixCellCode]
								,[MatrixSheetID]
								,[SiteId]
								,[OperatingAreaId]
								,[WorkstationId]
								,[UserGroupId]
								,[UserId]
								,[FCalcDate]
								,[FRevenueDate]
								,[Quantity]
								,[UnitAmount]
								,[GrossAmount]
								,[NetAmount]
								,[Price]
								,[Percentage]
								,[RemaningValues]
								,[RevenueAmount]
								,[AccountingType]
								,[RRCalcTypeTrigger]
								,[RRPercentage]
								,[RRDays]
								,[AttributeIDS])
						select @SuspendCOAAccountId,
								@SuspendRRRId,
								@SuspendRRRCode,
								@SuspendRRCalcTypeWhere,
								@SuspendRRCalcTypeMethod,
								@SuspendCOAAccountConfigId,
								@SuspendCOAAccountTypeId,
								@SuspendCOAAccountCode,
								data_transaction.transactionid, 
								data_transaction.saleid,
								DATA_TransactionItem.saleitemid,
								DATA_SaleItem.Matrixcellid,
								CNF_MatrixCell.Code,
								CNF_MatrixCell.MatrixSheetid,
								data_transaction.Siteid,
								data_transaction.OperatingAreaId,
								data_transaction.Workstationid,
								data_transaction.UserGroupid,
								data_transaction.UserId,
								@BatchDate,
								CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
									 else data_transaction.TransactionDate
								end TransactionDate,
								Coalesce(DATA_TransactionItem.Quantity, 1),
								DATA_SaleItem.UnitPrice,
								case when isnull(DATA_TransactionItem.TotalAmount, 0) &lt;&gt; 0 then DATA_TransactionItem.TotalAmount
									when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
									else DATA_Sale.TotalAmount
								end,
								case when isnull((DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes)
									when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
									else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
								end as NetAmount,
								@SuspendPrice,
								@SuspendCOAAccount_Percentage,
								@SuspendRemainingValues,
								case    when (data_saleitem.ProductTaxType &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) 
												  and (isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0) 
													   and (((select discountamount from data_saleitemrule where saleitemid = DATA_SaleItem.saleitemid) &gt; 0) and (data_transaction.transactiontype in (7, 20, 22)))							
											then ((DATA_SaleItem.UnitRawPrice + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)

				        when (data_saleitem.ProductTaxType &lt;&gt; 1) and (data_transaction.transactiontype in (18, 20, 22)) and (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitRawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitRawPrice  + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)
						when (data_saleitem.ProductTaxType = 1) and (data_transaction.transactiontype in (18, 20, 22)) and isnull((DATA_SaleItem.UnitRawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitRawPrice - DATA_SaleItem.unittaxes + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)

										when (data_saleitem.ProductTaxType &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice  + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)
										when (data_saleitem.ProductTaxType = 1) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice - DATA_SaleItem.unittaxes + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)

										when (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 and data_saleitem.unitRecharge = 0 then 0
										when (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 and data_saleitem.unitRecharge &lt;&gt; 0 then data_saleitem.unitRecharge
										when isnull((data_transaction.TotalAmount), 0) &lt;&gt; 0 then data_transaction.TotalAmount
										when isnull((DATA_Sale.TotalAmount), 0) &lt;&gt; 0 then DATA_Sale.TotalAmount
										else (data_transaction.Revenue)
								end,
								case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
										when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
										when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 1
										when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 2
										else @SuspendRRCOAAccountingType
								end Accountingtype,
								@SuspendRRCalcTypeTrigger,
								@SuspendPercentage,
								@SuspendDays,
								CNF_AttributeSet.Attributeids
	   
						from DATA_Sale
							inner join data_transaction			on data_transaction.TransactionId = ISNULL(data_sale.voidtransactionid, DATA_Sale.PaidTransactionId)
							left join DATA_TransactionItem		on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
							left join DATA_SaleItem			    on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
							left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
							left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

						where DATA_Sale.Paid = 1
							and data_transaction.transactiontype not in (6, 8, 10, 12, 14, 16, 42, 43, 31, 39, 48, 49, 52, 46, 47)
							and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
							   OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
							and data_transaction.transactionid in (select transactionid
																	from data_payment
																	where PaymentStatus = 1
																	and PaymentAmount &lt;&gt; 0
																)

						INSERT INTO [dbo].[RR_DATA_Revenue]
										([COAAccountId]
										,[RevenueRecognitionRuleId]
										,[RRCode]
										,[RRCalcTypeWhere]
										,[RRCalcTypeMethod]
										,[COAAccountConfigId]
										,[COAAccountType]
										,[COAAccountCode]
										,[TransactionId]
										,[SaleId]
										,[SiteId]
										,[OperatingAreaId]
										,[WorkstationId]
										,[UserGroupId]
										,[UserId]
										,[FCalcDate]
										,[FRevenueDate]
										,[Quantity]
										,[GrossAmount]
										,[NetAmount]
										,[Price]
										,[Percentage]
										,[RemaningValues]
										,[RevenueAmount]
										,[AccountingType]
										,[RRCalcTypeTrigger]
										,[RRPercentage]
										,[RRDays])
								select @SuspendCOAAccountId,
										@SuspendRRRId,
										@SuspendRRRCode,
										@SuspendRRCalcTypeWhere,
										@SuspendRRCalcTypeMethod,
										@SuspendCOAAccountConfigId,
										@SuspendCOAAccountTypeId,
										@SuspendCOAAccountCode,
										data_transaction.transactionid, 
										data_transaction.saleid,
										data_transaction.Siteid,
										data_transaction.OperatingAreaId,
										data_transaction.Workstationid,
										data_transaction.UserGroupid,
										data_transaction.UserId,
										@BatchDate,
										CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
											 else data_transaction.TransactionDate
										end TransactionDate,
										0 Quantity,
										data_transaction.revenue TotalAmount,
										data_transaction.revenue NetAmount,
										@SuspendPrice,
										@SuspendCOAAccount_Percentage,
										@SuspendRemainingValues,
										p.Amount,
										@SuspendRRCOAAccountingType,
										@SuspendRRCalcTypeTrigger,
										@SuspendPercentage,
										@SuspendDays
	   
						from DATA_Sale
							inner join data_transaction			on data_transaction.saleid = data_sale.saleid
							left  join  (select settletransactionid, sum(data_payment.paymentamount) as amount
											from data_paymentcredit
												INNER JOIN DATA_Payment						on data_payment.paymentid = data_paymentcredit.paymentid
												INNER JOIN DATA_Transaction					on data_transaction.transactionid = data_paymentcredit.SettleTransactionId
											where ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
												  OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
											group by settletransactionid)p					on p.SettleTransactionId = data_transaction.transactionid

						where DATA_Sale.Paid = 1
							and data_transaction.transactiontype in (6)
							and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
							   OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))


					INSERT INTO [dbo].[RR_DATA_Revenue]
								([COAAccountId]
								,[RevenueRecognitionRuleId]
								,[RRCode]
								,[RRCalcTypeWhere]
								,[RRCalcTypeMethod]
								,[COAAccountConfigId]
								,[COAAccountType]
								,[COAAccountCode]
								,[TransactionId]
								,[SaleId]
								,[SaleItemId]
								,[MatrixCellId]
								,[MatrixCellCode]
								,[MatrixSheetID]
								,[SiteId]
								,[OperatingAreaId]
								,[WorkstationId]
								,[UserGroupId]
								,[UserId]
								,[FCalcDate]
								,[FRevenueDate]
								,[Quantity]
								,[UnitAmount]
								,[GrossAmount]
								,[NetAmount]
								,[Price]
								,[Percentage]
								,[RemaningValues]
								,[RevenueAmount]
								,[AccountingType]
								,[RRCalcTypeTrigger]
								,[RRPercentage]
								,[RRDays]
								,[AttributeIDS])
						select @SuspendCOAAccountId,
								@SuspendRRRId,
								@SuspendRRRCode,
								@SuspendRRCalcTypeWhere,
								@SuspendRRCalcTypeMethod,
								@SuspendCOAAccountConfigId,
								@SuspendCOAAccountTypeId,
								@SuspendCOAAccountCode,
								data_transaction.transactionid, 
								data_transaction.saleid,
								DATA_SaleItem.saleitemid,
								DATA_SaleItem.Matrixcellid,
								CNF_MatrixCell.Code,
								CNF_MatrixCell.MatrixSheetid,
								data_transaction.Siteid,
								data_transaction.OperatingAreaId,
								data_transaction.Workstationid,
								data_transaction.UserGroupid,
								data_transaction.UserId,
								@BatchDate,
								CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
									 else data_transaction.TransactionDate
								end TransactionDate,
								Coalesce(DATA_SaleItem.Quantity, 1),
								DATA_SaleItem.UnitPrice,
								case when isnull(DATA_SaleItem.TotalAmount, 0) &lt;&gt; 0 then DATA_SaleItem.TotalAmount
									when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
									else DATA_Sale.TotalAmount
								end,
								case when isnull((DATA_SaleItem.TotalAmount - DATA_SaleItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_SaleItem.TotalAmount - DATA_SaleItem.TotalTaxes)
									when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
									else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
								end as NetAmount,
								@SuspendPrice,
								@SuspendCOAAccount_Percentage,
								@SuspendRemainingValues,
								case    when (data_saleitem.ProductTaxType &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) 
												  and (isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0) 
													   and (((select discountamount from data_saleitemrule where saleitemid = DATA_SaleItem.saleitemid) &gt; 0) and (data_transaction.transactiontype in (7, 20, 22)))							
											then ((DATA_SaleItem.UnitRawPrice + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)


										when (data_saleitem.ProductTaxType &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice  + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)
										when (data_saleitem.ProductTaxType = 1) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice - DATA_SaleItem.unittaxes + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)
										when (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 then 0
										when (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 and data_saleitem.unitRecharge &lt;&gt; 0 then data_saleitem.unitRecharge
										when isnull((data_transaction.TotalAmount), 0) &lt;&gt; 0 then data_transaction.TotalAmount
										when isnull((DATA_Sale.TotalAmount), 0) &lt;&gt; 0 then DATA_Sale.TotalAmount
										else (data_transaction.Revenue)
								end,
								case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
										when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
										when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 1
										when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 2
										else @SuspendRRCOAAccountingType
								end Accountingtype,
								@SuspendRRCalcTypeTrigger,
								@SuspendPercentage,
								@SuspendDays,
								CNF_AttributeSet.Attributeids
	   
						from DATA_Sale
							inner join data_transaction			on data_transaction.saleid = data_sale.saleid
							left join DATA_SaleItem			    on DATA_SaleItem.saleid = DATA_Transaction.saleid
							left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
							left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

						where DATA_Sale.Paid = 1
							and data_transaction.transactiontype in (46, 47)
							and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
							   OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
							and data_transaction.transactionid in (select transactionid
																	from data_payment
																	where PaymentStatus = 1
																	and PaymentAmount &lt;&gt; 0
																)


					INSERT INTO [dbo].[RR_DATA_Revenue]
								([COAAccountId]
								,[RevenueRecognitionRuleId]
								,[RRCode]
								,[RRCalcTypeWhere]
								,[RRCalcTypeMethod]
								,[COAAccountConfigId]
								,[COAAccountType]
								,[COAAccountCode]
								,[TransactionId]
								,[SaleId]
								,[SaleItemId]
								,[MatrixCellId]
								,[MatrixCellCode]
								,[MatrixSheetID]
								,[SiteId]
								,[OperatingAreaId]
								,[WorkstationId]
								,[UserGroupId]
								,[UserId]
								,[FCalcDate]
								,[FRevenueDate]
								,[Quantity]
								,[UnitAmount]
								,[GrossAmount]
								,[NetAmount]
								,[Price]
								,[Percentage]
								,[RemaningValues]
								,[RevenueAmount]
								,[AccountingType]
								,[RRCalcTypeTrigger]
								,[RRPercentage]
								,[RRDays]
								,[AttributeIDS])
						select @SuspendCOAAccountId,
								@SuspendRRRId,
								@SuspendRRRCode,
								@SuspendRRCalcTypeWhere,
								@SuspendRRCalcTypeMethod,
								@SuspendCOAAccountConfigId,
								@SuspendCOAAccountTypeId,
								@SuspendCOAAccountCode,
								data_transaction.transactionid, 
								data_transaction.saleid,
								DATA_TransactionItem.saleitemid,
								DATA_SaleItem.Matrixcellid,
								CNF_MatrixCell.Code,
								CNF_MatrixCell.MatrixSheetid,
								data_transaction.Siteid,
								data_transaction.OperatingAreaId,
								data_transaction.Workstationid,
								data_transaction.UserGroupid,
								data_transaction.UserId,
								@BatchDate,
								CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
									 else data_transaction.TransactionDate
								end TransactionDate,
								Coalesce(DATA_TransactionItem.Quantity, 1),
								DATA_SaleItem.UnitPrice,
								case when isnull(DATA_TransactionItem.TotalAmount, 0) &lt;&gt; 0 then DATA_TransactionItem.TotalAmount
									when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
									else DATA_Sale.TotalAmount
								end,
								case when isnull((DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes)
									when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
									else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
								end as NetAmount,
								@SuspendPrice,
								@SuspendCOAAccount_Percentage,
								@SuspendRemainingValues,
								DATA_SaleItem.Unitrecharge,
								case    when TransactionType in (5, 17, 8, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
										when TransactionType in (5, 17, 8, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
										when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 2
										when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 1
										else @SuspendRRCOAAccountingType
								end Accountingtype,
								@SuspendRRCalcTypeTrigger,
								@SuspendPercentage,
								@SuspendDays,
								CNF_AttributeSet.Attributeids
	   
						from DATA_Sale
							inner join data_transaction			on data_transaction.TransactionId = ISNULL(data_sale.voidtransactionid, DATA_Sale.PaidTransactionId)
							left join DATA_TransactionItem		on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
							left join DATA_SaleItem			    on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
							left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
							left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

						where DATA_Sale.Paid = 1
							and data_transaction.transactiontype in (10, 42, 43, 49)
							and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
							   OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
							and data_transaction.transactionid in (select transactionid
																	from data_payment
																	where PaymentStatus = 1
																	and PaymentAmount &lt;&gt; 0
																)
			
				INSERT INTO [dbo].[RR_DATA_Revenue]
								([COAAccountId]
								,[RevenueRecognitionRuleId]
								,[RRCode]
								,[RRCalcTypeWhere]
								,[RRCalcTypeMethod]
								,[COAAccountConfigId]
								,[COAAccountType]
								,[COAAccountCode]
								,[TransactionId]
								,[SaleId]
								,[SaleItemId]
								,[MatrixCellId]
								,[MatrixCellCode]
								,[MatrixSheetID]
								,[SiteId]
								,[OperatingAreaId]
								,[WorkstationId]
								,[UserGroupId]
								,[UserId]
								,[FCalcDate]
								,[FRevenueDate]
								,[Quantity]
								,[UnitAmount]
								,[GrossAmount]
								,[NetAmount]
								,[Price]
								,[Percentage]
								,[RemaningValues]
								,[RevenueAmount]
								,[AccountingType]
								,[RRCalcTypeTrigger]
								,[RRPercentage]
								,[RRDays]
								,[AttributeIDS])
						select @SuspendCOAAccountId,
								@SuspendRRRId,
								@SuspendRRRCode,
								@SuspendRRCalcTypeWhere,
								@SuspendRRCalcTypeMethod,
								@SuspendCOAAccountConfigId,
								@SuspendCOAAccountTypeId,
								@SuspendCOAAccountCode,
								data_transaction.transactionid, 
								data_transaction.saleid,
								DATA_TransactionItem.saleitemid,
								DATA_SaleItem.Matrixcellid,
								CNF_MatrixCell.Code,
								CNF_MatrixCell.MatrixSheetid,
								data_transaction.Siteid,
								data_transaction.OperatingAreaId,
								data_transaction.Workstationid,
								data_transaction.UserGroupid,
								data_transaction.UserId,
								@BatchDate,
								CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
									 else data_transaction.TransactionDate
								end TransactionDate,
								Coalesce(DATA_TransactionItem.Quantity, 1),
								DATA_SaleItem.UnitPrice,
								case when isnull(DATA_TransactionItem.TotalAmount, 0) &lt;&gt; 0 then DATA_TransactionItem.TotalAmount
									when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
									else DATA_Sale.TotalAmount
								end,
								case when isnull((DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes)
									when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
									else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
								end as NetAmount,
								@SuspendPrice,
								@SuspendCOAAccount_Percentage,
								@SuspendRemainingValues,
								ABS(DATA_SaleItem.Unitrecharge),
								case    when TransactionType in (5, 17, 8, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
										when TransactionType in (5, 17, 8, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
										when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 2
										when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 1
										else @SuspendRRCOAAccountingType
								end Accountingtype,
								@SuspendRRCalcTypeTrigger,
								@SuspendPercentage,
								@SuspendDays,
								CNF_AttributeSet.Attributeids
	   
						from DATA_Sale
							inner join data_transaction			on data_transaction.TransactionId = ISNULL(data_sale.voidtransactionid, DATA_Sale.PaidTransactionId)
							left join DATA_TransactionItem		on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
							left join DATA_SaleItem			    on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
							left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
							left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

						where DATA_Sale.Paid = 1
							and data_transaction.transactiontype in (31, 48, 52)
							and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
							   OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
							and data_transaction.transactionid in (select transactionid
																	from data_payment
																	where PaymentStatus = 1
																	and PaymentAmount &lt;&gt; 0
																   )


					INSERT INTO [dbo].[RR_DATA_Revenue]
										([COAAccountId]
										,[RevenueRecognitionRuleId]
										,[RRCode]
										,[RRCalcTypeWhere]
										,[RRCalcTypeMethod]
										,[COAAccountConfigId]
										,[COAAccountType]
										,[COAAccountCode]
										,[TransactionId]
										,[SaleId]
										,[SaleItemId]
										,[MatrixCellId]
										,[MatrixCellCode]
										,[MatrixSheetID]
										,[SiteId]
										,[OperatingAreaId]
										,[WorkstationId]
										,[UserGroupId]
										,[UserId]
										,[FCalcDate]
										,[FRevenueDate]
										,[Quantity]
										,[UnitAmount]
										,[GrossAmount]
										,[NetAmount]
										,[Price]
										,[Percentage]
										,[RemaningValues]
										,[RevenueAmount]
										,[AccountingType]
										,[RRCalcTypeTrigger]
										,[RRPercentage]
										,[RRDays]
										,[AttributeIDS])
								select @SuspendCOAAccountId,
										@SuspendRRRId,
										@SuspendRRRCode,
										@SuspendRRCalcTypeWhere,
										@SuspendRRCalcTypeMethod,
										@SuspendCOAAccountConfigId,
										@SuspendCOAAccountTypeId,
										@SuspendCOAAccountCode,
										data_transaction.transactionid, 
										data_transaction.saleid,
										DATA_TransactionItem.saleitemid,
										DATA_SaleItem.Matrixcellid,
										CNF_MatrixCell.Code,
										CNF_MatrixCell.MatrixSheetid,
										data_transaction.Siteid,
										data_transaction.OperatingAreaId,
										data_transaction.Workstationid,
										data_transaction.UserGroupid,
										data_transaction.UserId,
										@BatchDate,
										CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
											 else data_transaction.TransactionDate
										end TransactionDate,
										Coalesce(DATA_TransactionItem.Quantity, 1),
										DATA_SaleItem.UnitPrice,
										case when isnull(DATA_TransactionItem.TotalAmount, 0) &lt;&gt; 0 then DATA_TransactionItem.TotalAmount
											when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
											else DATA_Sale.TotalAmount
										end,
										case when isnull((DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes)
											when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
											else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
										end as NetAmount,
										@SuspendPrice,
										@SuspendCOAAccount_Percentage,
										@SuspendRemainingValues,
										case when (data_saleitem.ProductTaxType &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice + DATA_SaleItem.unittaxes) * DATA_SaleItem.Quantity)
											 when (data_saleitem.ProductTaxType = 1) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice) * DATA_SaleItem.Quantity)
											 when (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 then 0
											 when isnull((data_transaction.TotalAmount), 0) &lt;&gt; 0 then data_transaction.TotalAmount
											 when isnull((DATA_Sale.TotalAmount), 0) &lt;&gt; 0 then DATA_Sale.TotalAmount
											 else (data_transaction.Revenue)
										end,
										case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
												when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
												when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 2
												when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 1
												else @SuspendRRCOAAccountingType
										end Accountingtype,
										@SuspendRRCalcTypeTrigger,
										@SuspendPercentage,
										@SuspendDays,
										CNF_AttributeSet.Attributeids
	   
								from DATA_Sale
									inner join data_transaction			on data_transaction.Saleid = DATA_Sale.Saleid
									left join DATA_TransactionItem		on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
									left join DATA_SaleItem			    on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
									left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
									left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

								where data_transaction.transactiontype in (8)
									and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
										OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
									and data_transaction.transactionid in (select transactionid
																			from data_payment
																			where PaymentStatus = 1
																			and PaymentAmount &lt;&gt; 0
																		)

							INSERT INTO [dbo].[RR_DATA_Revenue]
										([COAAccountId]
										,[RevenueRecognitionRuleId]
										,[RRCode]
										,[RRCalcTypeWhere]
										,[RRCalcTypeMethod]
										,[COAAccountConfigId]
										,[COAAccountType]
										,[COAAccountCode]
										,[TransactionId]
										,[SaleId]
										,[SiteId]
										,[OperatingAreaId]
										,[WorkstationId]
										,[UserGroupId]
										,[UserId]
										,[FCalcDate]
										,[FRevenueDate]
										,[Quantity]
										,[GrossAmount]
										,[NetAmount]
										,[Price]
										,[Percentage]
										,[RemaningValues]
										,[RevenueAmount]
										,[AccountingType]
										,[RRCalcTypeTrigger]
										,[RRPercentage]
										,[RRDays])
								select @SuspendCOAAccountId,
										@SuspendRRRId,
										@SuspendRRRCode,
										@SuspendRRCalcTypeWhere,
										@SuspendRRCalcTypeMethod,
										@SuspendCOAAccountConfigId,
										@SuspendCOAAccountTypeId,
										@SuspendCOAAccountCode,
										data_transaction.transactionid, 
										data_transaction.saleid,
										data_transaction.Siteid,
										data_transaction.OperatingAreaId,
										data_transaction.Workstationid,
										data_transaction.UserGroupid,
										data_transaction.UserId,
										@BatchDate,
										CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
											 else data_transaction.TransactionDate
										end TransactionDate,
										0 Quantity,
										data_transaction.revenue TotalAmount,
										data_transaction.revenue NetAmount,
										@SuspendPrice,
										@SuspendCOAAccount_Percentage,
										@SuspendRemainingValues,
										data_transaction.revenue,
										@SuspendRRCOAAccountingType,
										@SuspendRRCalcTypeTrigger,
										@SuspendPercentage,
										@SuspendDays
	   
								from DATA_Sale
									inner join data_transaction			on data_transaction.saleid = DATA_Sale.saleid
								where data_transaction.transactiontype = 12
									and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
										OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
									and data_transaction.transactionid in (select transactionid
																			from data_payment
																			where PaymentStatus = 1
																			and PaymentAmount &lt;&gt; 0
																		)



								INSERT INTO [dbo].[RR_DATA_Revenue]
										([COAAccountId]
										,[RevenueRecognitionRuleId]
										,[RRCode]
										,[RRCalcTypeWhere]
										,[RRCalcTypeMethod]
										,[COAAccountConfigId]
										,[COAAccountType]
										,[COAAccountCode]
										,[TransactionId]
										,[SaleId]
										,[SaleItemId]
										,[MatrixCellId]
										,[MatrixCellCode]
										,[MatrixSheetID]
										,[SiteId]
										,[OperatingAreaId]
										,[WorkstationId]
										,[UserGroupId]
										,[UserId]
										,[FCalcDate]
										,[FRevenueDate]
										,[Quantity]
										,[UnitAmount]
										,[GrossAmount]
										,[NetAmount]
										,[Price]
										,[Percentage]
										,[RemaningValues]
										,[RevenueAmount]
										,[AccountingType]
										,[RRCalcTypeTrigger]
										,[RRPercentage]
										,[RRDays]
										,[AttributeIDS])
										select *
										from (
								select @SuspendCOAAccountId as COAAccountId,
										@SuspendRRRId as RevenueRecognitionRuleId,
										@SuspendRRRCode as RRCode,
										@SuspendRRCalcTypeWhere as RRCalcTypeWhere,
										@SuspendRRCalcTypeMethod as RRCalcTypeMethod,
										@SuspendCOAAccountConfigId as COAAccountConfigId,
										@SuspendCOAAccountTypeId as COAAccountType,
										@SuspendCOAAccountCode as COAAccountCode,
										data_transaction.transactionid, 
										data_transaction.saleid,
										DATA_SaleItem.saleitemid,
										DATA_SaleItem.Matrixcellid,
										CNF_MatrixCell.Code,
										CNF_MatrixCell.MatrixSheetid,
										data_transaction.Siteid,
										data_transaction.OperatingAreaId,
										data_transaction.Workstationid,
										data_transaction.UserGroupid,
										data_transaction.UserId,
										@BatchDate as calcdate,
										CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
												else data_transaction.TransactionDate
										end TransactionDate,
										Coalesce(DATA_SaleItem.Quantity, 1) as quantity,
										DATA_SaleItem.UnitPrice,
										case when isnull(DATA_SaleItem.TotalAmount, 0) &lt;&gt; 0 then DATA_SaleItem.TotalAmount
											when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
											else DATA_Sale.TotalAmount
										end as totalamount,
										case when isnull((DATA_SaleItem.TotalAmount - DATA_SaleItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_SaleItem.TotalAmount - DATA_SaleItem.TotalTaxes)
											when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
											else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
										end as NetAmount,
										@SuspendPrice as suspendprice,
										@SuspendCOAAccount_Percentage as percentage,
										@SuspendRemainingValues as remainingValues,
										case when (data_saleitem.ProductTaxType &lt;&gt; 1) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice) * DATA_SaleItem.Quantity)
											 when (data_saleitem.ProductTaxType = 1) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice - DATA_SaleItem.unittaxes) * DATA_SaleItem.Quantity)
											 when isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 then 0
											 when isnull((data_transaction.TotalAmount), 0) &lt;&gt; 0 then data_transaction.TotalAmount
											 when isnull((DATA_Sale.TotalAmount), 0) &lt;&gt; 0 then DATA_Sale.TotalAmount
											 else (data_transaction.Revenue)
										end as Revenueamount,
										case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
												when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
												when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 2
												when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 1
												else @SuspendRRCOAAccountingType
										end Accountingtype,
										@SuspendRRCalcTypeTrigger as rrTrigger,
										@SuspendPercentage as suspercentage,
										@SuspendDays as suspendday,
										CNF_AttributeSet.Attributeids
	   
								from DATA_Sale
									inner join data_transaction			on data_transaction.TransactionId = DATA_Sale.PaidTransactionId
									left join DATA_SaleItem			    on DATA_SaleItem.SAleid = data_transaction.SAleid
									left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
									left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

								where DATA_Sale.Paid = 1
									and data_transaction.transactiontype in (16)
									and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
									 OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
									and data_transaction.transactionid in (select transactionid
																			from data_payment
																			where PaymentStatus = 1
																			--and PaymentAmount &lt;&gt; 0
																		)
									and data_transaction.transactionid not in (select distinct transactionid
																				from rr_data_Revenue
																				where transactionid is not null)
									and data_saleitem.saleitemid not in (select distinct data_saleitem.saleitemid
																	from data_saleitem
																			inner join data_transactionitem   on data_transactionitem.saleitemid = data_saleitem.saleitemid
																			inner join data_transaction       on data_transaction.transactionid = data_transactionitem.transactionid
																	where data_transaction.transactiontype in (5)
																	)
									)p  where UnitPrice &lt;&gt; 0


								INSERT INTO [dbo].[RR_DATA_Revenue]
										([COAAccountId]
										,[RevenueRecognitionRuleId]
										,[RRCode]
										,[RRCalcTypeWhere]
										,[RRCalcTypeMethod]
										,[COAAccountConfigId]
										,[COAAccountType]
										,[COAAccountCode]
										,[TransactionId]
										,[SaleId]
										,[SaleItemId]
										,[MatrixCellId]
										,[MatrixCellCode]
										,[MatrixSheetID]
										,[SiteId]
										,[OperatingAreaId]
										,[WorkstationId]
										,[UserGroupId]
										,[UserId]
										,[FCalcDate]
										,[FRevenueDate]
										,[Quantity]
										,[UnitAmount]
										,[GrossAmount]
										,[NetAmount]
										,[Price]
										,[Percentage]
										,[RemaningValues]
										,[RevenueAmount]
										,[AccountingType]
										,[RRCalcTypeTrigger]
										,[RRPercentage]
										,[RRDays]
										,[AttributeIDS])
								select @SuspendCOAAccountId,
										@SuspendRRRId,
										@SuspendRRRCode,
										@SuspendRRCalcTypeWhere,
										@SuspendRRCalcTypeMethod,
										@SuspendCOAAccountConfigId,
										@SuspendCOAAccountTypeId,
										@SuspendCOAAccountCode,
										data_transaction.transactionid, 
										data_transaction.saleid,
										DATA_TransactionItem.saleitemid,
										DATA_SaleItem.Matrixcellid,
										CNF_MatrixCell.Code,
										CNF_MatrixCell.MatrixSheetid,
										data_transaction.Siteid,
										data_transaction.OperatingAreaId,
										data_transaction.Workstationid,
										data_transaction.UserGroupid,
										data_transaction.UserId,
										@BatchDate,
										CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
											 else data_transaction.TransactionDate
										end TransactionDate,
										Coalesce(DATA_TransactionItem.Quantity, 1),
										DATA_SaleItem.UnitPrice,
										case when isnull(DATA_TransactionItem.TotalAmount, 0) &lt;&gt; 0 then DATA_TransactionItem.TotalAmount
											when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
											else DATA_Sale.TotalAmount
										end,
										case when isnull((DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes)
											when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
											else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
										end as NetAmount,
										@SuspendPrice,
										@SuspendCOAAccount_Percentage,
										@SuspendRemainingValues,
										case when isnull((DATA_TransactionItem.UnitPrice *  DATA_TransactionItem.Quantity), 0) &lt;&gt; 0 then (DATA_TransactionItem.UnitPrice *  DATA_TransactionItem.Quantity)
											when isnull((data_transaction.TotalAmount), 0) &lt;&gt; 0 then data_transaction.TotalAmount
											when isnull((DATA_Sale.TotalAmount), 0) &lt;&gt; 0 then DATA_Sale.TotalAmount
											else (data_transaction.Revenue)
										end,
										case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
												when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
												when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 2
												when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 1
												else @SuspendRRCOAAccountingType
										end Accountingtype,
										@SuspendRRCalcTypeTrigger,
										@SuspendPercentage,
										@SuspendDays,
										CNF_AttributeSet.Attributeids
	   
								from DATA_Sale
									inner join data_transaction			on data_transaction.saleid = DATA_Sale.saleid
									inner join DATA_TransactionItem		on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
									left join DATA_SaleItem			    on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
									left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
									left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

								where DATA_Sale.Paid = 1
									and data_transaction.transactiontype in (5)
									and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
									 OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
					
									and data_transaction.transactionid in (select transactionid
																			from data_payment
																			where PaymentStatus = 1
																			and PaymentAmount &lt;&gt; 0
																		)
									and data_transaction.transactionid not in (select distinct transactionid
																				from rr_data_Revenue
																				where transactionid is not null)

				--PaymentMethod
								INSERT INTO [dbo].[RR_DATA_Revenue]
												([COAAccountId]
												,[RevenueRecognitionRuleId]
												,[RRCode]
												,[RRCalcTypeWhere]
												,[RRCalcTypeMethod]
												,[COAAccountConfigId]
												,[COAAccountType]
												,[COAAccountCode]
												,[TransactionId]
												,[SaleId]
												,[SiteId]
												,[OperatingAreaId]
												,[WorkstationId]
												,[UserGroupId]
												,[UserId]
												,[FCalcDate]
												,[FRevenueDate]
												,[Quantity]
												,[GrossAmount]
												,[NetAmount]
												,[Price]
												,[Percentage]
												,[RemaningValues]
												,[RevenueAmount]
												,[AccountingType]
												,[RRCalcTypeTrigger]
												,[RRPercentage]
												,[RRDays])
												select  coaaccountid,
														RRID,
														RRCode,
														TypeWhere,
														method,
														Configid,
														AccountType,
														AccountCode,
														transactionid, 
														saleid,
														Siteid,
														OperatingAreaId,
														WorkstationID,
														UserGroupid,
														UserId,
														BatchDate,
														TransactionDate,
														Qty,
														Gross,
														net,
														price,
														percentage,
														RemaningValue,
														sum(abs(RevenueAmount)),
														Accountingtype,
														TypeTrigger,
														PaymentPercentage,
														RRDays
												from (
												select  coaaccountid,
														RRID,
														RRCode,
														TypeWhere,
														method,
														Configid,
														AccountType,
														AccountCode,
														transactionid, 
														saleid,
														Siteid,
														OperatingAreaId,
														WorkstationID,
														UserGroupid,
														UserId,
														BatchDate,
														TransactionDate,
														Qty,
														Gross,
														net,
														price,
														percentage,
														RemaningValue,
														case when Rownumber = 1 then RevenueAmount + Change
															 else RevenueAmount
														 end RevenueAmount,
														Accountingtype,
														TypeTrigger,
														PaymentPercentage,
														RRDays
												from (
												select @PaymentCOAAccountId as coaaccountid,
														@PaymentRRRId as RRID,
														@PaymentRRRCode as RRCode,
														@PaymentRRCalcTypeWhere as TypeWhere,
														@PaymentRRCalcTypeMethod as method,
														@PaymentCOAAccountConfigId as Configid,
														@PaymentCOAAccountTypeId as AccountType,
														@PaymentCOAAccountCode as AccountCode,
														data_transaction.transactionid, 
														data_transaction.saleid,
														data_transaction.Siteid,
														data_transaction.OperatingAreaId,
														data_transaction.Workstationid,
														data_transaction.UserGroupid,
														data_transaction.UserId,
														@BatchDate as BatchDate,
														CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
															 else data_transaction.TransactionDate
														end TransactionDate,
														0 as Qty,
														0 as Gross,
														0 as net,
														0 as price,
														100 as percentage,
														0 as RemaningValue,
														(data_payment.PaymentAmount) as RevenueAmount,
														case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @PaymentRRCOAAccountingType = 1 then 2
																when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @PaymentRRCOAAccountingType = 2 then 1
																when TransactionType in (7) and (data_payment.PaymentAmount + data_Payment.PaymentFee) &lt;= 0  then 2
																when TransactionType in (7) and (data_payment.PaymentAmount + data_Payment.PaymentFee) &gt; 0  then 1
																else @PaymentRRCOAAccountingType
														end Accountingtype,
														data_transaction.Change,
														@PaymentRRCalcTypeTrigger as TypeTrigger,
														@PaymentPercentage as PaymentPercentage,
														@PaymentDays as RRDays,
														Row_Number ()  OVER (PARTITION BY data_transaction.transactionid order by data_transaction.transactionid)  as Rownumber
		  
												from DATA_Sale
															INNER join data_transaction			on ((data_transaction.TransactionId = Isnull(data_sale.voidtransactionid, DATA_Sale.PaidTransactionId)) or 
																								   (data_transaction.saleid = data_sale.saleid))
															INNER JOIN DATA_Payment				on data_payment.transactionid = data_transaction.transactionid
			
												where data_payment.PaymentStatus = 1
													and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
													 OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
											)p
											)r
											group by 	coaaccountid,
														RRID,
														RRCode,
														TypeWhere,
														method,
														Configid,
														AccountType,
														AccountCode,
														transactionid, 
														saleid,
														Siteid,
														OperatingAreaId,
														Workstationid,
														UserGroupid,
														UserId,
														BatchDate,
														TransactionDate,
														Qty,
														Gross,
														net,
														price,
														percentage,
														RemaningValue,
														Accountingtype,
														TypeTrigger,
														PaymentPercentage,
														RRDays
											Having sum(abs(RevenueAmount)) &lt;&gt; 0
						



				--Tax
									INSERT INTO [dbo].[RR_DATA_Revenue]
												([COAAccountId]
												,[RevenueRecognitionRuleId]
												,[RRCode]
												,[RRCalcTypeWhere]
												,[RRCalcTypeMethod]
												,[COAAccountConfigId]
												,[COAAccountType]
												,[COAAccountCode]
												,[TransactionId]
												,[SaleId]
												,[SiteId]
												,[OperatingAreaId]
												,[WorkstationId]
												,[UserGroupId]
												,[UserId]
												,[FCalcDate]
												,[FRevenueDate]
												,[Quantity]
												,[GrossAmount]
												,[NetAmount]
												,[Price]
												,[Percentage]
												,[RemaningValues]
												,[RevenueAmount]
												,[AccountingType]
												,[RRCalcTypeTrigger]
												,[RRPercentage]
												,[RRDays])

												select  @TaxCOAAccountId,
														@TaxRRRId,
														@TaxRRRCode,
														@TaxRRCalcTypeWhere,
														@TaxRRCalcTypeMethod,
														@TaxCOAAccountConfigId,
														@TaxCOAAccountTypeId,
														@TaxCOAAccountCode,
														data_transaction.transactionid, 
														data_transaction.saleid,
														data_transaction.Siteid,
														data_transaction.OperatingAreaId,
														data_transaction.Workstationid,
														data_transaction.UserGroupid,
														data_transaction.UserId,
														@BatchDate,
														CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
															 else data_transaction.TransactionDate
														end TransactionDate,
														0,
														0,
														0,
														0,
														100,
														0,
														ABS(sum(taxamount)) RevenueAmount,
														case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @TaxRRCOAAccountingType = 1 then 2
																when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @TaxRRCOAAccountingType = 2 then 1
																when TransactionType in (7) and sum(taxamount) &lt;= 0  then 1
																when TransactionType in (7) and sum(taxamount) &gt; 0  then 2
																else @TaxRRCOAAccountingType
														end Accountingtype,
														@TaxRRCalcTypeTrigger,
														@TaxPercentage,
														@TaxDays
		   
											from Data_Sale
												INNER JOIN DATA_Transaction						on data_transaction.Saleid = Data_Sale.Saleid
												INNER JOIN DATA_TransactionTax					on data_transactiontax.transactionid = data_transaction.transactionid
												INNER JOIN CNF_Tax								on cnf_tax.taxid = DATA_TransactionTax.taxid
												--INNER JOIN coa_cnf_account coa					on coa.coaaccountid = cnf_tax.coaaccountid


											where transactiontype NOT IN (33, 45, 46, 47)
											   and Data_Sale.paid = 1
												and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
												 OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
												  and data_transaction.transactionid in (select distinct transactionid
																						   from data_payment
																						   where data_payment.paymentstatus = 1
																						)
											group by 			data_transaction.transactionid, 
																data_transaction.saleid,
																data_transaction.Siteid,
																data_transaction.OperatingAreaId,
																data_transaction.Workstationid,
																data_transaction.UserGroupid,
																data_transaction.UserId,
																Data_Transaction.TransactionDate,
																TransactionType,
																fTransactionDate


				--Discount

										INSERT INTO [dbo].[RR_DATA_Revenue]
												([COAAccountId]
												,[RevenueRecognitionRuleId]
												,[RRCode]
												,[RRCalcTypeWhere]
												,[RRCalcTypeMethod]
												,[COAAccountConfigId]
												,[COAAccountType]
												,[COAAccountCode]
												,[TransactionId]
												,[SaleId]
												,[SiteId]
												,[OperatingAreaId]
												,[WorkstationId]
												,[UserGroupId]
												,[UserId]
												,[FCalcDate]
												,[FRevenueDate]
												,[Quantity]
												,[GrossAmount]
												,[NetAmount]
												,[Price]
												,[Percentage]
												,[RemaningValues]
												,[RevenueAmount]
												,[AccountingType]
												,[RRCalcTypeTrigger]
												,[RRPercentage]
												,[RRDays])

												select  @DiscountCOAAccountId,
														@DiscountRRRId,
														@DiscountRRRCode,
														@DiscountRRCalcTypeWhere,
														@DiscountRRCalcTypeMethod,
														@DiscountCOAAccountConfigId,
														@DiscountCOAAccountTypeId,
														@DiscountCOAAccountCode,
														data_transaction.transactionid, 
														data_transaction.saleid,
														data_transaction.Siteid,
														data_transaction.OperatingAreaId,
														data_transaction.Workstationid,
														data_transaction.UserGroupid,
														data_transaction.UserId,
														@BatchDate,
														CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
															 else data_transaction.TransactionDate
														end TransactionDate,
														0,
														0,
														0,
														0,
														100,
														0,
														ABS(p.GLAmount) RevenueAmount,
														case    when data_transaction.TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) then 2
																when data_transaction.TransactionType in (7) and (GLAmount) &lt;= 0  then 2
																when data_transaction.TransactionType in (7) and (GLAmount) &gt; 0  then 1
																else @DiscountRRCOAAccountingType
														end Accountingtype,

														@DiscountRRCalcTypeTrigger,
														@DiscountPercentage,
														@DiscountDays
											FROM
											(
												SELECT distinct DATA_SaleItem.Saleitemid,
																DATA_Sale.saleid AS SAleid,
      															DATA_Transaction.TransactionType,
      															( SELECT top 1 transactionid
																	FROM data_transaction		WITH (NOLOCK)
																   WHERE saleid = DATA_Sale.saleid
																	AND transactiontype in (14, 16)
																	AND paid = 1
																) AS tester,

																CASE WHEN DATA_Transaction.TransactionId IN (
																											  SELECT TR.TransactionID
																												FROM DATA_Transaction TR			WITH (NOLOCK)
																													LEFT JOIN DATA_Payment DP		WITH (NOLOCK) ON TR.TransactionId = DP.TransactionId
																											  WHERE TR.SaleId = DATA_Sale.SaleId
																												AND TR.Paid = 1
																												AND DP.PaymentStatus NOT IN (0, 2, 3)
																											)
      
																			THEN DATA_Transaction.Transactionid
																	 ELSE (
																			  SELECT MIN(TR.TransactionID)
																				FROM DATA_Transaction TR				WITH (NOLOCK)
																					LEFT JOIN DATA_Payment DP			WITH (NOLOCK) ON TR.TransactionId = DP.TransactionId
																			   WHERE TR.SaleId = DATA_Sale.saleid
																				 AND TR.TransactionType = 16
																				 AND TR.Paid = 1
																				 AND DP.PaymentStatus NOT IN (0, 2, 3)
																		  )
																END Transactionid, 
																 CASE WHEN CNF_Promotion.PromotionType = 1 AND CNF_PromotionItemRule.NewProduct = 1 THEN  (CNF_MatrixCell.Price - SUM(DATA_SaleItemRule.DiscountAmount))
																	  ELSE  CASE WHEN sum(1*data_saleItemRule.DiscountAmount) &lt; 0 AND transactiontype IN(20, 22, 30, 7, 5, 46, 47) AND
																																												(SELECT Count(*) 
																																												   FROM data_transaction WITH (NOLOCK)
																																												  WHERE saleid = data_sale.saleid
																																												 ) = 1 					  					  					  										  
																					  THEN Sum(1 * DATA_SaleItemRule.DiscountAmount)
																				 WHEN sum(1*data_saleItemRule.DiscountAmount) &lt; 0 THEN	Sum(-1 * DATA_SaleItemRule.DiscountAmount)
																				 WHEN sum(1*data_saleItemRule.DiscountAmount) &gt; 0 AND transactiontype IN(20, 22, 30, 7, 5, 46, 47) THEN Sum(-1 * DATA_SaleItemRule.DiscountAmount)		            	                  
																				 ELSE sum(1*Data_SaleItemRule.DiscountAmount)
																			END
																END AS GLAmount


												FROM dbo.DATA_SaleItemRule				WITH (NOLOCK)
													LEFT JOIN dbo.CNF_PromotionItemRule WITH (NOLOCK) ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
													LEFT JOIN dbo.CNF_PromotionItem		WITH (NOLOCK) ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
													LEFT JOIN dbo.CNF_Promotion			WITH (NOLOCK) ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId
													LEFT JOIN dbo.CNF_DmgCategory		WITH (NOLOCK) ON CNF_DmgCategory.DmgCategoryId = CNF_Promotion.DmgCategoryId
													LEFT JOIN dbo.DATA_SaleItem			WITH (NOLOCK) ON DATA_SaleItem.SaleItemId = DATA_SaleItemRule.SaleItemId
													LEFT JOIN dbo.DATA_Sale				WITH (NOLOCK) ON DATA_Sale.SaleID = DATA_SaleItem.SaleID
													LEFT JOIN DATA_TransactionItem		WITH (NOLOCK) ON DATA_TransactionItem.SaleItemId = DATA_SaleItem.SaleItemId 
													LEFT JOIN DATA_Transaction			WITH (NOLOCK) ON  DATA_Transaction.TransactionId = DATA_TransactionItem.TransactionId
													LEFT JOIN CNF_MatrixCell			WITH (NOLOCK) ON CNF_MatrixCell.MatrixCellId =  DATA_SaleItem.MatrixCellId

 
												WHERE DATA_Transaction.saleid in (
																					SELECT ff.saleid 
																					  FROM DATA_Transaction ff WITH (NOLOCK) 
																						LEFT JOIN Data_Payment WITH (NOLOCK) on (ff.Transactionid = Data_Payment.Transactionid) 
																					 WHERE  ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
																						OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
																					   AND DATA_PAyment.PaymentStatus NOT in (0,2,3) 
																					   AND (TransactionType not in (12)) 
																					   AND ff.PAid = 1
																				 )  

												 AND DATA_Sale.Paid = 1
												 and transactiontype NOT IN (33, 45, 46, 47)
												 AND ((DATA_SaleItem.quantity &gt; 0) OR ((DATA_SaleItem.quantity &lt; 0) AND (transactiontype IN (20, 22, 30, 7, 5, 46, 47))))

         
												group BY DATA_SaleItem.Saleitemid,
														 DATA_Sale.saleid,
														 Data_transaction.Paid,
														 Data_Transaction.Transactionid,
														 Data_Transaction.fTransactionDate,
														 Data_Saleitem.Matrixcellid,
														 CNF_DmgCategory.DmgCategoryCode,
														 PromotionType,
														 CNF_PromotionItemRule.NewProduct,
														 CNF_MatrixCell.Price,
														 transactiontype,
														 CNF_DmgCategory.Description
											)p
												LEFT JOIN data_transaction WITH (NOLOCK) on data_transaction.transactionid = p.transactionid

											WHERE ((p.TransactionType &lt;&gt; 5) or (Tester is not null))
											  AND data_transaction.transactionid is not null


					
						--End Move Transactions to Suspend Account

						exec otn_sp_RR_RevenueData_OnDepositTrigger @BatchDate, @RRTransDateType

						exec otn_sp_RR_RevenueData_OnSaleTrigger @BatchDate, @RRTransDateType
		
						exec otn_sp_RR_RevenueData_OnMoneyCardLoad @BatchDate, @RRTransDateType

						exec otn_sp_RR_RevenueData_OnMoneyCardCashOut @BatchDate, @RRTransDateType

						exec otn_sp_RR_RevenueData_OnExternalMoneyCardCashOut @BatchDate, @RRTransDateType

						exec otn_sp_RR_RevenueData_OnExternalMoneyCardLoad @BatchDate, @RRTransDateType

						exec otn_sp_RR_RevenueData_OnCreditWriteoff @BatchDate, @RRTransDateType

						exec otn_sp_RR_RevenueData_OnMoneyRefundTrigger @BatchDate, @RRTransDateType

						exec otn_sp_RR_RevenueData_OnAdvancedPaymentTrigger @BatchDate, @RRTransDateType
		
						--exec otn_sp_RR_RevenueData_OnFlexContractPayment @BatchDate, @RRTransDateType

						--exec otn_sp_RR_RevenueData_OnFlexContractCancelled @BatchDate, @RRTransDateType

						exec otn_sp_RR_RevenueData_OnCreditSettlementTrigger @BatchDate, @RRTransDateType
		
						exec otn_sp_RR_RevenueData_SettleUpSuspendAccount @BatchDate, @RRTransDateType


						exec otn_sp_RR_RevenueData_OnTicketUsageTrigger @BatchDate, @RRTransDateType

						exec otn_sp_RR_RevenueData_OnEventTrigger @BatchDate, @RRTransDateType

						exec otn_sp_RR_RevenueData_OnTimePeriodTrigger @BatchDate, @RRTransDateType

						exec otn_sp_RR_RevenueData_OnTicketExpiredTrigger @BatchDate, @RRTransDateType

						exec otn_sp_RR_RevenueData_OnChangeValiditydateTrigger @BatchDate, @RRTransDateType
		

	FETCH NEXT FROM date_Cursor INTO
		@BatchDate

end

End
</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>stefanocoluccia</ADDEDBY><SQLVERSION>2320</SQLVERSION><RMTRACKLINK>71930</RMTRACKLINK><REASON>Adding index to the CNF_CostCenter_Validity
CREATE NONCLUSTERED INDEX [IDX_CNF_CostCenter_Validity_MatrixcellId]
ON [CNF_CostCenter_Validity] ([MatrixCellId])</REASON><TABLENAMES>CNF_CostCenter_Validity=CostCenterValidityId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name='IDX_CNF_CostCenter_Validity_MatrixcellId' AND object_id = OBJECT_ID('CNF_CostCenter_Validity'))
begin
	CREATE NONCLUSTERED INDEX [IDX_CNF_CostCenter_Validity_MatrixcellId] ON [CNF_CostCenter_Validity]
	(
		[MatrixCellId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
end
</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>AndreaDavanzo</ADDEDBY><SQLVERSION>2319</SQLVERSION><RMTRACKLINK>IDBOS-577</RMTRACKLINK><REASON>Added column AttributeAK
[0] Add column AttributeAK
[1] Fill new field for all existing records</REASON><TABLENAMES>CNF_Attribute=AttributeId</TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'AttributeAK' AND
                Object_ID  = Object_ID(N'CNF_Attribute'))
BEGIN
  ALTER TABLE CNF_Attribute ADD AttributeAK varchar(20) NULL
END</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>UPDATE CNF_Attribute
SET AttributeAK = 
    (SELECT top 1 SystemCode FROM CNF_System WHERE Enabled = 1) + '.ATT' + CAST(AttributeId AS Varchar(MAX))
WHERE AttributeAK is null</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>INSERT INTO DATA_Counter
           (CounterType
           ,IdentifierAK
           ,ReferenceTime
           ,Counter
           ,LastUpdateGuid)
     VALUES
           (35,
           (SELECT top 1 SystemCode FROM CNF_System WHERE Enabled = 1) + '.ATT',
           'NEVER',
           (SELECT ISNULL(MAX(AttributeId), 0) FROM CNF_Attribute),
           NULL)</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>ALTER TABLE CNF_Attribute ALTER COLUMN AttributeAK varchar(20) NOT NULL</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>2318</SQLVERSION><RMTRACKLINK>71376</RMTRACKLINK><REASON>Update COA Stored procedure for Gate access</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_RR_RevenueData_OnTicketUsageTrigger]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_RR_RevenueData_OnTicketUsageTrigger
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>CREATE Procedure dbo.otn_sp_RR_RevenueData_OnTicketUsageTrigger
	@BatchDate Date,
	@RRTransDateType Integer
AS 
BEGIN
	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer
	Declare @TicketUsageTrigger Integer = 2	

	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1



	BEGIN

		--Normal TicketExpired No Remaining Value
			INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[SaleId]
				   ,[UsageID]
				   ,[Ticketid]
				   ,[MatrixCellid]
				   ,[MatrixCellCode]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				   ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]			
				   ,[RRDays]
				   ,[AttributeIDs])
				   select *
				   from (
				     select distinct coa_cnf_account.COAAccountId, 
							RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
							RR_CNF_RevenueRecognitionRule.code,		   
							RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
							RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
							COA_CNF_AccountConfig.COAAccountConfigId,
							coa_cnf_account.COAAccountTypeId,
							coa_cnf_account.Code as AccountCode,
							p.saleid as Saleid,
							p.Usageid,
							p.Ticketid as SaleitemID,
							p.Matrixcellid as Matrixcell,
							p.Code as MatrixCode,
							p.MatrixSheetId as MatrixSheetID,
							CASE When RR_CNF_RevenueRecognitionRule.rrCalcTypeWhere = 1 then p.AdmSiteid 
							else p.SaleSite
							end as SiteID,
							p.OperatingAreaId as OperatingAreaID,
							p.Workstationid as Workstationid,
							p.UserId as userID,
							@BatchDate as BatchDate,
							@BatchDate as TransDate,
							1 as Quantity,
							p.GrossAmount as GrossAmount,
							p.NetPrice as NetAmount,
							COA_CNF_AccountConfig.Price as ConfigPrice,
							COA_CNF_AccountConfig.Percentage as ConfigPercentage,
							COA_CNF_AccountConfig.RemainingValues,							
							Case when COA_CNF_AccountConfig.Price &gt; 0 then (COA_CNF_AccountConfig.Price) 
									else 
									
									case when RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod = 3 then
											case  when (((p.NetPrice - ISNULL(TotalUsed, 0)) &gt; 0) and (p.NetPrice - ISNULL(TotalUsed, 0)) &gt;= p.OptionValue) 
															
														then (((p.OptionValue * RR_CNF_RevenueRecognitionRule.Percentage)/100 * COA_CNF_AccountConfig.Percentage)/100)
													else ( ((p.NetPrice - ISNULL(TotalUsed, 0)) *  COA_CNF_AccountConfig.Percentage)/100)
												end


									     when (((p.NetPrice - ISNULL(TotalUsed, 0)) &gt; 0) and (p.NetPrice - ISNULL(TotalUsed, 0)) &gt;= (((p.NetPrice * RR_CNF_RevenueRecognitionRule.Percentage)/100 * COA_CNF_AccountConfig.Percentage)/100)) 
												then (((p.NetPrice * RR_CNF_RevenueRecognitionRule.Percentage)/100 * COA_CNF_AccountConfig.Percentage)/100)
											else p.NetPrice - ISNULL(TotalUsed, 0)
										end
							end as RevenueAmount,
							COA_CNF_AccountConfig.AccountingType,
							RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
							RR_CNF_RevenueRecognitionRule.Percentage,
							RR_CNF_RevenueRecognitionRule.Days,
							AttributeIDs
						from (			
								select  data_ticketusage.ticketid,
								        data_ticketusage.UsageID,
										1 as Quantity, 
										case when data_ticket.ProductTaxType = 1 then (rawPrice - data_ticket.taxes) 
										     else rawPrice
										end NetPrice,
										data_ticketusageoption.OptionValue,
										DATA_Ticket.Price as GrossAmount,
										CNF_MatrixCell.matrixcellid, 
										CNF_MatrixCell.code,
										CNF_MatrixCell.matrixsheetid, 
										DATA_Ticket.Siteid SaleSite,	  
										cnf_workstation.OperatingAreaId,
										cnf_workstation.workstationid,
										(select top 1 DATA_Sale.userid
											from data_saleitem
											INNER JOIN DATA_Sale		on data_sale.saleid = data_saleitem.saleid
											where data_saleitem.saleitemid = data_ticket.saleitemid
										) as userid,
										(select top 1 data_saleitem.saleid
											from data_saleitem
											where data_saleitem.saleitemid = data_ticket.saleitemid
										) as Saleid,
										(DATA_Ticket.RawPrice) as TicketPrice,
										CNF_Location.Siteid as AdmSiteid,
										CNF_AttributeSet.AttributeIDs,
										CNF_AttributeSet.AttributeSetId
								from data_ticketusage
								    LEFT  JOIN data_ticketusageoption								on data_ticketusageoption.usageid = data_ticketusage.usageid and data_ticketusageoption.optiontype = 7
									INNER JOIN DATA_Ticket											on DATA_Ticket.ticketid = data_ticketusage.ticketid
									INNER JOIN CNF_MatrixCell										on cnf_matrixcell.matrixcellid = data_ticket.matrixcellid
									INNER JOIN CNF_AttributeSet										on cnf_attributeset.AttributeSetId = CNF_MatrixCell.AttributeSetId
									INNER JOIN CNF_Workstation										on cnf_workstation.workstationid = data_ticket.WorkstationId
									INNER JOIN ADM_Gate												on ADM_Gate.gateid = data_ticketusage.gateid
									INNER JOIN CNF_Location											on CNF_Location.locationid = ADM_Gate.locationid
								where  data_ticketusage.validateResult &lt;=99
								and data_ticketusage.UsageType = 1							
								and cast(fusagedate as date) = @batchdate
						)p 
						INNER JOIN rr_cnf_product						ON ((RR_CNF_Product.matrixcellid = p.matrixcellid) or (RR_CNF_Product.matrixsheetid = p.matrixsheetid)
																				or (rr_cnf_product.Attributeid in (select Value
																										from dbo.split((select Attributeids
																														from CNF_AttributeSet
																														where CNF_AttributeSet.AttributeSetId = p.AttributeSetId), '.')
																										)
																					    
															))
						INNER JOIN RR_CNF_RevenueRecognitionRule			ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_cnf_product.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @TicketUsageTrigger
						INNER JOIN COA_CNF_AccountConfig					ON COA_CNF_AccountConfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
						INNER JOIN COA_CNF_Account							ON COA_CNF_Account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
						LEFT JOIN (select ticketid, AccountingType, sum(revenueamount) as TotalUsed
									from rr_data_revenue
									where rr_data_revenue.RRCalcTypeTrigger = @TicketUsageTrigger
									group by ticketid, AccountingType
									)rdata									ON rdata.ticketid = p.ticketid	and rdata.AccountingType = coa_cnf_accountconfig.AccountingType
						where p.TicketPrice &lt;&gt; 0
							and RR_CNF_RevenueRecognitionRule.Enabled = 1
							and coa_cnf_account.Enabled = 1
							and COA_CNF_AccountConfig.Enabled = 1
							and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
							and COA_CNF_AccountConfig.RemainingValues &lt;&gt; 1
							and (((RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere = 1) and ((coa_cnf_accountConfig.Siteid = p.AdmSiteid) or (coa_cnf_accountConfig.Siteid is null)))
							or (RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere = 2) and ((coa_cnf_accountConfig.Siteid = p.SaleSite) or (coa_cnf_accountConfig.Siteid is null))) 
						)k
						where RevenueAmount &lt;&gt; 0




		--Normal TicketExpired with Remaining Value
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[SaleId]
				   ,[UsageID]
				   ,[Ticketid]
				   ,[MatrixCellid]
				   ,[MatrixCellCode]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				   ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays]
				   ,[AttributeIDs])
				   select *
				   from (
						select   distinct	coa_cnf_account.COAAccountId, 
									RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
									RR_CNF_RevenueRecognitionRule.code,		   
									RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
									RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
									COA_CNF_AccountConfig.COAAccountConfigId,
									coa_cnf_account.COAAccountTypeId,
									coa_cnf_account.Code as AccountCode,
									p.saleid as Saleid,
									p.Usageid,
									p.Ticketid as SaleitemID,
									p.Matrixcellid as Matrixcell,
									p.Code as MatrixCode,
									p.MatrixSheetId as MatrixSheetID,
									CASE When RR_CNF_RevenueRecognitionRule.rrCalcTypeWhere = 1 then p.AdmSiteid 
									else p.SaleSite
									end as SiteID,
									p.OperatingAreaId as OperatingAreaID,
									p.Workstationid as Workstationid,
									p.UserId as userID,
									@BatchDate as BatchDate,
									@BatchDate as TransDate,
									1 as Quantity,
									p.GrossAmount as GrossAmount,
									p.NetPrice as NetAmount,
									COA_CNF_AccountConfig.Price as ConfigPrice,
									COA_CNF_AccountConfig.Percentage as ConfigPercentage,
									COA_CNF_AccountConfig.RemainingValues,
									case when RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod = 3 then
											case when (((p.NetPrice - ISNULL(TotalUsed, 0)) &gt; 0) and ((
															((p.NetPrice *  RR_CNF_RevenueRecognitionRule.Percentage)/100) -  
																((p.NetPrice *  (select sum(percentage)
																																	from coa_cnf_accountconfig AC
																																	where AC.revenuerecognitionruleid = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																																	and ac.accountingtype = coa_cnf_accountconfig.accountingtype
																																	)
																)/100)) &lt;= (p.OptionValue - ISNULL(TotalUsed, 0)))) and p.NetPrice &gt;= P.OptionValue

												then p.optionValue
												when ((p.NetPrice - ISNULL(TotalUsed, 0)) &gt; 0) and (p.optionValue * (select sum(percentage)
																																	from coa_cnf_accountconfig AC
																																	where AC.revenuerecognitionruleid = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																																	and ac.accountingtype = coa_cnf_accountconfig.accountingtype
																																	))/100 = (select sum(RR.revenueamount)
												                                                                      from rr_data_revenue RR
																													  where RR.ticketid = p.ticketid
																													    and RR.Usageid = p.Usageid
																														and rr.accountingtype = coa_cnf_accountconfig.accountingtype
																													) 
												
												
												                      and (p.NetPrice - ISNULL(TotalUsed, 0)) &gt;= (( (p.NetPrice - ISNULL(TotalUsed, 0)) *  RR_CNF_RevenueRecognitionRule.Percentage)/100) * (select sum(percentage)
																																	from coa_cnf_accountconfig AC
																																	where AC.revenuerecognitionruleid = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																																	and ac.accountingtype = coa_cnf_accountconfig.accountingtype
																																	)
																/100
												      then   p.optionValue - (p.optionValue *  (select sum(percentage)
																																	from coa_cnf_accountconfig AC
																																	where AC.revenuerecognitionruleid = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																																	and ac.accountingtype = coa_cnf_accountconfig.accountingtype
																																	)
																/100)


												else  
												
												
												ISNULL((((select sum(RR.revenueamount)
												                                                                      from rr_data_revenue RR
																													  where RR.ticketid = p.ticketid
																													    and RR.Usageid = p.Usageid
																														and rr.accountingtype = coa_cnf_accountconfig.accountingtype
																													) /  case when (select sum(percentage)
																																		from rr_data_revenue RR
																																		where RR.ticketid = p.ticketid
																																		and RR.Usageid = p.Usageid
																																		and rr.accountingtype = coa_cnf_accountconfig.accountingtype
																																	) = 0 then 1 
																																else (select sum(percentage)
																																from rr_data_revenue RR
																																where RR.ticketid = p.ticketid
																																and RR.Usageid = p.Usageid
																																and rr.accountingtype = coa_cnf_accountconfig.accountingtype
																															) end

														 )*100 ) - (select sum(RR.revenueamount)
												                                                                      from rr_data_revenue RR
																													  where RR.ticketid = p.ticketid
																													    and RR.Usageid = p.Usageid
																														and rr.accountingtype = coa_cnf_accountconfig.accountingtype
																													), case when (p.NetPrice - ISNULL(TotalUsed, 0)) &gt;= p.optionvalue then p.optionvalue 
																													        else  (p.NetPrice - ISNULL(TotalUsed, 0))
																															end)
												end		
												
												
												
												
												
												
																	
									 when (((p.NetPrice - ISNULL(TotalUsed, 0)) &gt; 0) and ((
										((p.NetPrice *  RR_CNF_RevenueRecognitionRule.Percentage)/100) -  
											((
											((p.NetPrice *  RR_CNF_RevenueRecognitionRule.Percentage)/100) * (select sum(percentage)
																												from coa_cnf_accountconfig AC
																												where AC.revenuerecognitionruleid = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																												and ac.accountingtype = coa_cnf_accountconfig.accountingtype
																												)
											)/100)) &lt;= (p.NetPrice - ISNULL(TotalUsed, 0))))
												then 
												(((p.NetPrice *  RR_CNF_RevenueRecognitionRule.Percentage)/100) -  (((p.NetPrice *  RR_CNF_RevenueRecognitionRule.Percentage)/100) * (select sum(percentage)
																														from coa_cnf_accountconfig AC
																														where AC.revenuerecognitionruleid = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																														and ac.accountingtype = coa_cnf_accountconfig.accountingtype
																														))/100)
											else 0
										end  RevenueAmount,

									COA_CNF_AccountConfig.AccountingType,
									RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
									RR_CNF_RevenueRecognitionRule.Percentage,
									RR_CNF_RevenueRecognitionRule.Days,
									AttributeIDs
								from (			
										select  data_ticketusage.ticketid,
										data_ticketusage.UsageID,
												1 as Quantity, 
												case when data_ticket.ProductTaxType = 1 then (rawPrice - data_ticket.taxes) 
													 else rawPrice
												end NetPrice,
												data_ticketusageoption.OptionValue,
												DATA_Ticket.Price as GrossAmount,
												CNF_MatrixCell.matrixcellid, 
												CNF_MatrixCell.code,
												CNF_MatrixCell.matrixsheetid, 
												DATA_Ticket.Siteid SaleSite,	  
												cnf_workstation.OperatingAreaId,
												cnf_workstation.workstationid,
												(select top 1 DATA_Sale.userid
													from data_saleitem
													INNER JOIN DATA_Sale		on data_sale.saleid = data_saleitem.saleid
													where data_saleitem.saleitemid = data_ticket.saleitemid
												) as userid,
												(select top 1 data_saleitem.saleid
													from data_saleitem
													where data_saleitem.saleitemid = data_ticket.saleitemid
												) as Saleid,
												(DATA_Ticket.RawPrice) as TicketPrice,
												CNF_Location.Siteid as AdmSiteid,
												CNF_AttributeSet.AttributeIDs,
												CNF_AttributeSet.AttributeSetId
										from data_ticketusage
										    LEFT  JOIN data_ticketusageoption								on data_ticketusageoption.usageid = data_ticketusage.usageid and data_ticketusageoption.optiontype = 7
											INNER JOIN DATA_Ticket											on DATA_Ticket.ticketid = data_ticketusage.ticketid
											INNER JOIN CNF_MatrixCell										on cnf_matrixcell.matrixcellid = data_ticket.matrixcellid
											INNER JOIN CNF_AttributeSet										on cnf_attributeset.AttributeSetId = CNF_MatrixCell.AttributeSetId
											INNER JOIN CNF_Workstation										on cnf_workstation.workstationid = data_ticket.WorkstationId
											INNER JOIN ADM_Gate												on ADM_Gate.gateid = data_ticketusage.gateid
											INNER JOIN CNF_Location											on CNF_Location.locationid = ADM_Gate.locationid
										where data_ticketusage.validateResult &lt;=99
										and data_ticketusage.UsageType = 1
										and cast(fusagedate as date) = @batchdate
								)p 
								INNER JOIN rr_cnf_product						ON ((RR_CNF_Product.matrixcellid = p.matrixcellid) or (RR_CNF_Product.matrixsheetid = p.matrixsheetid)
																				or (rr_cnf_product.Attributeid in (select Value
																										from dbo.split((select Attributeids
																														from CNF_AttributeSet
																														where CNF_AttributeSet.AttributeSetId = p.AttributeSetId), '.')
																										)
																					    
															))
								INNER JOIN RR_CNF_RevenueRecognitionRule			ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_cnf_product.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @TicketUsageTrigger
								INNER JOIN COA_CNF_AccountConfig					ON COA_CNF_AccountConfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
								INNER JOIN COA_CNF_Account							ON COA_CNF_Account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
								LEFT JOIN (select ticketid, accountingtype, sum(revenueamount) as TotalUsed
											from rr_data_revenue
											where rr_data_revenue.RRCalcTypeTrigger = @TicketUsageTrigger
											group by ticketid, accountingtype
											)rdata									ON rdata.ticketid = p.ticketid	and rdata.accountingtype = COA_CNF_AccountConfig.accountingtype
								where p.TicketPrice &lt;&gt; 0
									and RR_CNF_RevenueRecognitionRule.Enabled = 1
									and coa_cnf_account.Enabled = 1
									and COA_CNF_AccountConfig.Enabled = 1
									and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
									and COA_CNF_AccountConfig.RemainingValues = 1
									and (((RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere = 1) and ((coa_cnf_accountConfig.Siteid = p.AdmSiteid) or (coa_cnf_accountConfig.Siteid is null)))
									or (RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere = 2) and ((coa_cnf_accountConfig.Siteid = p.SaleSite) or (coa_cnf_accountConfig.Siteid is null))) 
						)k
						where RevenueAmount &lt;&gt; 0

	end

END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_RR_RevenueData_batchJob]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_RR_RevenueData_batchJob
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>CREATE Procedure dbo.otn_sp_RR_RevenueData_batchJob	 
	@FromDate Date,
	@ToDate Date
AS 
BEGIN

	delete from rr_data_revenue
	where fcalcdate between @FromDate and @ToDate

	Declare @BatchDate Date
	Declare @RRTransDateType Integer

	Declare @SuspendRRRId Integer
	Declare @SuspendCOAAccountId Integer
	Declare @SuspendRRRCode varchar(10)
	Declare @SuspendRRCalcTypeTrigger Integer
	Declare @SuspendRRCalcTypeWhere Integer
	Declare @SuspendRRCalcTypeMethod Integer
	Declare @SuspendCOAAccountConfigId Integer
	Declare @SuspendCOAAccountTypeId Integer
	Declare @SuspendCOAAccountCode varchar(10)
	Declare @SuspendPercentage float
	Declare @SuspendDays Integer
	Declare @SuspendPrice float
	Declare @SuspendCOAAccount_Percentage Float
	Declare @SuspendRemainingValues Integer
	Declare @SuspendRRCOAAccountingType Integer
	Declare @SuspendAccountingType Integer

	Declare @PaymentRRRId Integer
	Declare @PaymentCOAAccountId Integer
	Declare @PaymentRRRCode varchar(10)
	Declare @PaymentRRCalcTypeTrigger Integer
	Declare @PaymentRRCalcTypeWhere Integer
	Declare @PaymentRRCalcTypeMethod Integer
	Declare @PaymentCOAAccountConfigId Integer
	Declare @PaymentCOAAccountTypeId Integer
	Declare @PaymentCOAAccountCode varchar(10)
	Declare @PaymentPercentage float
	Declare @PaymentDays Integer
	Declare @PaymentPrice float
	Declare @PaymentCOAAccount_Percentage Float
	Declare @PaymentRemainingValues Integer
	Declare @PaymentRRCOAAccountingType Integer
	Declare @PaymentAccountingType Integer


	Declare @TaxRRRId Integer
	Declare @TaxCOAAccountId Integer
	Declare @TaxRRRCode varchar(10)
	Declare @TaxRRCalcTypeTrigger Integer
	Declare @TaxRRCalcTypeWhere Integer
	Declare @TaxRRCalcTypeMethod Integer
	Declare @TaxCOAAccountConfigId Integer
	Declare @TaxCOAAccountTypeId Integer
	Declare @TaxCOAAccountCode varchar(10)
	Declare @TaxPercentage float
	Declare @TaxDays Integer
	Declare @TaxPrice float
	Declare @TaxCOAAccount_Percentage Float
	Declare @TaxRemainingValues Integer
	Declare @TaxRRCOAAccountingType Integer
	Declare @TaxAccountingType Integer


	Declare @DiscountRRRId Integer
	Declare @DiscountCOAAccountId Integer
	Declare @DiscountRRRCode varchar(10)
	Declare @DiscountRRCalcTypeTrigger Integer
	Declare @DiscountRRCalcTypeWhere Integer
	Declare @DiscountRRCalcTypeMethod Integer
	Declare @DiscountCOAAccountConfigId Integer
	Declare @DiscountCOAAccountTypeId Integer
	Declare @DiscountCOAAccountCode varchar(10)
	Declare @DiscountPercentage float
	Declare @DiscountDays Integer
	Declare @DiscountPrice float
	Declare @DiscountCOAAccount_Percentage Float
	Declare @DiscountRemainingValues Integer
	Declare @DiscountRRCOAAccountingType Integer
	Declare @DiscountAccountingType Integer

	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer

	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1


	select @RRTransDateType = RRTransDateType
      from cnf_system

--Begin Move Transactions to Suspend Account
	select TOP 1 @SuspendRRRId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
			@SuspendRRRCode = RR_CNF_RevenueRecognitionRule.code,
			@SuspendRRCalcTypeTrigger = RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
			@SuspendRRCalcTypeWhere = RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
			@SuspendRRCalcTypeMethod = RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
			@SuspendCOAAccountConfigId = COA_CNF_AccountConfig.COAAccountConfigId,
			@SuspendCOAAccountTypeId = COA_CNF_AccountType.COAAccountTypeId,
			@SuspendCOAAccountId = coa_cnf_account.COAAccountId,
			@SuspendPercentage = RR_CNF_RevenueRecognitionRule.Percentage,
			@SuspendDays = RR_CNF_RevenueRecognitionRule.Days,
			@SuspendPrice = COA_CNF_AccountConfig.Price,
			@SuspendCOAAccount_Percentage = COA_CNF_AccountConfig.Percentage,
			@SuspendRemainingValues = COA_CNF_AccountConfig.RemainingValues,
			@SuspendCOAAccountCode = coa_cnf_account.Code,
			@SuspendRRCOAAccountingType = COA_CNF_AccountConfig.AccountingType
	from coa_cnf_account
		INNER JOIN COA_CNF_AccountType				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
		INNER JOIN COA_CNF_AccountConfig			on COA_CNF_AccountConfig.COAAccountId = coa_cnf_account.COAAccountId
		INNER JOIN RR_CNF_RevenueRecognitionRule	on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId
	where coa_cnf_account.COAAccountID = @SuspendID
	 order by RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId

	select TOP 1 @PaymentRRRId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
			@PaymentRRRCode = RR_CNF_RevenueRecognitionRule.code,
			@PaymentRRCalcTypeTrigger = RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
			@PaymentRRCalcTypeWhere = RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
			@PaymentRRCalcTypeMethod = RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
			@PaymentCOAAccountConfigId = COA_CNF_AccountConfig.COAAccountConfigId,
			@PaymentCOAAccountTypeId = COA_CNF_AccountType.COAAccountTypeId,
			@PaymentCOAAccountId = coa_cnf_account.COAAccountId,
			@PaymentPercentage = RR_CNF_RevenueRecognitionRule.Percentage,
			@PaymentDays = RR_CNF_RevenueRecognitionRule.Days,
			@PaymentPrice = COA_CNF_AccountConfig.Price,
			@PaymentCOAAccount_Percentage = COA_CNF_AccountConfig.Percentage,
			@PaymentRemainingValues = COA_CNF_AccountConfig.RemainingValues,
			@PaymentCOAAccountCode = coa_cnf_account.Code,
			@PaymentRRCOAAccountingType = COA_CNF_AccountConfig.AccountingType
	from coa_cnf_account
		INNER JOIN COA_CNF_AccountType				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
		INNER JOIN COA_CNF_AccountConfig			on COA_CNF_AccountConfig.COAAccountId = coa_cnf_account.COAAccountId
		INNER JOIN RR_CNF_RevenueRecognitionRule	on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId
	where coa_cnf_account.COAAccountID = @ACCPaymentMethod
	 order by RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId

	select TOP 1 @TaxRRRId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
			@TaxRRRCode = RR_CNF_RevenueRecognitionRule.code,
			@TaxRRCalcTypeTrigger = RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
			@TaxRRCalcTypeWhere = RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
			@TaxRRCalcTypeMethod = RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
			@TaxCOAAccountConfigId = COA_CNF_AccountConfig.COAAccountConfigId,
			@TaxCOAAccountTypeId = COA_CNF_AccountType.COAAccountTypeId,
			@TaxCOAAccountId = coa_cnf_account.COAAccountId,
			@TaxPercentage = RR_CNF_RevenueRecognitionRule.Percentage,
			@TaxDays = RR_CNF_RevenueRecognitionRule.Days,
			@TaxPrice = COA_CNF_AccountConfig.Price,
			@TaxCOAAccount_Percentage = COA_CNF_AccountConfig.Percentage,
			@TaxRemainingValues = COA_CNF_AccountConfig.RemainingValues,
			@TaxCOAAccountCode = coa_cnf_account.Code,
			@TaxRRCOAAccountingType = COA_CNF_AccountConfig.AccountingType
	from coa_cnf_account
		INNER JOIN COA_CNF_AccountType				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
		INNER JOIN COA_CNF_AccountConfig			on COA_CNF_AccountConfig.COAAccountId = coa_cnf_account.COAAccountId
		INNER JOIN RR_CNF_RevenueRecognitionRule	on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId
	where coa_cnf_account.COAAccountID = @TaxAccountID
	 order by RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId

	select TOP 1 @DiscountRRRId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
			@DiscountRRRCode = RR_CNF_RevenueRecognitionRule.code,
			@DiscountRRCalcTypeTrigger = RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
			@DiscountRRCalcTypeWhere = RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
			@DiscountRRCalcTypeMethod = RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
			@DiscountCOAAccountConfigId = COA_CNF_AccountConfig.COAAccountConfigId,
			@DiscountCOAAccountTypeId = COA_CNF_AccountType.COAAccountTypeId,
			@DiscountCOAAccountId = coa_cnf_account.COAAccountId,
			@DiscountPercentage = RR_CNF_RevenueRecognitionRule.Percentage,
			@DiscountDays = RR_CNF_RevenueRecognitionRule.Days,
			@DiscountPrice = COA_CNF_AccountConfig.Price,
			@DiscountCOAAccount_Percentage = COA_CNF_AccountConfig.Percentage,
			@DiscountRemainingValues = COA_CNF_AccountConfig.RemainingValues,
			@DiscountCOAAccountCode = coa_cnf_account.Code,
			@DiscountRRCOAAccountingType = COA_CNF_AccountConfig.AccountingType
	from coa_cnf_account
		INNER JOIN COA_CNF_AccountType				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
		INNER JOIN COA_CNF_AccountConfig			on COA_CNF_AccountConfig.COAAccountId = coa_cnf_account.COAAccountId
		INNER JOIN RR_CNF_RevenueRecognitionRule	on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId
	where coa_cnf_account.COAAccountID = @DiscountAccountID
	 order by RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId

	Declare @Temp table (BatchDate date)

	;with dates_CTE (date) as (
			select @FromDate 
		Union ALL
			select DATEADD(day, 1, date)
			from dates_CTE
			where date &lt; @ToDate
	) 
	INSERT INTO @Temp (
	BatchDate
	) 
	select *
	from dates_CTE 

	DECLARE date_Cursor CURSOR LOCAL FOR
				select * from @Temp

	OPEN date_Cursor

	FETCH NEXT FROM date_Cursor INTO
		@BatchDate

	WHILE @@FETCH_STATUS = 0
	BEGIN

				INSERT INTO [dbo].[RR_DATA_Revenue]
								([COAAccountId]
								,[RevenueRecognitionRuleId]
								,[RRCode]
								,[RRCalcTypeWhere]
								,[RRCalcTypeMethod]
								,[COAAccountConfigId]
								,[COAAccountType]
								,[COAAccountCode]
								,[TransactionId]
								,[SaleId]
								,[SaleItemId]
								,[MatrixCellId]
								,[MatrixCellCode]
								,[MatrixSheetID]
								,[SiteId]
								,[OperatingAreaId]
								,[WorkstationId]
								,[UserGroupId]
								,[UserId]
								,[FCalcDate]
								,[FRevenueDate]
								,[Quantity]
								,[UnitAmount]
								,[GrossAmount]
								,[NetAmount]
								,[Price]
								,[Percentage]
								,[RemaningValues]
								,[RevenueAmount]
								,[AccountingType]
								,[RRCalcTypeTrigger]
								,[RRPercentage]
								,[RRDays]
								,[AttributeIDS])
						select @SuspendCOAAccountId,
								@SuspendRRRId,
								@SuspendRRRCode,
								@SuspendRRCalcTypeWhere,
								@SuspendRRCalcTypeMethod,
								@SuspendCOAAccountConfigId,
								@SuspendCOAAccountTypeId,
								@SuspendCOAAccountCode,
								data_transaction.transactionid, 
								data_transaction.saleid,
								DATA_TransactionItem.saleitemid,
								DATA_SaleItem.Matrixcellid,
								CNF_MatrixCell.Code,
								CNF_MatrixCell.MatrixSheetid,
								data_transaction.Siteid,
								data_transaction.OperatingAreaId,
								data_transaction.Workstationid,
								data_transaction.UserGroupid,
								data_transaction.UserId,
								@BatchDate,
								CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
									 else data_transaction.TransactionDate
								end TransactionDate,
								Coalesce(DATA_TransactionItem.Quantity, 1),
								DATA_SaleItem.UnitPrice,
								case when isnull(DATA_TransactionItem.TotalAmount, 0) &lt;&gt; 0 then DATA_TransactionItem.TotalAmount
									when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
									else DATA_Sale.TotalAmount
								end,
								case when isnull((DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes)
									when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
									else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
								end as NetAmount,
								@SuspendPrice,
								@SuspendCOAAccount_Percentage,
								@SuspendRemainingValues,
								case    when (data_saleitem.ProductTaxType &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice ) * DATA_SaleItem.Quantity)
										when (data_saleitem.ProductTaxType = 1) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice - DATA_SaleItem.unittaxes) * DATA_SaleItem.Quantity)
										when (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 then 0				
										when isnull((data_transaction.TotalAmount), 0) &lt;&gt; 0 then data_transaction.TotalAmount
										when isnull((DATA_Sale.TotalAmount), 0) &lt;&gt; 0 then DATA_Sale.TotalAmount
										else (data_transaction.Revenue)
								end,
								case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
										when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
										when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 1
										when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 2
										else @SuspendRRCOAAccountingType
								end Accountingtype,
								@SuspendRRCalcTypeTrigger,
								@SuspendPercentage,
								@SuspendDays,
								CNF_AttributeSet.Attributeids
	   
						from DATA_Sale
							inner join data_transaction			on data_transaction.TransactionId = DATA_Sale.PaidTransactionId
							left join DATA_TransactionItem		on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
							left join DATA_SaleItem			    on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
							left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
							left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

						where DATA_Sale.Paid = 1
							and data_transaction.transactiontype in (14)
							and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
							   OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
							and data_transaction.transactionid in (select transactionid
																	from data_payment
																	where PaymentStatus = 1
																	and PaymentAmount &lt;&gt; 0
																)

				INSERT INTO [dbo].[RR_DATA_Revenue]
								([COAAccountId]
								,[RevenueRecognitionRuleId]
								,[RRCode]
								,[RRCalcTypeWhere]
								,[RRCalcTypeMethod]
								,[COAAccountConfigId]
								,[COAAccountType]
								,[COAAccountCode]
								,[TransactionId]
								,[SaleId]
								,[SaleItemId]
								,[MatrixCellId]
								,[MatrixCellCode]
								,[MatrixSheetID]
								,[SiteId]
								,[OperatingAreaId]
								,[WorkstationId]
								,[UserGroupId]
								,[UserId]
								,[FCalcDate]
								,[FRevenueDate]
								,[Quantity]
								,[UnitAmount]
								,[GrossAmount]
								,[NetAmount]
								,[Price]
								,[Percentage]
								,[RemaningValues]
								,[RevenueAmount]
								,[AccountingType]
								,[RRCalcTypeTrigger]
								,[RRPercentage]
								,[RRDays]
								,[AttributeIDS])
						select @SuspendCOAAccountId,
								@SuspendRRRId,
								@SuspendRRRCode,
								@SuspendRRCalcTypeWhere,
								@SuspendRRCalcTypeMethod,
								@SuspendCOAAccountConfigId,
								@SuspendCOAAccountTypeId,
								@SuspendCOAAccountCode,
								data_transaction.transactionid, 
								data_transaction.saleid,
								DATA_TransactionItem.saleitemid,
								DATA_SaleItem.Matrixcellid,
								CNF_MatrixCell.Code,
								CNF_MatrixCell.MatrixSheetid,
								data_transaction.Siteid,
								data_transaction.OperatingAreaId,
								data_transaction.Workstationid,
								data_transaction.UserGroupid,
								data_transaction.UserId,
								@BatchDate,
								CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
									 else data_transaction.TransactionDate
								end TransactionDate,
								Coalesce(DATA_TransactionItem.Quantity, 1),
								DATA_SaleItem.UnitPrice,
								case when isnull(DATA_TransactionItem.TotalAmount, 0) &lt;&gt; 0 then DATA_TransactionItem.TotalAmount
									when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
									else DATA_Sale.TotalAmount
								end,
								case when isnull((DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes)
									when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
									else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
								end as NetAmount,
								@SuspendPrice,
								@SuspendCOAAccount_Percentage,
								@SuspendRemainingValues,
								DATA_SaleItem.UnitRecharge * data_saleitem.Quantity,
								case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
										when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
										when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 1
										when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 2
										else @SuspendRRCOAAccountingType
								end Accountingtype,
								@SuspendRRCalcTypeTrigger,
								@SuspendPercentage,
								@SuspendDays,
								CNF_AttributeSet.Attributeids
	   
						from DATA_Sale
							inner join data_transaction			on data_transaction.TransactionId = DATA_Sale.PaidTransactionId
							left join DATA_TransactionItem		on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
							left join DATA_SaleItem			    on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
							left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
							left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

						where DATA_Sale.Paid = 1
							and data_transaction.transactiontype in (14, 39)
							and DATA_SaleItem.UnitRecharge &lt;&gt; 0
							and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
							   OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
							and data_transaction.transactionid in (select transactionid
																	from data_payment
																	where PaymentStatus = 1
																	and PaymentAmount &lt;&gt; 0
																)

					INSERT INTO [dbo].[RR_DATA_Revenue]
								([COAAccountId]
								,[RevenueRecognitionRuleId]
								,[RRCode]
								,[RRCalcTypeWhere]
								,[RRCalcTypeMethod]
								,[COAAccountConfigId]
								,[COAAccountType]
								,[COAAccountCode]
								,[TransactionId]
								,[SaleId]
								,[SaleItemId]
								,[MatrixCellId]
								,[MatrixCellCode]
								,[MatrixSheetID]
								,[SiteId]
								,[OperatingAreaId]
								,[WorkstationId]
								,[UserGroupId]
								,[UserId]
								,[FCalcDate]
								,[FRevenueDate]
								,[Quantity]
								,[UnitAmount]
								,[GrossAmount]
								,[NetAmount]
								,[Price]
								,[Percentage]
								,[RemaningValues]
								,[RevenueAmount]
								,[AccountingType]
								,[RRCalcTypeTrigger]
								,[RRPercentage]
								,[RRDays]
								,[AttributeIDS])
						select @SuspendCOAAccountId,
								@SuspendRRRId,
								@SuspendRRRCode,
								@SuspendRRCalcTypeWhere,
								@SuspendRRCalcTypeMethod,
								@SuspendCOAAccountConfigId,
								@SuspendCOAAccountTypeId,
								@SuspendCOAAccountCode,
								data_transaction.transactionid, 
								data_transaction.saleid,
								DATA_TransactionItem.saleitemid,
								DATA_SaleItem.Matrixcellid,
								CNF_MatrixCell.Code,
								CNF_MatrixCell.MatrixSheetid,
								data_transaction.Siteid,
								data_transaction.OperatingAreaId,
								data_transaction.Workstationid,
								data_transaction.UserGroupid,
								data_transaction.UserId,
								@BatchDate,
								CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
									 else data_transaction.TransactionDate
								end TransactionDate,
								Coalesce(DATA_TransactionItem.Quantity, 1),
								DATA_SaleItem.UnitPrice,
								case when isnull(DATA_TransactionItem.TotalAmount, 0) &lt;&gt; 0 then DATA_TransactionItem.TotalAmount
									when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
									else DATA_Sale.TotalAmount
								end,
								case when isnull((DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes)
									when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
									else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
								end as NetAmount,
								@SuspendPrice,
								@SuspendCOAAccount_Percentage,
								@SuspendRemainingValues,
								case    when (data_saleitem.ProductTaxType &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) 
												  and (isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0) 
													   and (((select discountamount from data_saleitemrule where saleitemid = DATA_SaleItem.saleitemid) &gt; 0) and (data_transaction.transactiontype in (7, 20, 22)))							
											then ((DATA_SaleItem.UnitRawPrice + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)

				        when (data_saleitem.ProductTaxType &lt;&gt; 1) and (data_transaction.transactiontype in (18, 20, 22)) and (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitRawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitRawPrice  + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)
						when (data_saleitem.ProductTaxType = 1) and (data_transaction.transactiontype in (18, 20, 22)) and isnull((DATA_SaleItem.UnitRawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitRawPrice - DATA_SaleItem.unittaxes + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)

										when (data_saleitem.ProductTaxType &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice  + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)
										when (data_saleitem.ProductTaxType = 1) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice - DATA_SaleItem.unittaxes + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)

										when (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 and data_saleitem.unitRecharge = 0 then 0
										when (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 and data_saleitem.unitRecharge &lt;&gt; 0 then data_saleitem.unitRecharge
										when isnull((data_transaction.TotalAmount), 0) &lt;&gt; 0 then data_transaction.TotalAmount
										when isnull((DATA_Sale.TotalAmount), 0) &lt;&gt; 0 then DATA_Sale.TotalAmount
										else (data_transaction.Revenue)
								end,
								case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
										when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
										when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 1
										when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 2
										else @SuspendRRCOAAccountingType
								end Accountingtype,
								@SuspendRRCalcTypeTrigger,
								@SuspendPercentage,
								@SuspendDays,
								CNF_AttributeSet.Attributeids
	   
						from DATA_Sale
							inner join data_transaction			on data_transaction.TransactionId = ISNULL(data_sale.voidtransactionid, DATA_Sale.PaidTransactionId)
							left join DATA_TransactionItem		on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
							left join DATA_SaleItem			    on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
							left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
							left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

						where DATA_Sale.Paid = 1
							and data_transaction.transactiontype not in (6, 8, 10, 12, 14, 16, 42, 43, 31, 39, 48, 49, 52, 46, 47)
							and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
							   OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
							and data_transaction.transactionid in (select transactionid
																	from data_payment
																	where PaymentStatus = 1
																	and PaymentAmount &lt;&gt; 0
																)

						INSERT INTO [dbo].[RR_DATA_Revenue]
										([COAAccountId]
										,[RevenueRecognitionRuleId]
										,[RRCode]
										,[RRCalcTypeWhere]
										,[RRCalcTypeMethod]
										,[COAAccountConfigId]
										,[COAAccountType]
										,[COAAccountCode]
										,[TransactionId]
										,[SaleId]
										,[SiteId]
										,[OperatingAreaId]
										,[WorkstationId]
										,[UserGroupId]
										,[UserId]
										,[FCalcDate]
										,[FRevenueDate]
										,[Quantity]
										,[GrossAmount]
										,[NetAmount]
										,[Price]
										,[Percentage]
										,[RemaningValues]
										,[RevenueAmount]
										,[AccountingType]
										,[RRCalcTypeTrigger]
										,[RRPercentage]
										,[RRDays])
								select @SuspendCOAAccountId,
										@SuspendRRRId,
										@SuspendRRRCode,
										@SuspendRRCalcTypeWhere,
										@SuspendRRCalcTypeMethod,
										@SuspendCOAAccountConfigId,
										@SuspendCOAAccountTypeId,
										@SuspendCOAAccountCode,
										data_transaction.transactionid, 
										data_transaction.saleid,
										data_transaction.Siteid,
										data_transaction.OperatingAreaId,
										data_transaction.Workstationid,
										data_transaction.UserGroupid,
										data_transaction.UserId,
										@BatchDate,
										CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
											 else data_transaction.TransactionDate
										end TransactionDate,
										0 Quantity,
										data_transaction.revenue TotalAmount,
										data_transaction.revenue NetAmount,
										@SuspendPrice,
										@SuspendCOAAccount_Percentage,
										@SuspendRemainingValues,
										p.Amount,
										@SuspendRRCOAAccountingType,
										@SuspendRRCalcTypeTrigger,
										@SuspendPercentage,
										@SuspendDays
	   
						from DATA_Sale
							inner join data_transaction			on data_transaction.saleid = data_sale.saleid
							left  join  (select settletransactionid, sum(data_payment.paymentamount) as amount
											from data_paymentcredit
												INNER JOIN DATA_Payment						on data_payment.paymentid = data_paymentcredit.paymentid
												INNER JOIN DATA_Transaction					on data_transaction.transactionid = data_paymentcredit.SettleTransactionId
											where ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
												  OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
											group by settletransactionid)p					on p.SettleTransactionId = data_transaction.transactionid

						where DATA_Sale.Paid = 1
							and data_transaction.transactiontype in (6)
							and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
							   OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))


					INSERT INTO [dbo].[RR_DATA_Revenue]
								([COAAccountId]
								,[RevenueRecognitionRuleId]
								,[RRCode]
								,[RRCalcTypeWhere]
								,[RRCalcTypeMethod]
								,[COAAccountConfigId]
								,[COAAccountType]
								,[COAAccountCode]
								,[TransactionId]
								,[SaleId]
								,[SaleItemId]
								,[MatrixCellId]
								,[MatrixCellCode]
								,[MatrixSheetID]
								,[SiteId]
								,[OperatingAreaId]
								,[WorkstationId]
								,[UserGroupId]
								,[UserId]
								,[FCalcDate]
								,[FRevenueDate]
								,[Quantity]
								,[UnitAmount]
								,[GrossAmount]
								,[NetAmount]
								,[Price]
								,[Percentage]
								,[RemaningValues]
								,[RevenueAmount]
								,[AccountingType]
								,[RRCalcTypeTrigger]
								,[RRPercentage]
								,[RRDays]
								,[AttributeIDS])
						select @SuspendCOAAccountId,
								@SuspendRRRId,
								@SuspendRRRCode,
								@SuspendRRCalcTypeWhere,
								@SuspendRRCalcTypeMethod,
								@SuspendCOAAccountConfigId,
								@SuspendCOAAccountTypeId,
								@SuspendCOAAccountCode,
								data_transaction.transactionid, 
								data_transaction.saleid,
								DATA_SaleItem.saleitemid,
								DATA_SaleItem.Matrixcellid,
								CNF_MatrixCell.Code,
								CNF_MatrixCell.MatrixSheetid,
								data_transaction.Siteid,
								data_transaction.OperatingAreaId,
								data_transaction.Workstationid,
								data_transaction.UserGroupid,
								data_transaction.UserId,
								@BatchDate,
								CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
									 else data_transaction.TransactionDate
								end TransactionDate,
								Coalesce(DATA_SaleItem.Quantity, 1),
								DATA_SaleItem.UnitPrice,
								case when isnull(DATA_SaleItem.TotalAmount, 0) &lt;&gt; 0 then DATA_SaleItem.TotalAmount
									when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
									else DATA_Sale.TotalAmount
								end,
								case when isnull((DATA_SaleItem.TotalAmount - DATA_SaleItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_SaleItem.TotalAmount - DATA_SaleItem.TotalTaxes)
									when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
									else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
								end as NetAmount,
								@SuspendPrice,
								@SuspendCOAAccount_Percentage,
								@SuspendRemainingValues,
								case    when (data_saleitem.ProductTaxType &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) 
												  and (isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0) 
													   and (((select discountamount from data_saleitemrule where saleitemid = DATA_SaleItem.saleitemid) &gt; 0) and (data_transaction.transactiontype in (7, 20, 22)))							
											then ((DATA_SaleItem.UnitRawPrice + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)


										when (data_saleitem.ProductTaxType &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice  + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)
										when (data_saleitem.ProductTaxType = 1) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice - DATA_SaleItem.unittaxes + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)
										when (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 then 0
										when (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 and data_saleitem.unitRecharge &lt;&gt; 0 then data_saleitem.unitRecharge
										when isnull((data_transaction.TotalAmount), 0) &lt;&gt; 0 then data_transaction.TotalAmount
										when isnull((DATA_Sale.TotalAmount), 0) &lt;&gt; 0 then DATA_Sale.TotalAmount
										else (data_transaction.Revenue)
								end,
								case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
										when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
										when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 1
										when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 2
										else @SuspendRRCOAAccountingType
								end Accountingtype,
								@SuspendRRCalcTypeTrigger,
								@SuspendPercentage,
								@SuspendDays,
								CNF_AttributeSet.Attributeids
	   
						from DATA_Sale
							inner join data_transaction			on data_transaction.saleid = data_sale.saleid
							left join DATA_SaleItem			    on DATA_SaleItem.saleid = DATA_Transaction.saleid
							left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
							left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

						where DATA_Sale.Paid = 1
							and data_transaction.transactiontype in (46, 47)
							and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
							   OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
							and data_transaction.transactionid in (select transactionid
																	from data_payment
																	where PaymentStatus = 1
																	and PaymentAmount &lt;&gt; 0
																)


					INSERT INTO [dbo].[RR_DATA_Revenue]
								([COAAccountId]
								,[RevenueRecognitionRuleId]
								,[RRCode]
								,[RRCalcTypeWhere]
								,[RRCalcTypeMethod]
								,[COAAccountConfigId]
								,[COAAccountType]
								,[COAAccountCode]
								,[TransactionId]
								,[SaleId]
								,[SaleItemId]
								,[MatrixCellId]
								,[MatrixCellCode]
								,[MatrixSheetID]
								,[SiteId]
								,[OperatingAreaId]
								,[WorkstationId]
								,[UserGroupId]
								,[UserId]
								,[FCalcDate]
								,[FRevenueDate]
								,[Quantity]
								,[UnitAmount]
								,[GrossAmount]
								,[NetAmount]
								,[Price]
								,[Percentage]
								,[RemaningValues]
								,[RevenueAmount]
								,[AccountingType]
								,[RRCalcTypeTrigger]
								,[RRPercentage]
								,[RRDays]
								,[AttributeIDS])
						select @SuspendCOAAccountId,
								@SuspendRRRId,
								@SuspendRRRCode,
								@SuspendRRCalcTypeWhere,
								@SuspendRRCalcTypeMethod,
								@SuspendCOAAccountConfigId,
								@SuspendCOAAccountTypeId,
								@SuspendCOAAccountCode,
								data_transaction.transactionid, 
								data_transaction.saleid,
								DATA_TransactionItem.saleitemid,
								DATA_SaleItem.Matrixcellid,
								CNF_MatrixCell.Code,
								CNF_MatrixCell.MatrixSheetid,
								data_transaction.Siteid,
								data_transaction.OperatingAreaId,
								data_transaction.Workstationid,
								data_transaction.UserGroupid,
								data_transaction.UserId,
								@BatchDate,
								CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
									 else data_transaction.TransactionDate
								end TransactionDate,
								Coalesce(DATA_TransactionItem.Quantity, 1),
								DATA_SaleItem.UnitPrice,
								case when isnull(DATA_TransactionItem.TotalAmount, 0) &lt;&gt; 0 then DATA_TransactionItem.TotalAmount
									when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
									else DATA_Sale.TotalAmount
								end,
								case when isnull((DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes)
									when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
									else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
								end as NetAmount,
								@SuspendPrice,
								@SuspendCOAAccount_Percentage,
								@SuspendRemainingValues,
								DATA_SaleItem.Unitrecharge,
								case    when TransactionType in (5, 17, 8, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
										when TransactionType in (5, 17, 8, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
										when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 2
										when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 1
										else @SuspendRRCOAAccountingType
								end Accountingtype,
								@SuspendRRCalcTypeTrigger,
								@SuspendPercentage,
								@SuspendDays,
								CNF_AttributeSet.Attributeids
	   
						from DATA_Sale
							inner join data_transaction			on data_transaction.TransactionId = ISNULL(data_sale.voidtransactionid, DATA_Sale.PaidTransactionId)
							left join DATA_TransactionItem		on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
							left join DATA_SaleItem			    on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
							left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
							left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

						where DATA_Sale.Paid = 1
							and data_transaction.transactiontype in (10, 42, 43, 49)
							and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
							   OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
							and data_transaction.transactionid in (select transactionid
																	from data_payment
																	where PaymentStatus = 1
																	and PaymentAmount &lt;&gt; 0
																)
			
				INSERT INTO [dbo].[RR_DATA_Revenue]
								([COAAccountId]
								,[RevenueRecognitionRuleId]
								,[RRCode]
								,[RRCalcTypeWhere]
								,[RRCalcTypeMethod]
								,[COAAccountConfigId]
								,[COAAccountType]
								,[COAAccountCode]
								,[TransactionId]
								,[SaleId]
								,[SaleItemId]
								,[MatrixCellId]
								,[MatrixCellCode]
								,[MatrixSheetID]
								,[SiteId]
								,[OperatingAreaId]
								,[WorkstationId]
								,[UserGroupId]
								,[UserId]
								,[FCalcDate]
								,[FRevenueDate]
								,[Quantity]
								,[UnitAmount]
								,[GrossAmount]
								,[NetAmount]
								,[Price]
								,[Percentage]
								,[RemaningValues]
								,[RevenueAmount]
								,[AccountingType]
								,[RRCalcTypeTrigger]
								,[RRPercentage]
								,[RRDays]
								,[AttributeIDS])
						select @SuspendCOAAccountId,
								@SuspendRRRId,
								@SuspendRRRCode,
								@SuspendRRCalcTypeWhere,
								@SuspendRRCalcTypeMethod,
								@SuspendCOAAccountConfigId,
								@SuspendCOAAccountTypeId,
								@SuspendCOAAccountCode,
								data_transaction.transactionid, 
								data_transaction.saleid,
								DATA_TransactionItem.saleitemid,
								DATA_SaleItem.Matrixcellid,
								CNF_MatrixCell.Code,
								CNF_MatrixCell.MatrixSheetid,
								data_transaction.Siteid,
								data_transaction.OperatingAreaId,
								data_transaction.Workstationid,
								data_transaction.UserGroupid,
								data_transaction.UserId,
								@BatchDate,
								CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
									 else data_transaction.TransactionDate
								end TransactionDate,
								Coalesce(DATA_TransactionItem.Quantity, 1),
								DATA_SaleItem.UnitPrice,
								case when isnull(DATA_TransactionItem.TotalAmount, 0) &lt;&gt; 0 then DATA_TransactionItem.TotalAmount
									when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
									else DATA_Sale.TotalAmount
								end,
								case when isnull((DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes)
									when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
									else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
								end as NetAmount,
								@SuspendPrice,
								@SuspendCOAAccount_Percentage,
								@SuspendRemainingValues,
								ABS(DATA_SaleItem.Unitrecharge),
								case    when TransactionType in (5, 17, 8, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
										when TransactionType in (5, 17, 8, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
										when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 2
										when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 1
										else @SuspendRRCOAAccountingType
								end Accountingtype,
								@SuspendRRCalcTypeTrigger,
								@SuspendPercentage,
								@SuspendDays,
								CNF_AttributeSet.Attributeids
	   
						from DATA_Sale
							inner join data_transaction			on data_transaction.TransactionId = ISNULL(data_sale.voidtransactionid, DATA_Sale.PaidTransactionId)
							left join DATA_TransactionItem		on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
							left join DATA_SaleItem			    on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
							left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
							left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

						where DATA_Sale.Paid = 1
							and data_transaction.transactiontype in (31, 48, 52)
							and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
							   OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
							and data_transaction.transactionid in (select transactionid
																	from data_payment
																	where PaymentStatus = 1
																	and PaymentAmount &lt;&gt; 0
																   )


					INSERT INTO [dbo].[RR_DATA_Revenue]
										([COAAccountId]
										,[RevenueRecognitionRuleId]
										,[RRCode]
										,[RRCalcTypeWhere]
										,[RRCalcTypeMethod]
										,[COAAccountConfigId]
										,[COAAccountType]
										,[COAAccountCode]
										,[TransactionId]
										,[SaleId]
										,[SaleItemId]
										,[MatrixCellId]
										,[MatrixCellCode]
										,[MatrixSheetID]
										,[SiteId]
										,[OperatingAreaId]
										,[WorkstationId]
										,[UserGroupId]
										,[UserId]
										,[FCalcDate]
										,[FRevenueDate]
										,[Quantity]
										,[UnitAmount]
										,[GrossAmount]
										,[NetAmount]
										,[Price]
										,[Percentage]
										,[RemaningValues]
										,[RevenueAmount]
										,[AccountingType]
										,[RRCalcTypeTrigger]
										,[RRPercentage]
										,[RRDays]
										,[AttributeIDS])
								select @SuspendCOAAccountId,
										@SuspendRRRId,
										@SuspendRRRCode,
										@SuspendRRCalcTypeWhere,
										@SuspendRRCalcTypeMethod,
										@SuspendCOAAccountConfigId,
										@SuspendCOAAccountTypeId,
										@SuspendCOAAccountCode,
										data_transaction.transactionid, 
										data_transaction.saleid,
										DATA_TransactionItem.saleitemid,
										DATA_SaleItem.Matrixcellid,
										CNF_MatrixCell.Code,
										CNF_MatrixCell.MatrixSheetid,
										data_transaction.Siteid,
										data_transaction.OperatingAreaId,
										data_transaction.Workstationid,
										data_transaction.UserGroupid,
										data_transaction.UserId,
										@BatchDate,
										CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
											 else data_transaction.TransactionDate
										end TransactionDate,
										Coalesce(DATA_TransactionItem.Quantity, 1),
										DATA_SaleItem.UnitPrice,
										case when isnull(DATA_TransactionItem.TotalAmount, 0) &lt;&gt; 0 then DATA_TransactionItem.TotalAmount
											when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
											else DATA_Sale.TotalAmount
										end,
										case when isnull((DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes)
											when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
											else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
										end as NetAmount,
										@SuspendPrice,
										@SuspendCOAAccount_Percentage,
										@SuspendRemainingValues,
										case when (data_saleitem.ProductTaxType &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice + DATA_SaleItem.unittaxes) * DATA_SaleItem.Quantity)
											 when (data_saleitem.ProductTaxType = 1) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice) * DATA_SaleItem.Quantity)
											 when (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 then 0
											 when isnull((data_transaction.TotalAmount), 0) &lt;&gt; 0 then data_transaction.TotalAmount
											 when isnull((DATA_Sale.TotalAmount), 0) &lt;&gt; 0 then DATA_Sale.TotalAmount
											 else (data_transaction.Revenue)
										end,
										case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
												when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
												when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 2
												when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 1
												else @SuspendRRCOAAccountingType
										end Accountingtype,
										@SuspendRRCalcTypeTrigger,
										@SuspendPercentage,
										@SuspendDays,
										CNF_AttributeSet.Attributeids
	   
								from DATA_Sale
									inner join data_transaction			on data_transaction.Saleid = DATA_Sale.Saleid
									left join DATA_TransactionItem		on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
									left join DATA_SaleItem			    on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
									left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
									left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

								where data_transaction.transactiontype in (8)
									and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
										OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
									and data_transaction.transactionid in (select transactionid
																			from data_payment
																			where PaymentStatus = 1
																			and PaymentAmount &lt;&gt; 0
																		)

							INSERT INTO [dbo].[RR_DATA_Revenue]
										([COAAccountId]
										,[RevenueRecognitionRuleId]
										,[RRCode]
										,[RRCalcTypeWhere]
										,[RRCalcTypeMethod]
										,[COAAccountConfigId]
										,[COAAccountType]
										,[COAAccountCode]
										,[TransactionId]
										,[SaleId]
										,[SiteId]
										,[OperatingAreaId]
										,[WorkstationId]
										,[UserGroupId]
										,[UserId]
										,[FCalcDate]
										,[FRevenueDate]
										,[Quantity]
										,[GrossAmount]
										,[NetAmount]
										,[Price]
										,[Percentage]
										,[RemaningValues]
										,[RevenueAmount]
										,[AccountingType]
										,[RRCalcTypeTrigger]
										,[RRPercentage]
										,[RRDays])
								select @SuspendCOAAccountId,
										@SuspendRRRId,
										@SuspendRRRCode,
										@SuspendRRCalcTypeWhere,
										@SuspendRRCalcTypeMethod,
										@SuspendCOAAccountConfigId,
										@SuspendCOAAccountTypeId,
										@SuspendCOAAccountCode,
										data_transaction.transactionid, 
										data_transaction.saleid,
										data_transaction.Siteid,
										data_transaction.OperatingAreaId,
										data_transaction.Workstationid,
										data_transaction.UserGroupid,
										data_transaction.UserId,
										@BatchDate,
										CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
											 else data_transaction.TransactionDate
										end TransactionDate,
										0 Quantity,
										data_transaction.revenue TotalAmount,
										data_transaction.revenue NetAmount,
										@SuspendPrice,
										@SuspendCOAAccount_Percentage,
										@SuspendRemainingValues,
										data_transaction.revenue,
										@SuspendRRCOAAccountingType,
										@SuspendRRCalcTypeTrigger,
										@SuspendPercentage,
										@SuspendDays
	   
								from DATA_Sale
									inner join data_transaction			on data_transaction.saleid = DATA_Sale.saleid
								where data_transaction.transactiontype = 12
									and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
										OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
									and data_transaction.transactionid in (select transactionid
																			from data_payment
																			where PaymentStatus = 1
																			and PaymentAmount &lt;&gt; 0
																		)



								INSERT INTO [dbo].[RR_DATA_Revenue]
										([COAAccountId]
										,[RevenueRecognitionRuleId]
										,[RRCode]
										,[RRCalcTypeWhere]
										,[RRCalcTypeMethod]
										,[COAAccountConfigId]
										,[COAAccountType]
										,[COAAccountCode]
										,[TransactionId]
										,[SaleId]
										,[SaleItemId]
										,[MatrixCellId]
										,[MatrixCellCode]
										,[MatrixSheetID]
										,[SiteId]
										,[OperatingAreaId]
										,[WorkstationId]
										,[UserGroupId]
										,[UserId]
										,[FCalcDate]
										,[FRevenueDate]
										,[Quantity]
										,[UnitAmount]
										,[GrossAmount]
										,[NetAmount]
										,[Price]
										,[Percentage]
										,[RemaningValues]
										,[RevenueAmount]
										,[AccountingType]
										,[RRCalcTypeTrigger]
										,[RRPercentage]
										,[RRDays]
										,[AttributeIDS])
										select *
										from (
								select @SuspendCOAAccountId as COAAccountId,
										@SuspendRRRId as RevenueRecognitionRuleId,
										@SuspendRRRCode as RRCode,
										@SuspendRRCalcTypeWhere as RRCalcTypeWhere,
										@SuspendRRCalcTypeMethod as RRCalcTypeMethod,
										@SuspendCOAAccountConfigId as COAAccountConfigId,
										@SuspendCOAAccountTypeId as COAAccountType,
										@SuspendCOAAccountCode as COAAccountCode,
										data_transaction.transactionid, 
										data_transaction.saleid,
										DATA_SaleItem.saleitemid,
										DATA_SaleItem.Matrixcellid,
										CNF_MatrixCell.Code,
										CNF_MatrixCell.MatrixSheetid,
										data_transaction.Siteid,
										data_transaction.OperatingAreaId,
										data_transaction.Workstationid,
										data_transaction.UserGroupid,
										data_transaction.UserId,
										@BatchDate as calcdate,
										CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
												else data_transaction.TransactionDate
										end TransactionDate,
										Coalesce(DATA_SaleItem.Quantity, 1) as quantity,
										DATA_SaleItem.UnitPrice,
										case when isnull(DATA_SaleItem.TotalAmount, 0) &lt;&gt; 0 then DATA_SaleItem.TotalAmount
											when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
											else DATA_Sale.TotalAmount
										end as totalamount,
										case when isnull((DATA_SaleItem.TotalAmount - DATA_SaleItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_SaleItem.TotalAmount - DATA_SaleItem.TotalTaxes)
											when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
											else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
										end as NetAmount,
										@SuspendPrice as suspendprice,
										@SuspendCOAAccount_Percentage as percentage,
										@SuspendRemainingValues as remainingValues,
										case when (data_saleitem.ProductTaxType &lt;&gt; 1) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice) * DATA_SaleItem.Quantity)
											 when (data_saleitem.ProductTaxType = 1) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice - DATA_SaleItem.unittaxes) * DATA_SaleItem.Quantity)
											 when isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 then 0
											 when isnull((data_transaction.TotalAmount), 0) &lt;&gt; 0 then data_transaction.TotalAmount
											 when isnull((DATA_Sale.TotalAmount), 0) &lt;&gt; 0 then DATA_Sale.TotalAmount
											 else (data_transaction.Revenue)
										end as Revenueamount,
										case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
												when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
												when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 2
												when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 1
												else @SuspendRRCOAAccountingType
										end Accountingtype,
										@SuspendRRCalcTypeTrigger as rrTrigger,
										@SuspendPercentage as suspercentage,
										@SuspendDays as suspendday,
										CNF_AttributeSet.Attributeids
	   
								from DATA_Sale
									inner join data_transaction			on data_transaction.TransactionId = DATA_Sale.PaidTransactionId
									left join DATA_SaleItem			    on DATA_SaleItem.SAleid = data_transaction.SAleid
									left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
									left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

								where DATA_Sale.Paid = 1
									and data_transaction.transactiontype in (16)
									and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
									 OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
									and data_transaction.transactionid in (select transactionid
																			from data_payment
																			where PaymentStatus = 1
																			--and PaymentAmount &lt;&gt; 0
																		)
									and data_transaction.transactionid not in (select distinct transactionid
																				from rr_data_Revenue
																				where transactionid is not null)
									and data_saleitem.saleitemid not in (select distinct data_saleitem.saleitemid
																	from data_saleitem
																			inner join data_transactionitem   on data_transactionitem.saleitemid = data_saleitem.saleitemid
																			inner join data_transaction       on data_transaction.transactionid = data_transactionitem.transactionid
																	where data_transaction.transactiontype in (5)
																	)
									)p  where UnitPrice &lt;&gt; 0


								INSERT INTO [dbo].[RR_DATA_Revenue]
										([COAAccountId]
										,[RevenueRecognitionRuleId]
										,[RRCode]
										,[RRCalcTypeWhere]
										,[RRCalcTypeMethod]
										,[COAAccountConfigId]
										,[COAAccountType]
										,[COAAccountCode]
										,[TransactionId]
										,[SaleId]
										,[SaleItemId]
										,[MatrixCellId]
										,[MatrixCellCode]
										,[MatrixSheetID]
										,[SiteId]
										,[OperatingAreaId]
										,[WorkstationId]
										,[UserGroupId]
										,[UserId]
										,[FCalcDate]
										,[FRevenueDate]
										,[Quantity]
										,[UnitAmount]
										,[GrossAmount]
										,[NetAmount]
										,[Price]
										,[Percentage]
										,[RemaningValues]
										,[RevenueAmount]
										,[AccountingType]
										,[RRCalcTypeTrigger]
										,[RRPercentage]
										,[RRDays]
										,[AttributeIDS])
								select @SuspendCOAAccountId,
										@SuspendRRRId,
										@SuspendRRRCode,
										@SuspendRRCalcTypeWhere,
										@SuspendRRCalcTypeMethod,
										@SuspendCOAAccountConfigId,
										@SuspendCOAAccountTypeId,
										@SuspendCOAAccountCode,
										data_transaction.transactionid, 
										data_transaction.saleid,
										DATA_TransactionItem.saleitemid,
										DATA_SaleItem.Matrixcellid,
										CNF_MatrixCell.Code,
										CNF_MatrixCell.MatrixSheetid,
										data_transaction.Siteid,
										data_transaction.OperatingAreaId,
										data_transaction.Workstationid,
										data_transaction.UserGroupid,
										data_transaction.UserId,
										@BatchDate,
										CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
											 else data_transaction.TransactionDate
										end TransactionDate,
										Coalesce(DATA_TransactionItem.Quantity, 1),
										DATA_SaleItem.UnitPrice,
										case when isnull(DATA_TransactionItem.TotalAmount, 0) &lt;&gt; 0 then DATA_TransactionItem.TotalAmount
											when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
											else DATA_Sale.TotalAmount
										end,
										case when isnull((DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes)
											when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
											else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
										end as NetAmount,
										@SuspendPrice,
										@SuspendCOAAccount_Percentage,
										@SuspendRemainingValues,
										case when isnull((DATA_TransactionItem.UnitPrice *  DATA_TransactionItem.Quantity), 0) &lt;&gt; 0 then (DATA_TransactionItem.UnitPrice *  DATA_TransactionItem.Quantity)
											when isnull((data_transaction.TotalAmount), 0) &lt;&gt; 0 then data_transaction.TotalAmount
											when isnull((DATA_Sale.TotalAmount), 0) &lt;&gt; 0 then DATA_Sale.TotalAmount
											else (data_transaction.Revenue)
										end,
										case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
												when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
												when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 2
												when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 1
												else @SuspendRRCOAAccountingType
										end Accountingtype,
										@SuspendRRCalcTypeTrigger,
										@SuspendPercentage,
										@SuspendDays,
										CNF_AttributeSet.Attributeids
	   
								from DATA_Sale
									inner join data_transaction			on data_transaction.saleid = DATA_Sale.saleid
									inner join DATA_TransactionItem		on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
									left join DATA_SaleItem			    on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
									left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
									left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

								where DATA_Sale.Paid = 1
									and data_transaction.transactiontype in (5)
									and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
									 OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
					
									and data_transaction.transactionid in (select transactionid
																			from data_payment
																			where PaymentStatus = 1
																			and PaymentAmount &lt;&gt; 0
																		)
									and data_transaction.transactionid not in (select distinct transactionid
																				from rr_data_Revenue
																				where transactionid is not null)

				--PaymentMethod
								INSERT INTO [dbo].[RR_DATA_Revenue]
												([COAAccountId]
												,[RevenueRecognitionRuleId]
												,[RRCode]
												,[RRCalcTypeWhere]
												,[RRCalcTypeMethod]
												,[COAAccountConfigId]
												,[COAAccountType]
												,[COAAccountCode]
												,[TransactionId]
												,[SaleId]
												,[SiteId]
												,[OperatingAreaId]
												,[WorkstationId]
												,[UserGroupId]
												,[UserId]
												,[FCalcDate]
												,[FRevenueDate]
												,[Quantity]
												,[GrossAmount]
												,[NetAmount]
												,[Price]
												,[Percentage]
												,[RemaningValues]
												,[RevenueAmount]
												,[AccountingType]
												,[RRCalcTypeTrigger]
												,[RRPercentage]
												,[RRDays])
												select  coaaccountid,
														RRID,
														RRCode,
														TypeWhere,
														method,
														Configid,
														AccountType,
														AccountCode,
														transactionid, 
														saleid,
														Siteid,
														OperatingAreaId,
														WorkstationID,
														UserGroupid,
														UserId,
														BatchDate,
														TransactionDate,
														Qty,
														Gross,
														net,
														price,
														percentage,
														RemaningValue,
														sum(abs(RevenueAmount)),
														Accountingtype,
														TypeTrigger,
														PaymentPercentage,
														RRDays
												from (
												select  coaaccountid,
														RRID,
														RRCode,
														TypeWhere,
														method,
														Configid,
														AccountType,
														AccountCode,
														transactionid, 
														saleid,
														Siteid,
														OperatingAreaId,
														WorkstationID,
														UserGroupid,
														UserId,
														BatchDate,
														TransactionDate,
														Qty,
														Gross,
														net,
														price,
														percentage,
														RemaningValue,
														case when Rownumber = 1 then RevenueAmount + Change
															 else RevenueAmount
														 end RevenueAmount,
														Accountingtype,
														TypeTrigger,
														PaymentPercentage,
														RRDays
												from (
												select @PaymentCOAAccountId as coaaccountid,
														@PaymentRRRId as RRID,
														@PaymentRRRCode as RRCode,
														@PaymentRRCalcTypeWhere as TypeWhere,
														@PaymentRRCalcTypeMethod as method,
														@PaymentCOAAccountConfigId as Configid,
														@PaymentCOAAccountTypeId as AccountType,
														@PaymentCOAAccountCode as AccountCode,
														data_transaction.transactionid, 
														data_transaction.saleid,
														data_transaction.Siteid,
														data_transaction.OperatingAreaId,
														data_transaction.Workstationid,
														data_transaction.UserGroupid,
														data_transaction.UserId,
														@BatchDate as BatchDate,
														CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
															 else data_transaction.TransactionDate
														end TransactionDate,
														0 as Qty,
														0 as Gross,
														0 as net,
														0 as price,
														100 as percentage,
														0 as RemaningValue,
														(data_payment.PaymentAmount) as RevenueAmount,
														case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @PaymentRRCOAAccountingType = 1 then 2
																when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @PaymentRRCOAAccountingType = 2 then 1
																when TransactionType in (7) and (data_payment.PaymentAmount + data_Payment.PaymentFee) &lt;= 0  then 2
																when TransactionType in (7) and (data_payment.PaymentAmount + data_Payment.PaymentFee) &gt; 0  then 1
																else @PaymentRRCOAAccountingType
														end Accountingtype,
														data_transaction.Change,
														@PaymentRRCalcTypeTrigger as TypeTrigger,
														@PaymentPercentage as PaymentPercentage,
														@PaymentDays as RRDays,
														Row_Number ()  OVER (PARTITION BY data_transaction.transactionid order by data_transaction.transactionid)  as Rownumber
		  
												from DATA_Sale
															INNER join data_transaction			on ((data_transaction.TransactionId = Isnull(data_sale.voidtransactionid, DATA_Sale.PaidTransactionId)) or 
																								   (data_transaction.saleid = data_sale.saleid))
															INNER JOIN DATA_Payment				on data_payment.transactionid = data_transaction.transactionid
			
												where data_payment.PaymentStatus = 1
													and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
													 OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
											)p
											)r
											group by 	coaaccountid,
														RRID,
														RRCode,
														TypeWhere,
														method,
														Configid,
														AccountType,
														AccountCode,
														transactionid, 
														saleid,
														Siteid,
														OperatingAreaId,
														Workstationid,
														UserGroupid,
														UserId,
														BatchDate,
														TransactionDate,
														Qty,
														Gross,
														net,
														price,
														percentage,
														RemaningValue,
														Accountingtype,
														TypeTrigger,
														PaymentPercentage,
														RRDays
											Having sum(abs(RevenueAmount)) &lt;&gt; 0
						



				--Tax
									INSERT INTO [dbo].[RR_DATA_Revenue]
												([COAAccountId]
												,[RevenueRecognitionRuleId]
												,[RRCode]
												,[RRCalcTypeWhere]
												,[RRCalcTypeMethod]
												,[COAAccountConfigId]
												,[COAAccountType]
												,[COAAccountCode]
												,[TransactionId]
												,[SaleId]
												,[SiteId]
												,[OperatingAreaId]
												,[WorkstationId]
												,[UserGroupId]
												,[UserId]
												,[FCalcDate]
												,[FRevenueDate]
												,[Quantity]
												,[GrossAmount]
												,[NetAmount]
												,[Price]
												,[Percentage]
												,[RemaningValues]
												,[RevenueAmount]
												,[AccountingType]
												,[RRCalcTypeTrigger]
												,[RRPercentage]
												,[RRDays])

												select  @TaxCOAAccountId,
														@TaxRRRId,
														@TaxRRRCode,
														@TaxRRCalcTypeWhere,
														@TaxRRCalcTypeMethod,
														@TaxCOAAccountConfigId,
														@TaxCOAAccountTypeId,
														@TaxCOAAccountCode,
														data_transaction.transactionid, 
														data_transaction.saleid,
														data_transaction.Siteid,
														data_transaction.OperatingAreaId,
														data_transaction.Workstationid,
														data_transaction.UserGroupid,
														data_transaction.UserId,
														@BatchDate,
														CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
															 else data_transaction.TransactionDate
														end TransactionDate,
														0,
														0,
														0,
														0,
														100,
														0,
														ABS(sum(taxamount)) RevenueAmount,
														case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @TaxRRCOAAccountingType = 1 then 2
																when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @TaxRRCOAAccountingType = 2 then 1
																when TransactionType in (7) and sum(taxamount) &lt;= 0  then 1
																when TransactionType in (7) and sum(taxamount) &gt; 0  then 2
																else @TaxRRCOAAccountingType
														end Accountingtype,
														@TaxRRCalcTypeTrigger,
														@TaxPercentage,
														@TaxDays
		   
											from Data_Sale
												INNER JOIN DATA_Transaction						on data_transaction.Saleid = Data_Sale.Saleid
												INNER JOIN DATA_TransactionTax					on data_transactiontax.transactionid = data_transaction.transactionid
												INNER JOIN CNF_Tax								on cnf_tax.taxid = DATA_TransactionTax.taxid
												--INNER JOIN coa_cnf_account coa					on coa.coaaccountid = cnf_tax.coaaccountid


											where transactiontype NOT IN (33, 45, 46, 47)
											   and Data_Sale.paid = 1
												and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
												 OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
												  and data_transaction.transactionid in (select distinct transactionid
																						   from data_payment
																						   where data_payment.paymentstatus = 1
																						)
											group by 			data_transaction.transactionid, 
																data_transaction.saleid,
																data_transaction.Siteid,
																data_transaction.OperatingAreaId,
																data_transaction.Workstationid,
																data_transaction.UserGroupid,
																data_transaction.UserId,
																Data_Transaction.TransactionDate,
																TransactionType,
																fTransactionDate


				--Discount

										INSERT INTO [dbo].[RR_DATA_Revenue]
												([COAAccountId]
												,[RevenueRecognitionRuleId]
												,[RRCode]
												,[RRCalcTypeWhere]
												,[RRCalcTypeMethod]
												,[COAAccountConfigId]
												,[COAAccountType]
												,[COAAccountCode]
												,[TransactionId]
												,[SaleId]
												,[SiteId]
												,[OperatingAreaId]
												,[WorkstationId]
												,[UserGroupId]
												,[UserId]
												,[FCalcDate]
												,[FRevenueDate]
												,[Quantity]
												,[GrossAmount]
												,[NetAmount]
												,[Price]
												,[Percentage]
												,[RemaningValues]
												,[RevenueAmount]
												,[AccountingType]
												,[RRCalcTypeTrigger]
												,[RRPercentage]
												,[RRDays])

												select  @DiscountCOAAccountId,
														@DiscountRRRId,
														@DiscountRRRCode,
														@DiscountRRCalcTypeWhere,
														@DiscountRRCalcTypeMethod,
														@DiscountCOAAccountConfigId,
														@DiscountCOAAccountTypeId,
														@DiscountCOAAccountCode,
														data_transaction.transactionid, 
														data_transaction.saleid,
														data_transaction.Siteid,
														data_transaction.OperatingAreaId,
														data_transaction.Workstationid,
														data_transaction.UserGroupid,
														data_transaction.UserId,
														@BatchDate,
														CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
															 else data_transaction.TransactionDate
														end TransactionDate,
														0,
														0,
														0,
														0,
														100,
														0,
														ABS(p.GLAmount) RevenueAmount,
														case    when data_transaction.TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) then 2
																when data_transaction.TransactionType in (7) and (GLAmount) &lt;= 0  then 2
																when data_transaction.TransactionType in (7) and (GLAmount) &gt; 0  then 1
																else @DiscountRRCOAAccountingType
														end Accountingtype,

														@DiscountRRCalcTypeTrigger,
														@DiscountPercentage,
														@DiscountDays
											FROM
											(
												SELECT distinct DATA_SaleItem.Saleitemid,
																DATA_Sale.saleid AS SAleid,
      															DATA_Transaction.TransactionType,
      															( SELECT top 1 transactionid
																	FROM data_transaction		WITH (NOLOCK)
																   WHERE saleid = DATA_Sale.saleid
																	AND transactiontype in (14, 16)
																	AND paid = 1
																) AS tester,

																CASE WHEN DATA_Transaction.TransactionId IN (
																											  SELECT TR.TransactionID
																												FROM DATA_Transaction TR			WITH (NOLOCK)
																													LEFT JOIN DATA_Payment DP		WITH (NOLOCK) ON TR.TransactionId = DP.TransactionId
																											  WHERE TR.SaleId = DATA_Sale.SaleId
																												AND TR.Paid = 1
																												AND DP.PaymentStatus NOT IN (0, 2, 3)
																											)
      
																			THEN DATA_Transaction.Transactionid
																	 ELSE (
																			  SELECT MIN(TR.TransactionID)
																				FROM DATA_Transaction TR				WITH (NOLOCK)
																					LEFT JOIN DATA_Payment DP			WITH (NOLOCK) ON TR.TransactionId = DP.TransactionId
																			   WHERE TR.SaleId = DATA_Sale.saleid
																				 AND TR.TransactionType = 16
																				 AND TR.Paid = 1
																				 AND DP.PaymentStatus NOT IN (0, 2, 3)
																		  )
																END Transactionid, 
																 CASE WHEN CNF_Promotion.PromotionType = 1 AND CNF_PromotionItemRule.NewProduct = 1 THEN  (CNF_MatrixCell.Price - SUM(DATA_SaleItemRule.DiscountAmount))
																	  ELSE  CASE WHEN sum(1*data_saleItemRule.DiscountAmount) &lt; 0 AND transactiontype IN(20, 22, 30, 7, 5, 46, 47) AND
																																												(SELECT Count(*) 
																																												   FROM data_transaction WITH (NOLOCK)
																																												  WHERE saleid = data_sale.saleid
																																												 ) = 1 					  					  					  										  
																					  THEN Sum(1 * DATA_SaleItemRule.DiscountAmount)
																				 WHEN sum(1*data_saleItemRule.DiscountAmount) &lt; 0 THEN	Sum(-1 * DATA_SaleItemRule.DiscountAmount)
																				 WHEN sum(1*data_saleItemRule.DiscountAmount) &gt; 0 AND transactiontype IN(20, 22, 30, 7, 5, 46, 47) THEN Sum(-1 * DATA_SaleItemRule.DiscountAmount)		            	                  
																				 ELSE sum(1*Data_SaleItemRule.DiscountAmount)
																			END
																END AS GLAmount


												FROM dbo.DATA_SaleItemRule				WITH (NOLOCK)
													LEFT JOIN dbo.CNF_PromotionItemRule WITH (NOLOCK) ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
													LEFT JOIN dbo.CNF_PromotionItem		WITH (NOLOCK) ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
													LEFT JOIN dbo.CNF_Promotion			WITH (NOLOCK) ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId
													LEFT JOIN dbo.CNF_DmgCategory		WITH (NOLOCK) ON CNF_DmgCategory.DmgCategoryId = CNF_Promotion.DmgCategoryId
													LEFT JOIN dbo.DATA_SaleItem			WITH (NOLOCK) ON DATA_SaleItem.SaleItemId = DATA_SaleItemRule.SaleItemId
													LEFT JOIN dbo.DATA_Sale				WITH (NOLOCK) ON DATA_Sale.SaleID = DATA_SaleItem.SaleID
													LEFT JOIN DATA_TransactionItem		WITH (NOLOCK) ON DATA_TransactionItem.SaleItemId = DATA_SaleItem.SaleItemId 
													LEFT JOIN DATA_Transaction			WITH (NOLOCK) ON  DATA_Transaction.TransactionId = DATA_TransactionItem.TransactionId
													LEFT JOIN CNF_MatrixCell			WITH (NOLOCK) ON CNF_MatrixCell.MatrixCellId =  DATA_SaleItem.MatrixCellId

 
												WHERE DATA_Transaction.saleid in (
																					SELECT ff.saleid 
																					  FROM DATA_Transaction ff WITH (NOLOCK) 
																						LEFT JOIN Data_Payment WITH (NOLOCK) on (ff.Transactionid = Data_Payment.Transactionid) 
																					 WHERE  ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
																						OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
																					   AND DATA_PAyment.PaymentStatus NOT in (0,2,3) 
																					   AND (TransactionType not in (12)) 
																					   AND ff.PAid = 1
																				 )  

												 AND DATA_Sale.Paid = 1
												 and transactiontype NOT IN (33, 45, 46, 47)
												 AND ((DATA_SaleItem.quantity &gt; 0) OR ((DATA_SaleItem.quantity &lt; 0) AND (transactiontype IN (20, 22, 30, 7, 5, 46, 47))))

         
												group BY DATA_SaleItem.Saleitemid,
														 DATA_Sale.saleid,
														 Data_transaction.Paid,
														 Data_Transaction.Transactionid,
														 Data_Transaction.fTransactionDate,
														 Data_Saleitem.Matrixcellid,
														 CNF_DmgCategory.DmgCategoryCode,
														 PromotionType,
														 CNF_PromotionItemRule.NewProduct,
														 CNF_MatrixCell.Price,
														 transactiontype,
														 CNF_DmgCategory.Description
											)p
												LEFT JOIN data_transaction WITH (NOLOCK) on data_transaction.transactionid = p.transactionid

											WHERE ((p.TransactionType &lt;&gt; 5) or (Tester is not null))
											  AND data_transaction.transactionid is not null


					
						--End Move Transactions to Suspend Account

						exec otn_sp_RR_RevenueData_OnDepositTrigger @BatchDate, @RRTransDateType

						exec otn_sp_RR_RevenueData_OnSaleTrigger @BatchDate, @RRTransDateType
		
						exec otn_sp_RR_RevenueData_OnMoneyCardLoad @BatchDate, @RRTransDateType

						exec otn_sp_RR_RevenueData_OnMoneyCardCashOut @BatchDate, @RRTransDateType

						exec otn_sp_RR_RevenueData_OnExternalMoneyCardCashOut @BatchDate, @RRTransDateType

						exec otn_sp_RR_RevenueData_OnExternalMoneyCardLoad @BatchDate, @RRTransDateType

						exec otn_sp_RR_RevenueData_OnCreditWriteoff @BatchDate, @RRTransDateType

						exec otn_sp_RR_RevenueData_OnMoneyRefundTrigger @BatchDate, @RRTransDateType

						exec otn_sp_RR_RevenueData_OnAdvancedPaymentTrigger @BatchDate, @RRTransDateType
		
						--exec otn_sp_RR_RevenueData_OnFlexContractPayment @BatchDate, @RRTransDateType

						--exec otn_sp_RR_RevenueData_OnFlexContractCancelled @BatchDate, @RRTransDateType

						exec otn_sp_RR_RevenueData_OnCreditSettlementTrigger @BatchDate, @RRTransDateType
		
						exec otn_sp_RR_RevenueData_SettleUpSuspendAccount @BatchDate, @RRTransDateType


						exec otn_sp_RR_RevenueData_OnTicketUsageTrigger @BatchDate, @RRTransDateType

						exec otn_sp_RR_RevenueData_OnEventTrigger @BatchDate, @RRTransDateType

						exec otn_sp_RR_RevenueData_OnTimePeriodTrigger @BatchDate, @RRTransDateType

						exec otn_sp_RR_RevenueData_OnTicketExpiredTrigger @BatchDate, @RRTransDateType

						--exec otn_sp_RR_RevenueData_OnChangeValiditydateTrigger @BatchDate, @RRTransDateType
		

	FETCH NEXT FROM date_Cursor INTO
		@BatchDate

end

End
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT> IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_RR_RevenueData_OnTimePeriodTrigger]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_RR_RevenueData_OnTimePeriodTrigger
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>CREATE Procedure dbo.otn_sp_RR_RevenueData_OnTimePeriodTrigger
	@BatchDate Date,
	@RRTransDateType Integer
AS 
BEGIN
	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer
	Declare @OnTimePeriodTrigger Integer = 4	

	create table #RulesToRun
	(
		RRID int
	)

	Declare @TodayDayofWeek Int
	Declare @TodaySpecificDay Int
	Declare @TodayMonthlyWeek Int
	Declare @TodayMonth Int
	Declare @TodayDay Int
	Declare @TodayDaysofWeek Int

	select @TodayDayofWeek   = datePart(weekday, cast(@BatchDate as date)),
		   @TodayMonth       = datePart(mm, cast(@BatchDate as date)),
		   @TodaySpecificDay = datePart(dd, cast(@BatchDate as date)),
		   @TodayMonthlyWeek = datediff(week, dateadd(week, datediff(week, 0, dateadd(month, datediff(month, 0, cast(@BatchDate as date)), 0)), 0), getdate() - 1) + 1

	if @TodayDaysofWeek = 6 
	   SET @TodayDaysofWeek = 1

	insert into #RulesToRun
	select	distinct RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
		from RR_CNF_RevenueRecognitionRuleSchedule
			INNER JOIN RR_CNF_RevenueRecognitionRule					ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRuleSchedule.RevenueRecognitionRuleId

	where RR_CNF_RevenueRecognitionRule.Enabled = 1
	  and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
	  and ((PeriodOption = 1)
			  or ((PeriodOption = 2) and (((@TodayDayofWeek = 1) and (ActiveSunday = 1))
											or ((@TodayDayofWeek = 2) and (ActiveMonday = 1))
											or ((@TodayDayofWeek = 3) and (ActiveTuesday = 1))
											or ((@TodayDayofWeek = 4) and (ActiveWednesday = 1))
											or ((@TodayDayofWeek = 5) and (ActiveThursday = 1))
											or ((@TodayDayofWeek = 6) and (ActiveFriday = 1))
											or ((@TodayDayofWeek = 6) and (ActiveFriday = 1))
											or ((@TodayDayofWeek = 7) and (ActiveSaturday = 1))
										)))
			 or ((PeriodOption = 3) and ((SpecificDay = @TodaySpecificDay) 
										  or ((WeekOption = @TodayMonthlyWeek and (((@TodayDayofWeek = 1) and (ActiveSunday = 1))
																					or ((@TodayDayofWeek = 2) and (ActiveMonday = 1))
																					or ((@TodayDayofWeek = 3) and (ActiveTuesday = 1))
																					or ((@TodayDayofWeek = 4) and (ActiveWednesday = 1))
																					or ((@TodayDayofWeek = 5) and (ActiveThursday = 1))
																					or ((@TodayDayofWeek = 6) and (ActiveFriday = 1))
																					or ((@TodayDayofWeek = 6) and (ActiveFriday = 1))
																					or ((@TodayDayofWeek = 7) and (ActiveSaturday = 1))
																					or (LastDayOptionWeek = 1))
																				))))  
			 or ((PeriodOption = 4) and (((SpecificDay = @TodaySpecificDay) and (MonthOption = @TodayMonth))  
										   or ((WeekOption = @TodayMonthlyWeek and (((@TodayDayofWeek = 1) and (ActiveSunday = 1))
																					or ((@TodayDayofWeek = 2) and (ActiveMonday = 1))
																					or ((@TodayDayofWeek = 3) and (ActiveTuesday = 1))
																					or ((@TodayDayofWeek = 4) and (ActiveWednesday = 1))
																					or ((@TodayDayofWeek = 5) and (ActiveThursday = 1))
																					or ((@TodayDayofWeek = 6) and (ActiveFriday = 1))
																					or ((@TodayDayofWeek = 6) and (ActiveFriday = 1))
																					or ((@TodayDayofWeek = 7) and (ActiveSaturday = 1))
																					or (LastDayOptionWeek = 1))
																				)))
																				and (MonthOption = @TodayMonth))



			INSERT INTO [dbo].[RR_DATA_Revenue]
						   ([COAAccountId]
						   ,[RevenueRecognitionRuleId]
						   ,[RRCode]
						   ,[RRCalcTypeWhere]
						   ,[RRCalcTypeMethod]
						   ,[COAAccountConfigId]
						   ,[COAAccountType]
						   ,[COAAccountCode]
						   ,[SaleId]
						   ,[Ticketid]
						   ,[MatrixCellid]
						   ,[MatrixCellCode]
						   ,[MatrixSheetid]
						   ,[SiteId]
						   ,[OperatingAreaId]
						   ,[WorkstationId]
						   ,[Usergroupid]
						   ,[UserId]
						   ,[FCalcDate]
						   ,[FRevenueDate]
						   ,[Quantity]
						   ,[GrossAmount]
						   ,[NetAmount]
						   ,[Price]
						   ,[Percentage]
						   ,[RemaningValues]
						   ,[RevenueAmount]
						   ,[AccountingType]
						   ,[RRCalcTypeTrigger]
						   ,[RRPercentage]			
						   ,[RRDays]
						   ,[AttributeIDs]
						   )
						   select *
						   from (
							select distinct p.COAAccountId, 
								   p.RevenueRecognitionRuleId,
								   p.RRcode,		   
								   p.RRCalcTypeWhere,
								   p.RRCalcTypeMethod,	   
								   p.COAAccountConfigId,
								   p.COAAccountTypeId,
								   p.AccountCode as AccountCode,
								   RR_DATA_REVENUE.saleid as Saleid,
								   ISNULL(rdata.Ticketid, DATA_SaleItem2Ticket.Ticketid) TicketID, 
								   RR_DATA_REVENUE.Matrixcellid,
								   RR_DATA_REVENUE.MatrixcellCode,
								   RR_DATA_REVENUE.MatrixSheetId,
								   RR_DATA_REVENUE.Siteid,
								   RR_DATA_REVENUE.OperatingAreaId,
								   RR_DATA_REVENUE.Workstationid,
								   RR_DATA_REVENUE.UserGroupid,
								   RR_DATA_REVENUE.UserId as userID,
								   @BatchDate as BatchDate,
								   @BatchDate as TransDate,
								   RR_DATA_REVENUE.Quantity as Quantity,
								   RR_DATA_REVENUE.GrossAmount as GrossAmount,
								   RR_DATA_REVENUE.NetAmount as NetAmount,
								   p.Price as ConfigPrice,
								   p.Percentage as ConfigPercentage,
								   p.RemainingValues,																		
								  round(Case when p.Price &gt; 0 then (p.Price) 
									   else case when ((((DATA_Ticket.Price - DATA_Ticket.taxes) - ISNULL(rdata.TotalUsed, 0)) &gt; 0) and ((DATA_Ticket.Price - DATA_Ticket.taxes) - ISNULL(rdata.TotalUsed, 0)) &gt;= ((((DATA_Ticket.Price - DATA_Ticket.taxes) * p.RRPercentage)/100 * p.Percentage)/100)) 
										              then ((((DATA_Ticket.Price - DATA_Ticket.taxes) * p.RRPercentage)/100 * p.Percentage)/100)
									              else (((DATA_Ticket.Price - DATA_Ticket.taxes) - ISNULL(rdata.TotalUsed, 0)) * p.Percentage)/100
								            end
							       end, 2) as RevenueAmount,
								   p.Accountingtype,
								   p.RRCalcTypeTrigger,
								   p.RRPercentage,
								   p.Days,
								   RR_DATA_REVENUE.AttributeIDs

							from RR_DATA_REVENUE
								INNER JOIN DATA_SaleItem							ON data_saleitem.SaleItemId		   = rr_data_revenue.saleitemid
								INNER JOIN DATA_SaleItem2Ticket						on data_saleitem2ticket.Saleitemid = data_saleitem.saleitemid
								INNER JOIN DATA_Ticket								on data_ticket.ticketid = data_saleitem2ticket.ticketid
								INNER JOIN (  
										select  RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleid, 
										RR_CNF_RevenueRecognitionRule.Code as RRCode,
										RR_CNF_RevenueRecognitionRule.Days,
										RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
										RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,
										FromDate,
										ToDate,
										RR_CNF_RevenueRecognitionRule.rrCalcTypeTrigger,
										RR_CNF_RevenueRecognitionRule.Percentage as RRPercentage,
										COA_CNF_AccountConfig.CoaAccountid,
										COA_CNF_AccountConfig.AccountingType,
										COA_CNF_AccountConfig.Price,
										COA_CNF_AccountConfig.Percentage,
										COA_CNF_AccountConfig.RemainingValues,
										COA_CNF_AccountConfig.SiteID,
										coa_cnf_account.code as AccountCode,
										COA_CNF_AccountType.Code as AccountTypeCode,
										COA_CNF_AccountType.COAAccountTypeId,
										rr_cnf_Product.MatrixcellID,
										rr_cnf_Product.matrixsheetID,
										COA_CNF_AccountConfig.COAAccountConfigId,
										rr_cnf_Product.AttributeId

								from RR_CNF_RevenueRecognitionRule
									inner join rr_cnf_Product						ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_cnf_product.RevenueRecognitionRuleId and rr_cnf_Product.Enabled = 1		
									INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
									INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
									INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 

								where COA_CNF_AccountConfig.RemainingValues &lt;&gt; 1
								  and RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId in (select RRID 
								                                                                   from #RulesToRun)

									)p   ON ((RR_DATA_REVENUE.MATRIXCELLID = p.MATRIXCELLID) or (RR_DATA_REVENUE.MatrixSheetId = p.MatrixSheetId)
										or (p.Attributeid in (select Value
																								from dbo.split((select Attributeids
																												from RR_DATA_REVENUE rr
																												where rr.RevenueRecognitionDataId = rr_data_revenue.RevenueRecognitionDataId), '.')
																								)
																					    
													))

                                   LEFT JOIN (select ticketid, AttributeIDs coaaccountid, AccountingType, sum(revenueamount) as TotalUsed
												from rr_data_revenue
												where ticketid is not null
												group by ticketid, AccountingType, coaaccountid, AttributeIDs
												)rdata									ON rdata.ticketid = ISNULL(RR_DATA_REVENUE.ticketid, DATA_SaleItem2Ticket.ticketid)	and rdata.AccountingType = p.AccountingType 
												                                           and rdata.coaaccountid = p.coaaccountid
					where data_ticket.FEncodeDate &lt;= @BatchDate
					)p
					where Round(RevenueAmount, 12) &lt;&gt; 0 


					INSERT INTO [dbo].[RR_DATA_Revenue]
						   ([COAAccountId]
						   ,[RevenueRecognitionRuleId]
						   ,[RRCode]
						   ,[RRCalcTypeWhere]
						   ,[RRCalcTypeMethod]
						   ,[COAAccountConfigId]
						   ,[COAAccountType]
						   ,[COAAccountCode]
						   ,[SaleId]
						   ,[Ticketid]
						   ,[MatrixCellid]
						   ,[MatrixCellCode]
						   ,[MatrixSheetid]
						   ,[SiteId]
						   ,[OperatingAreaId]
						   ,[WorkstationId]
						   ,[Usergroupid]
						   ,[UserId]
						   ,[FCalcDate]
						   ,[FRevenueDate]
						   ,[Quantity]
						   ,[GrossAmount]
						   ,[NetAmount]
						   ,[Price]
						   ,[Percentage]
						   ,[RemaningValues]
						   ,[RevenueAmount]
						   ,[AccountingType]
						   ,[RRCalcTypeTrigger]
						   ,[RRPercentage]			
						   ,[RRDays]
						   ,[AttributeIDs]
						   )
						   select *
						   from (
							select distinct p.COAAccountId, 
								   p.RevenueRecognitionRuleId,
								   p.RRcode,		   
								   p.RRCalcTypeWhere,
								   p.RRCalcTypeMethod,	   
								   p.COAAccountConfigId,
								   p.COAAccountTypeId,
								   p.AccountCode as AccountCode,
								   RR_DATA_REVENUE.saleid as Saleid,
								   ISNULL(rdata.Ticketid, DATA_SaleItem2Ticket.Ticketid) as ticketID, 
								   RR_DATA_REVENUE.Matrixcellid,
								   RR_DATA_REVENUE.MatrixcellCode,
								   RR_DATA_REVENUE.MatrixSheetId,
								   RR_DATA_REVENUE.Siteid,
								   RR_DATA_REVENUE.OperatingAreaId,
								   RR_DATA_REVENUE.Workstationid,
								   RR_DATA_REVENUE.UserGroupid,
								   RR_DATA_REVENUE.UserId as userID,
								   @BatchDate as BatchDate,
								   @BatchDate as TransDate,
								   RR_DATA_REVENUE.Quantity as Quantity,
								   RR_DATA_REVENUE.GrossAmount as GrossAmount,
								   RR_DATA_REVENUE.NetAmount as NetAmount,
								   p.Price as ConfigPrice,
								   p.Percentage as ConfigPercentage,
								   p.RemainingValues,																		
								  round(case when ((((DATA_Ticket.Price - DATA_Ticket.taxes) - ISNULL(TotalUsed, 0)) &gt; 0) and ((
																					(((DATA_Ticket.Price - DATA_Ticket.taxes) *  p.rrPercentage)/100) -  
																						((
																						(((DATA_Ticket.Price - DATA_Ticket.taxes) *  p.rrPercentage)/100) * (select sum(percentage)
																																							from coa_cnf_accountconfig AC
																																							where AC.revenuerecognitionruleid = p.RevenueRecognitionRuleId
																																							and ac.accountingtype = p.accountingtype
																																							)
																						)/100)) &lt;= ((DATA_Ticket.Price - DATA_Ticket.taxes) - ISNULL(TotalUsed, 0))))

														then 
														((((DATA_Ticket.Price - DATA_Ticket.taxes) *  p.rrPercentage)/100) -  ((((DATA_Ticket.Price - DATA_Ticket.taxes) *  p.RRPercentage)/100) * (select sum(percentage)
																																from coa_cnf_accountconfig AC
																																where AC.revenuerecognitionruleid = p.RevenueRecognitionRuleId
																																and ac.accountingtype = p.accountingtype
																																))/100)
													else (DATA_Ticket.Price - DATA_Ticket.taxes) - TotalUsed
												end, 2) as RevenueAmount,
								   p.Accountingtype,
								   p.RRCalcTypeTrigger,
								   p.RRPercentage,
								   p.Days,
								   RR_DATA_REVENUE.AttributeIDs

							from RR_DATA_REVENUE
								INNER JOIN DATA_SaleItem							ON data_saleitem.SaleItemId		   = rr_data_revenue.saleitemid
								INNER JOIN DATA_SaleItem2Ticket						on data_saleitem2ticket.Saleitemid = data_saleitem.saleitemid
								INNER JOIN DATA_Ticket								on data_ticket.ticketid = data_saleitem2ticket.ticketid
								INNER JOIN (  
										select  RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleid, 
										RR_CNF_RevenueRecognitionRule.Code as RRCode,
										RR_CNF_RevenueRecognitionRule.Days,
										RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
										RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,
										FromDate,
										ToDate,
										RR_CNF_RevenueRecognitionRule.rrCalcTypeTrigger,
										RR_CNF_RevenueRecognitionRule.Percentage as RRPercentage,
										COA_CNF_AccountConfig.CoaAccountid,
										COA_CNF_AccountConfig.AccountingType,
										COA_CNF_AccountConfig.Price,
										COA_CNF_AccountConfig.Percentage,
										COA_CNF_AccountConfig.RemainingValues,
										COA_CNF_AccountConfig.SiteID,
										coa_cnf_account.code as AccountCode,
										COA_CNF_AccountType.Code as AccountTypeCode,
										COA_CNF_AccountType.COAAccountTypeId,
										rr_cnf_Product.MatrixcellID,
										rr_cnf_Product.matrixsheetID,
										COA_CNF_AccountConfig.COAAccountConfigId,
										rr_cnf_Product.AttributeID

								from RR_CNF_RevenueRecognitionRule
									inner join rr_cnf_Product						ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_cnf_product.RevenueRecognitionRuleId and rr_cnf_Product.Enabled = 1		
									INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
									INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
									INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 

								where COA_CNF_AccountConfig.RemainingValues = 1
								  and RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId in (select RRID 
								                                                                   from #RulesToRun)

								)p   ON ((RR_DATA_REVENUE.MATRIXCELLID = p.MATRIXCELLID) or (RR_DATA_REVENUE.MatrixSheetId = p.MatrixSheetId)
										or (p.Attributeid in (select Value
																								from dbo.split((select Attributeids
																												from RR_DATA_REVENUE rr
																												where rr.RevenueRecognitionDataId = rr_data_revenue.RevenueRecognitionDataId), '.')
																								)
																					    
													))
                                   LEFT JOIN (select ticketid, AttributeIDs, coaaccountid, AccountingType, sum(revenueamount) as TotalUsed
												from rr_data_revenue
												where ticketid is not null
												group by ticketid, AccountingType, coaaccountid, AttributeIDs
												)rdata									ON rdata.ticketid = ISNULL(RR_DATA_REVENUE.ticketid, DATA_SaleItem2Ticket.ticketid)	and rdata.AccountingType = p.AccountingType 
												                                           and rdata.coaaccountid = p.coaaccountid
								where data_ticket.FEncodeDate &lt;= @BatchDate
								)r
								where Round(RevenueAmount, 12) &lt;&gt; 0 

END
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_RR_RevenueData_PaymentMethodTaxDiscounts]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_RR_RevenueData_PaymentMethodTaxDiscounts
</SCRIPT></SQLSCRIPTLIST><SQLSCRIPTLIST><SCRIPT>CREATE Procedure dbo.otn_sp_RR_RevenueData_PaymentMethodTaxDiscounts
	@BatchDate Date,
	@Transactions varchar(500),
	@Trigger int,
	@RRTransDateType integer
AS 
BEGIN
	 
	Create Table #TransactionIDs(
	TransactionId Int NOT NULL)

	DECLARE @DelimPosition INT

    SET @DelimPosition = CHARINDEX(',', @Transactions)

    WHILE @DelimPosition &gt; 0
    BEGIN
        INSERT INTO #TransactionIDs(TransactionId)
            VALUES(CAST(RTRIM(LEFT(@Transactions, @DelimPosition - 1)) AS INT))
        SET @Transactions = right(@Transactions, len(@Transactions) - @DelimPosition)

        SET @DelimPosition = CHARINDEX(',', @Transactions)
    END

	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer

	Declare @OnCreditWriteoff Integer = 9
	Declare @StartTime DateTime

	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1
	

		--	--	--Normal Sale Split out the Payments to Smaller Subset.
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])				    
						select distinct COA.COAAccountId, 
						   p.RevenueRecognitionRuleId,
						   p.RRCode,		   
						   p.RRCalcTypeWhere,
						   p.RRCalcTypeMethod,	   
						   p.COAAccountConfigId,
						   COA.COAAccountTypeId,
						   COA.Code,
						   RR_DATA_REVENUE.Transactionid as Transactionid,
						   RR_DATA_REVENUE.saleid as Saleid,
						   RR_DATA_REVENUE.Siteid as SiteID,
						   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
						   RR_DATA_REVENUE.Workstationid as Workstationid,
						   RR_DATA_REVENUE.UserGroupid as UserGroupID,
						   RR_DATA_REVENUE.UserId as userID,
						   @BatchDate,
						   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
							    else DATA_Transaction.transactiondate
						   end as TransDate,
						   0,
						   0,
						   0,
						   0,
						   100,
						   0, 	
						   ABS ((data_payment.PaymentAmount) -
						   (case when data_payment.paymentid = (select top 1 paymentid
																from data_payment
																where transactionid = RR_DATA_REVENUE.Transactionid
																	and data_payment.paymentamount &gt; (select sum(Change) *-1
																								from data_transaction
																								where data_transaction.transactionid = RR_DATA_REVENUE.Transactionid))
								then (select sum(Change) *-1
																								from data_transaction
																								where data_transaction.transactionid = RR_DATA_REVENUE.Transactionid)
								else 0
							end ))
							as RevenueAmount,
							p.Accountingtype,		
						    p.RRCalcTypeTrigger,
						    p.RRPercentage,
						    p.RRDays

						from RR_DATA_REVENUE
						INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
						INNER JOIN data_payment							on data_payment.transactionid = rr_data_revenue.transactionid
						left  JOIN DATA_PaymentCard						on data_paymentcard.paymentid = data_payment.PaymentId
						left JOIN CNF_PaymentCard						on cnf_paymentcard.paymentcardid = data_paymentcard.paymentcardid
						INNER JOIN CNF_PaymentMethod					on CNF_PaymentMethod.PaymentMethodId = data_payment.PaymentMethodId
						INNER JOIN COA_CNF_Account COA					on COA.COAAccountid = ISNULL(cnf_paymentcard.coaaccountid, CNF_PaymentMethod.COAAccountid)

						INNER JOIN (select transactionid, RevenueRecognitionRuleId, RR_DATA_Revenue.RRCode, RRCalcTypeWhere, 
											RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount,  Accountingtype
											from RR_DATA_Revenue
											INNER JOIN COA_CNF_Account		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
											where COA_CNF_Account.coaAccountID = @ACCPaymentMethod
											--and RR_DATA_Revenue.RRCalcTypeTrigger = @Trigger
											and RR_DATA_REVENUE.fcalcdate = @BatchDate
										)p    on p.transactionid = 	data_payment.transactionid

					where data_payment.paymentstatus = 1
					and DATA_Transaction.TransactionType in (select transactionid
																from #TransactionIDs)
					and RR_DATA_REVENUE.fcalcdate = @BatchDate
					--and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
					AND data_payment.Transactionid not in (select distinct transactionid
												from rr_Data_Revenue
												where matrixcellid is null
												  and coaaccountid in (select distinct coaaccountid
																			from cnf_paymentmethod CP
																			where coaaccountid is not null
																			union all
																			select distinct coaaccountid
																			from cnf_paymentcard pc
																			where coaaccountid is not null
																		)
																			and transactionid is not null
												)
					AND data_payment.Transactionid in (select distinct transactionid
												from rr_Data_Revenue
												where coaaccountid in (@ACCPaymentMethod)
												)
					 AND RR_DATA_REVENUE.coaaccountid not in (@ACCPaymentMethod)


		----Normal Sale Split out the Payments to Payment Fees
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])				    
				select distinct COA.COAAccountId, 
						   p.RevenueRecognitionRuleId,
						   p.RRCode,		   
						   p.RRCalcTypeWhere,
						   p.RRCalcTypeMethod,	   
						   p.COAAccountConfigId,
						   COA.COAAccountTypeId,
						   COA.Code,
						   RR_DATA_REVENUE.Transactionid as Transactionid,
						   RR_DATA_REVENUE.saleid as Saleid,
						   RR_DATA_REVENUE.Siteid as SiteID,
						   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
						   RR_DATA_REVENUE.Workstationid as Workstationid,
						   RR_DATA_REVENUE.UserGroupid as UserGroupID,
						   RR_DATA_REVENUE.UserId as userID,
						   @BatchDate,
						   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
							    else DATA_Transaction.transactiondate
						   end as TransDate,
						   0,
						   0,
						   0,
						   0,
						   100,
						   0,  	
						   data_payment.paymentfee as RevenueAmount,
						   case when data_payment.paymentfee &gt;= 0 then 2
						        else 1
							end accountingtype,		
						   p.RRCalcTypeTrigger,
						   p.RRPercentage,
						   p.RRDays

						from RR_DATA_REVENUE
						INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
						INNER JOIN data_payment							on data_payment.transactionid = rr_data_revenue.transactionid
						left  JOIN DATA_PaymentCard						on data_paymentcard.paymentid = data_payment.PaymentId
						left JOIN CNF_PaymentCard						on cnf_paymentcard.paymentcardid = data_paymentcard.paymentcardid
						INNER JOIN CNF_PaymentMethod					on CNF_PaymentMethod.PaymentMethodId = data_payment.PaymentMethodId
						INNER JOIN COA_CNF_Account COA					on COA.COAAccountid = CNF_PaymentMethod.FeeCOAAccountId

						INNER JOIN (select transactionid, RevenueRecognitionRuleId, RR_DATA_Revenue.RRCode, RRCalcTypeWhere, 
											RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount,  Accountingtype
											from RR_DATA_Revenue
											INNER JOIN COA_CNF_Account		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
											where COA_CNF_Account.coaAccountID = @ACCPaymentMethod
										)p    on p.transactionid = 	data_payment.transactionid

					where data_payment.paymentstatus = 1
					and DATA_Transaction.TransactionType in (select transactionid
																from #TransactionIDs)
					and data_payment.paymentfee &lt;&gt; 0
					and RR_DATA_REVENUE.fcalcdate = @BatchDate
					--and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
					AND data_payment.Transactionid not in (select distinct transactionid
												from rr_Data_Revenue
												where coaaccountid in (select distinct FeeCOAAccountId
																			from cnf_paymentmethod CP
																		)
																			and transactionid is not null
												)
					AND data_payment.Transactionid in (select distinct transactionid
												from rr_Data_Revenue
												where coaaccountid in (@ACCPaymentMethod)
												)


		--	--Normal Transactions Reverse out of PaymentMethods
			INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])				    					
					select COAAccountId, 
						   Max(RevenueRecognitionRuleId),
						   Max(RRCode),		   
						   RRCalcTypeWhere,
						   RRCalcTypeMethod,	   
						   Max(COAAccountConfigId),
						   COAAccountTypeId,
						   COAAccountCode,
						   Transactionid,
						   saleid,
						   Siteid,
						   OperatingAreaId,
						   Workstationid,
						   UserGroupid,
						   UserId,
						   batchdate,
						   TransDate,
						   0,
						   0,
						   0,						
						   0,
						   0,
						   0,
						   ABS(sum(RevenueAmount)) as RevenueAmount,
						   case when accountingtype = 1 then 2
								else 1
							end Accountingtype,		
						   RRCalcTypeTrigger,
						   RRPercentage,
						   RRDays
						   from (
			select distinct rr_data_Revenue.coaaccountid as rrcoaaccountid,
								       p.COAAccountId, 
									   p.RevenueRecognitionRuleId,
									   p.RRCode,		   
									   p.RRCalcTypeWhere,
									   p.RRCalcTypeMethod,	   
									   p.COAAccountConfigId,
									   p.COAAccountTypeId,
									   p.COAAccountCode,
									   rr_data_Revenue.Transactionid Transactionid,
									   rr_data_Revenue.saleid saleid,
									   rr_data_Revenue.Siteid siteid,
									   rr_data_Revenue.OperatingAreaId OperatingAreaid,
									   rr_data_Revenue.Workstationid workstationid,
									   rr_data_Revenue.UserGroupid usergroupid,
									   rr_data_Revenue.UserId userid,
									   @BatchDate batchdate,
									   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
											else DATA_Transaction.transactiondate
									   end as TransDate,
									   rr_data_Revenue.RevenueAmount  as RevenueAmount,
								       p.Accountingtype,
									   transactiontype,		
									   p.RRCalcTypeTrigger,
									   p.RRPercentage,
									   p.RRDays
							FROM rr_data_Revenue   				        WITH (NOLOCK)
								   INNER JOIN (select saleid, transactionid, RevenueRecognitionRuleId, RR_DATA_Revenue.RRCode, RRCalcTypeWhere, Saleitemid, RR_DATA_Revenue.COAAccountId, 
													   RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount, COA_CNF_Account.COAAccountTypeId,  Accountingtype,
													   RR_DATA_Revenue.COAAccountCode
													  from RR_DATA_Revenue
														INNER JOIN COA_CNF_Account		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
													 where COA_CNF_Account.coaAccountID = @ACCPaymentMethod
													-- and rr_data_Revenue.RRCalcTypeTrigger = @Trigger
													)p								ON p.transactionid = 	rr_data_Revenue.transactionid
									INNER JOIN DATA_Transaction			on data_transaction.transactionid = rr_data_revenue.transactionid
							where RR_DATA_REVENUE.fcalcdate = @BatchDate
							  
							  and DATA_Transaction.TransactionType in (select transactionid
																from #TransactionIDs)
							  and rr_data_Revenue.coaaccountid in (select distinct coaaccountid
																	 from cnf_paymentmethod
																	 where coaaccountid is not null
																	union all
																   select distinct coaaccountid
																	 from cnf_paymentcard
																	 where coaaccountid is not null

																  )
						)r	
							group by	 COAAccountId, 		   
									   RRCalcTypeWhere,
									   RRCalcTypeMethod,	   
									   COAAccountTypeId,
									   COAAccountCode,
									   Transactionid,
									   saleid,
									   Siteid,
									   OperatingAreaId,
									   Workstationid,
									   UserGroupid,
									   UserId,
									   batchdate,
									   TransDate,					
									   Accountingtype,		
									   RRCalcTypeTrigger,
									   RRPercentage,
									   RRDays, 
									   TransactionType
							

----Normal Sale Split out the Payments to returned Checks
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])				    
				select distinct COA.COAAccountId, 
						   p.RevenueRecognitionRuleId,
						   p.RRCode,		   
						   p.RRCalcTypeWhere,
						   p.RRCalcTypeMethod,	   
						   p.COAAccountConfigId,
						   COA.COAAccountTypeId,
						   COA.Code,
						   RR_DATA_REVENUE.Transactionid as Transactionid,
						   RR_DATA_REVENUE.saleid as Saleid,
						   RR_DATA_REVENUE.Siteid as SiteID,
						   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
						   RR_DATA_REVENUE.Workstationid as Workstationid,
						   RR_DATA_REVENUE.UserGroupid as UserGroupID,
						   RR_DATA_REVENUE.UserId as userID,
						   @BatchDate,
						   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
							    else DATA_Transaction.transactiondate
						   end as TransDate,
						   0,
						   0,
						   0,
						   0,
						   100,
						   0,  	
						  ABS(data_ledger.entryAmount) as RevenueAmount,
							case when data_ledger.entryAmount &gt;= 0 then 1
								else 2
							end accountingtype,		
							p.RRCalcTypeTrigger,
							p.RRPercentage,
							p.RRDays

						from RR_DATA_REVENUE
						INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
						INNER JOIN data_payment							on data_payment.transactionid = rr_data_revenue.transactionid
						left  JOIN DATA_PaymentCard						on data_paymentcard.paymentid = data_payment.PaymentId
						left JOIN CNF_PaymentCard						on cnf_paymentcard.paymentcardid = data_paymentcard.paymentcardid
						INNER JOIN CNF_PaymentMethod					on CNF_PaymentMethod.PaymentMethodId = data_payment.PaymentMethodId
						INNER JOIN COA_CNF_Account COA					on COA.COAAccountid = CNF_PaymentMethod.returnedcheckcoaaccountid
						INNER JOIN data_ledger							ON data_ledger.transactionid = data_transaction.transactionid
						INNER JOIN cnf_ledgeraccount					ON cnf_ledgeraccount.LedgerAccountId = data_ledger.ledgeraccountid
												INNER JOIN (select transactionid, RevenueRecognitionRuleId, RR_DATA_Revenue.RRCode, RRCalcTypeWhere, 
																	RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount,  Accountingtype
																	from RR_DATA_Revenue
																	INNER JOIN COA_CNF_Account		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
																	where COA_CNF_Account.coaAccountID = @ACCPaymentMethod
																)p    on p.transactionid = 	data_payment.transactionid


						where data_payment.paymentstatus = 1
							and DATA_Transaction.TransactionType in (select transactionid
																from #TransactionIDs)
							and DATA_Transaction.tip &lt;&gt; 0
							and RR_DATA_REVENUE.fcalcdate = @BatchDate
							and systemaccounttable = 119
							and systemaccountid = 15

----Breakage for Fixed Vouchers.   The left over money.
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])				    
					select distinct COA.COAAccountId, 
						   p.RevenueRecognitionRuleId,
						   p.RRCode,		   
						   p.RRCalcTypeWhere,
						   p.RRCalcTypeMethod,	   
						   p.COAAccountConfigId,
						   COA.COAAccountTypeId,
						   COA.Code,
						   RR_DATA_REVENUE.Transactionid as Transactionid,
						   RR_DATA_REVENUE.saleid as Saleid,
						   RR_DATA_REVENUE.Siteid as SiteID,
						   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
						   RR_DATA_REVENUE.Workstationid as Workstationid,
						   RR_DATA_REVENUE.UserGroupid as UserGroupID,
						   RR_DATA_REVENUE.UserId as userID,
						   @BatchDate,
						   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
							    else DATA_Transaction.transactiondate
						   end as TransDate,
						   0,
						   0,
						   0,
						   0,
						   100,
						   0,  	
						  ABS(DATA_Transaction.Tip) as RevenueAmount,
							2 accountingtype,		
							p.RRCalcTypeTrigger,
							p.RRPercentage,
							p.RRDays

						from RR_DATA_REVENUE

							INNER JOIN data_transaction		on data_transaction.transactionid = rr_data_revenue.transactionid
							INNER JOIN DATA_Payment			on data_payment.transactionid = data_transaction.transactionid
							INNER JOIN CNF_PaymentMethod	on cnf_paymentmethod.paymentmethodid = data_payment.paymentmethodid
							INNER JOIN CNF_Driver			on cnf_driver.driverID = cnf_paymentmethod.driverid
							INNER JOIN COA_CNF_Account COA	on COA.COAAccountid = CNF_PaymentMethod.FixedVoucherCOAAccountId


							INNER JOIN (select transactionid, RevenueRecognitionRuleId, RR_DATA_Revenue.RRCode, RRCalcTypeWhere, 
																	RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount,  Accountingtype
																	from RR_DATA_Revenue
																	INNER JOIN COA_CNF_Account		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
																	where COA_CNF_Account.coaAccountID = @ACCPaymentMethod
																)p    on p.transactionid = 	data_payment.transactionid


						where data_payment.paymentstatus = 1
						  and TransactionType in (select transactionid
														from #TransactionIDs)
							and DATA_Transaction.tip &lt;&gt; 0
							and RR_DATA_REVENUE.fcalcdate = @BatchDate


				--Normal Transaction break out Tax
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])				    
						  select COAAccountId, 
						   MIN(p.RevenueRecognitionRuleId),
						   MIN(p.RRCode),		   
						   RRCalcTypeWhere,
						   RRCalcTypeMethod,	   
						   COAAccountConfigId,
						   COAAccountTypeId,
						   COACODE,
						   Transactionid,
						   saleid,
						   Siteid,
						   OperatingAreaId,
						   Workstationid,
						   UserGroupid,
						   UserId,
						   batchdate,
						   TransDate,
						   0,
						   0,
						   0,						
						   price,
						   percentage,
						   test,
						   ABS(sum(RevenueAmount)) as RevenueAmount,
				           case when TransactionType in (5, 17, 18, 20, 22, 30) and sum(RevenueAmount) &lt;= 0  then 1
						        when TransactionType in (5, 17, 18, 20, 22, 30) and sum(RevenueAmount) &lt;= 0  then 2
								when TransactionType in (7) and sum(RevenueAmount) &lt;= 0  then 1
								when TransactionType in (7) and sum(RevenueAmount) &gt; 0  then 2
								else Accountingtype
							end Accountingtype,		
						   RRCalcTypeTrigger,
						   RRPercentage,
						   RRDays
						   
						   from (
						  select distinct COA.COAAccountId, 
						   min(p.RevenueRecognitionRuleId) RevenueRecognitionRuleId,
						   min(p.rrcode) rrcode,		   
						   RR_DATA_REVENUE.RRCalcTypeWhere,
						   RR_DATA_REVENUE.RRCalcTypeMethod,	   
						   RR_DATA_REVENUE.COAAccountConfigId,
						   COA.COAAccountTypeId,
						   COA.Code COACODE,
						   RR_DATA_REVENUE.Transactionid as Transactionid,
						   RR_DATA_REVENUE.saleid as Saleid,
						   RR_DATA_REVENUE.Siteid as SiteID,
						   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
						   RR_DATA_REVENUE.Workstationid as Workstationid,
						   RR_DATA_REVENUE.UserGroupid as UserGroupID,
						   RR_DATA_REVENUE.UserId as userID,
						   @BatchDate as batchdate,
						   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
							    else DATA_Transaction.transactiondate
						   end as TransDate,
						   0 as Quantity,
						   0 as GrossAmount,
						   0 as NetAmount,
						   0 as price,
						   100 as percentage,
						   0 as test, 	
						   taxamount RevenueAmount,
						   Transactiontype,
							p.Accountingtype,					   		
						   RR_DATA_REVENUE.RRCalcTypeTrigger,
						   RR_DATA_REVENUE.RRPercentage,
						   RR_DATA_REVENUE.RRDays

					from RR_DATA_REVENUE
						INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
						INNER JOIN DATA_TransactionTax					on data_transactiontax.transactionid = data_transaction.transactionid
						INNER JOIN CNF_Tax								on cnf_tax.taxid = DATA_TransactionTax.taxid
						INNER JOIN coa_cnf_account coa					on coa.coaaccountid = cnf_tax.coaaccountid
							INNER JOIN (select saleid, transactionid, RevenueRecognitionRuleId, RR_DATA_Revenue.RRCode, RRCalcTypeWhere, Saleitemid, RR_DATA_Revenue.coaaccountid,
												RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount,  Accountingtype
												from RR_DATA_Revenue
												INNER JOIN COA_CNF_Account		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
												where COA_CNF_Account.coaAccountID = @TaxAccountID
												--and rr_data_Revenue.RRCalcTypeTrigger = @Trigger
												and RR_DATA_REVENUE.fcalcdate = @BatchDate
											)p    on p.transactionid = 	data_transactiontax.transactionid
					where RR_DATA_REVENUE.coaaccountid = 1
					and RR_DATA_REVENUE.fcalcdate = @BatchDate
					and TransactionType in (select transactionid
														from #TransactionIDs)
					AND DATA_Transaction.Transactionid not in (select distinct transactionid
																	from rr_Data_Revenue
																	where coaaccountid in (select distinct coaaccountid
																								from cnf_tax 
																							)
																	)
					group by COA.COAAccountId,    
						   RR_DATA_REVENUE.RRCalcTypeWhere,
						   RR_DATA_REVENUE.RRCalcTypeMethod,	   
						   RR_DATA_REVENUE.COAAccountConfigId,
						   COA.COAAccountTypeId,
						   COA.Code,
						   RR_DATA_REVENUE.Transactionid,
						   RR_DATA_REVENUE.saleid,
						   RR_DATA_REVENUE.Siteid,
						   RR_DATA_REVENUE.OperatingAreaId,
						   RR_DATA_REVENUE.Workstationid,
						   RR_DATA_REVENUE.UserGroupid,
						   RR_DATA_REVENUE.UserId,
						   DATA_Transaction.ftransactiondate, 
						   DATA_Transaction.transactiondate,
						   taxamount,
						   Transactiontype,
							p.Accountingtype,					   		
						   RR_DATA_REVENUE.RRCalcTypeTrigger,
						   RR_DATA_REVENUE.RRPercentage,
						   RR_DATA_REVENUE.RRDays

					)p
					where revenueamount &lt;&gt; 0
					group by COAAccountId, 	   
							RRCalcTypeWhere,
							RRCalcTypeMethod,	   
							COAAccountConfigId,
							COAAccountTypeId,
							COACODE,
							Transactionid,
							saleid,
							Siteid,
							OperatingAreaId,
							Workstationid,
							UserGroupid,
							UserId,
							TransDate,
							Accountingtype,		
							RRCalcTypeTrigger,
							RRPercentage,
							RRDays,
							price,
							percentage,
							test,
							batchdate,
							TransactionType


																									
		--	--------Reverse Tax Out
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])	
				      select  COAAccountId, 
									   RevenueRecognitionRuleId,
									   RRCode,		   
									   RRCalcTypeWhere,
									   RRCalcTypeMethod,	   
									   COAAccountConfigId,
									   COAAccountTypeId,
									   COAAccountCode,
									   Transactionid,
									   saleid,
									   siteid,
									   OperatingAreaid,
									   workstationid,
									   usergroupid,
									   userid,
									   batchdate,
									   TransDate,
									   Quantity,
									   grossamount,
									   netamount,
									   price,
									   percentage,
									   tax,
									   ABS(sum(RevenueAmount))  as RevenueAmount,
									    case when p.accountingtype = 1 then 2
											else 1
										end Accountingtype,	
									   RRCalcTypeTrigger,
									   RRPercentage,
									   RRDays
					  from (		    
				             select distinct 
								       p.COAAccountId, 
									   p.RevenueRecognitionRuleId,
									   p.RRCode,		   
									   p.RRCalcTypeWhere,
									   p.RRCalcTypeMethod,	   
									   p.COAAccountConfigId,
									   p.COAAccountTypeId,
									   p.COAAccountCode,
									   rr_data_Revenue.Transactionid Transactionid,
									   rr_data_Revenue.saleid saleid,
									   rr_data_Revenue.Siteid siteid,
									   rr_data_Revenue.OperatingAreaId OperatingAreaid,
									   rr_data_Revenue.Workstationid workstationid,
									   rr_data_Revenue.UserGroupid usergroupid,
									   rr_data_Revenue.UserId userid,
									   @BatchDate batchdate,
									   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
											else DATA_Transaction.transactiondate
									   end as TransDate,
									   rr_data_Revenue.Quantity Quantity,
									   rr_data_Revenue.GrossAmount grossamount,
									   rr_data_Revenue.NetAmount netamount,
									   0 price,
									   100 percentage,
									   0 tax,
									   rr_data_Revenue.RevenueAmount  as RevenueAmount,
									   data_transaction.transactiontype,
								       p.Accountingtype,		
									   p.RRCalcTypeTrigger,
									   p.RRPercentage,
									   p.RRDays
							FROM rr_data_Revenue   				        WITH (NOLOCK)
								   INNER JOIN (select saleid, transactionid, RevenueRecognitionRuleId, RR_DATA_Revenue.RRCode, RRCalcTypeWhere, Saleitemid, RR_DATA_Revenue.COAAccountId, 
													   RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount, COA_CNF_Account.COAAccountTypeId,  Accountingtype,
													   RR_DATA_Revenue.COAAccountCode
													  from RR_DATA_Revenue
														INNER JOIN COA_CNF_Account		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
													 where COA_CNF_Account.coaAccountID = @TaxAccountID
													)p								ON p.Transactionid = 	rr_data_Revenue.Transactionid
									INNER JOIN data_transaction						on data_transaction.transactionid = rr_data_revenue.transactionid

							where RR_DATA_REVENUE.fcalcdate = @BatchDate
							  and rr_data_Revenue.RRCalcTypeTrigger = @Trigger
							  and DATA_Transaction.TransactionType in (select transactionid
																		from #TransactionIDs)
							  and rr_data_Revenue.coaaccountid in (select distinct coaaccountid
						                                             from cnf_tax
																    where coaaccountid is not null
															      )
							)p
							group by   COAAccountId, 
									   RevenueRecognitionRuleId,
									   RRCode,		   
									   RRCalcTypeWhere,
									   RRCalcTypeMethod,	   
									   COAAccountConfigId,
									   COAAccountTypeId,
									   COAAccountCode,
									   Transactionid,
									   saleid,
									   siteid,
									   OperatingAreaid,
									   workstationid,
									   usergroupid,
									   userid,
									   batchdate,
									   TransDate,
									   Quantity,
									   grossamount,
									   netamount,
									   price,
									   percentage,
									   tax,
								       Accountingtype,		
									   RRCalcTypeTrigger,
									   RRPercentage,
									   RRDays,
									   TransactionType


		------		--Normal Transaction Break out the discounts
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])
				   select COAAccountId, 
						   RevenueRecognitionRuleId,
						   RRCode,		   
						   RRCalcTypeWhere,
						   RRCalcTypeMethod,	   
						   COAAccountConfigId,
						   COAAccountTypeId,
						   Code,
						   Transactionid,
						   Saleid,
						   SiteID,
						   OperatingAreaID,
						   Workstationid,
						   UserGroupID,
						   userID,
						   batchdate,
						   TransDate,
						   quantity,
						   grossamount,
						   netamount,
						   price,
						   percentage,
						   remaningValues, 	
						   RevenueAmount,
						   Accountingtype,		
						   RRCalcTypeTrigger,
						   RRPercentage,
						   RRDays
				   from (				    
						select distinct 
						   COA.COAAccountId, 
						   RR_DATA_REVENUE.RevenueRecognitionRuleId,
						   RR_DATA_REVENUE.RRCode,		   
						   RR_DATA_REVENUE.RRCalcTypeWhere,
						   RR_DATA_REVENUE.RRCalcTypeMethod,	   
						   RR_DATA_REVENUE.COAAccountConfigId,
						   COA.COAAccountTypeId,
						   COA.Code,
						   RR_DATA_REVENUE.Transactionid as Transactionid,
						   RR_DATA_REVENUE.saleid as Saleid,
						   RR_DATA_REVENUE.Siteid as SiteID,
						   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
						   RR_DATA_REVENUE.Workstationid as Workstationid,
						   RR_DATA_REVENUE.UserGroupid as UserGroupID,
						   RR_DATA_REVENUE.UserId as userID,
						   @BatchDate as batchdate,
						   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
							    else DATA_Transaction.transactiondate
						   end as TransDate,
						   0 as quantity,
						   0 as grossamount,
						   0 as netamount,
						   0 as price,
						   100 as percentage,
						   0 as remaningValues, 	
						   abs(DATA_SaleItemRule.discountamount)
							as RevenueAmount,
						   p.Accountingtype,		
						   RR_DATA_REVENUE.RRCalcTypeTrigger,
						   RR_DATA_REVENUE.RRPercentage,
						   RR_DATA_REVENUE.RRDays,
						   DATA_SaleItemRule.SaleItemRuleId


					from RR_DATA_REVENUE
						--inner join rr_cnf_Product						ON ((RR_DATA_REVENUE.MATRIXCELLID = rr_cnf_Product.MATRIXCELLID) or (RR_DATA_REVENUE.MatrixSheetId = rr_cnf_Product.MatrixSheetId)) and rr_cnf_Product.Enabled = 1
						--inner join RR_CNF_RevenueRecognitionRule		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_cnf_Product.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  
						--INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
						--INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
						--INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 
						INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
						LEFT  JOIN DATA_Sale				            ON DATA_Sale.SaleID = data_transaction.SaleID
						LEFT  JOIN DATA_SaleItem			            ON DATA_SaleItem.saleitemid = RR_DATA_REVENUE.saleitemid
						LEFT JOIN DATA_SaleItemRule						ON data_saleitemrule.saleitemid = DATA_SaleItem.saleitemid	 
						LEFT JOIN CNF_PromotionItemRule					ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
						LEFT JOIN CNF_PromotionItem						ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
						LEFT JOIN CNF_Promotion							ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId	
						LEFT JOIN COA_CNF_Account	COA			        ON COA.coaaccountid = CNF_Promotion.coaaccountid
						
						
						INNER JOIN (select transactionid, RevenueRecognitionRuleId, RR_DATA_Revenue.RRCode, RRCalcTypeWhere, 
											RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount,  Accountingtype
											from RR_DATA_Revenue
											INNER JOIN COA_CNF_Account		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
											where COA_CNF_Account.coaAccountID = @DiscountAccountID
										)p    on p.transactionid = 	DATA_Transaction.transactionid



					where RR_DATA_REVENUE.coaaccountid = 1
					and DATA_Transaction.TransactionType in (select transactionid
																from #TransactionIDs)
					and RR_DATA_REVENUE.fcalcdate = @BatchDate
					--and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
					AND DATA_Transaction.Transactionid not in (select distinct transactionid
																	from rr_Data_Revenue
																	where coaaccountid in (select distinct coaaccountid
																								from CNF_Promotion
																								where coaaccountid is not null 
																							)
																	)	
					)p
					where revenueamount &lt;&gt; 0	
					  and coaaccountid is not null													
																																								
		--		--Reverse out Discounts														
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])	
				   select COAAccountId, 
						   RevenueRecognitionRuleId,
						   RRCode,		   
						   RRCalcTypeWhere,
						   RRCalcTypeMethod,	   
						   COAAccountConfigId,
						   COAAccountTypeId,
						   COAAccountCode,
						   Transactionid,
						   Saleid,
						   SiteID,
						   OperatingAreaID,
						   Workstationid,
						   UserGroupID,
						   userID,
						   batchdate,
						   TransDate,
						   quantity,
						   grossamount,
						   netamount,
						   price,
						   percentage,
						   remaningValues, 	
						   sum(RevenueAmount),
						   Accountingtype,		
						   RRCalcTypeTrigger,
						   RRPercentage,
						   RRDays
				   from (		    
				select distinct 				           
				           p.RevenueRecognitionDataId,
                           p.COAAccountId, 
						   p.RevenueRecognitionRuleId,
						   p.RRCode,		   
						   p.RRCalcTypeWhere,
						   p.RRCalcTypeMethod,	   
						   p.COAAccountConfigId,
						   p.COAAccountTypeId,
						   p.COAAccountCode,
						   rr_data_Revenue.Transactionid,
						   rr_data_Revenue.saleid,
						   rr_data_Revenue.saleitemid,
						   rr_data_Revenue.Siteid,
						   rr_data_Revenue.OperatingAreaId,
						   rr_data_Revenue.Workstationid,
						   rr_data_Revenue.UserGroupid,
						   rr_data_Revenue.UserId,
						   @BatchDate batchdate,
						   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
							    else DATA_Transaction.transactiondate
						   end as TransDate,
							0 as quantity,
						   0 as grossamount,
						   0 as netamount,
						   0 as price,
						   100 as percentage,
						   0 as remaningValues,
						   rr_data_Revenue.RevenueAmount  as RevenueAmount,
						   case when p.accountingtype = 1 then 2
					        else 1
						   end Accountingtype,
						   p.RRCalcTypeTrigger,
						   p.RRPercentage,
						   p.RRDays

						  FROM rr_data_Revenue   				        WITH (NOLOCK)
								   INNER JOIN (select saleid, transactionid, RevenueRecognitionRuleId, RR_DATA_Revenue.RRCode, RRCalcTypeWhere, Saleitemid, RR_DATA_Revenue.COAAccountId, 
													   RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount, COA_CNF_Account.COAAccountTypeId,  Accountingtype,
													   RR_DATA_Revenue.COAAccountCode, rr_data_Revenue.RevenueRecognitionDataId
													  from RR_DATA_Revenue
														INNER JOIN COA_CNF_Account		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
													 where COA_CNF_Account.coaAccountID = @DiscountAccountID
													)p								ON p.saleid = 	rr_data_Revenue.saleid
								INNER JOIN data_transaction        on data_transaction.transactionid = rr_data_revenue.transactionid

						where  rr_data_Revenue.coaaccountid in (select distinct coaaccountid
						                                         from CNF_Promotion
															  )
						 and RR_DATA_REVENUE.fcalcdate = @BatchDate
						 and DATA_Transaction.TransactionType in (select transactionid
															from #TransactionIDs)
						)p		
						
						group by  COAAccountId, 
						   RevenueRecognitionRuleId,
						   RRCode,		   
						   RRCalcTypeWhere,
						   RRCalcTypeMethod,	   
						   COAAccountConfigId,
						   COAAccountTypeId,
						   COAAccountCode,
						   Transactionid,
						   Saleid,
						   SiteID,
						   OperatingAreaID,
						   Workstationid,
						   UserGroupID,
						   userID,
						   batchdate,
						   TransDate,
						   quantity,
						   grossamount,
						   netamount,
						   price,
						   percentage,
						   remaningValues, 	
						   Accountingtype,		
						   RRCalcTypeTrigger,
						   RRPercentage,
						   RRDays																																																																																			

		
		End
</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE><ADDEDBY>kdixon</ADDEDBY><SQLVERSION>2317</SQLVERSION><RMTRACKLINK>71752</RMTRACKLINK><REASON>Add new Index to Data_TicketStatus table</REASON><TABLENAMES></TABLENAMES><SQLSCRIPTLIST><SCRIPT>IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name='IDX_DATA_TicketStatus_TicketId_Active' AND object_id = OBJECT_ID('DBO.DATA_TicketStatus'))
begin
	CREATE NONCLUSTERED INDEX [IDX_DATA_TicketStatus_TicketId_Active] ON [dbo].[DATA_TicketStatus]
	(
		[TicketId] ASC,
		[Active] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
end
</SCRIPT></SQLSCRIPTLIST></SQLUPDATE><SQLUPDATE>
			<ADDEDBY>smcdonald</ADDEDBY>
			<SQLVERSION>2316</SQLVERSION>
			<RMTRACKLINK>69691</RMTRACKLINK>
			<REASON>Add new column to DATA_TicketHistory</REASON>
			<TABLENAMES>DATA_TicketHistory=TicketHistoryId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'PriorActiveToDate' AND
                Object_ID  = Object_ID(N'DATA_TicketHistory'))
BEGIN
  ALTER TABLE DATA_TicketHistory ADD PriorActiveToDate datetime NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>smcdonald</ADDEDBY>
			<SQLVERSION>2315</SQLVERSION>
			<RMTRACKLINK>67297</RMTRACKLINK>
			<REASON>Add new column to TravelMatrix table</REASON>
			<TABLENAMES>CNF_TravelMatrix=TravelMatrixId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Active' AND
                Object_ID  = Object_ID(N'CNF_TravelMatrix'))
BEGIN
  ALTER TABLE CNF_TravelMatrix ADD Active smallint default 0
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>kdixon</ADDEDBY>
			<SQLVERSION>2314</SQLVERSION>
			<RMTRACKLINK>71376</RMTRACKLINK>
			<REASON>Chart of Accounts-Phase 2 - Sprint 3</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_RR_RevenueData_PaymentMethodTaxDiscounts2]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_RR_RevenueData_PaymentMethodTaxDiscounts2
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE Procedure dbo.otn_sp_RR_RevenueData_PaymentMethodTaxDiscounts2
	@BatchDate Date,
	@Transactions varchar(500),
	@Trigger int,
	@RRTransDateType Integer
AS 
BEGIN
	 
	Create Table #TransactionIDs(
	TransactionId Int NOT NULL)

	DECLARE @DelimPosition INT

    SET @DelimPosition = CHARINDEX(',', @Transactions)

    WHILE @DelimPosition &gt; 0
    BEGIN
        INSERT INTO #TransactionIDs(TransactionId)
            VALUES(CAST(RTRIM(LEFT(@Transactions, @DelimPosition - 1)) AS INT))
        SET @Transactions = right(@Transactions, len(@Transactions) - @DelimPosition)

        SET @DelimPosition = CHARINDEX(',', @Transactions)
    END


	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer

	Declare @OnCreditWriteoff Integer = 9
	Declare @StartTime DateTime

	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1
	

		--Normal Sale Split out the Payments to Smaller Subset.
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays]
				   ,[attributeids])				    
						select distinct COA.COAAccountId, 
								p.RevenueRecognitionRuleId,
								p.code,		   
								p.RRCalcTypeWhere,
								p.RRCalcTypeMethod,	   
								p.COAAccountConfigId,
								p.COAAccountTypeId,
								COA.Code,
								RR_DATA_REVENUE.Transactionid as Transactionid,
								RR_DATA_REVENUE.saleid as Saleid,
								RR_DATA_REVENUE.Siteid as SiteID,
								RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								RR_DATA_REVENUE.Workstationid as Workstationid,
								RR_DATA_REVENUE.UserGroupid as UserGroupID,
								RR_DATA_REVENUE.UserId as userID,
								@BatchDate as BatchDate,
							   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
									else DATA_Transaction.transactiondate
							   end as TransDate,
								0 as Quantity,
								0 as GrossAmount,
								0 as NetAmount,
								0 as ConfigPrice,
								100 as ConfigPercentage,
								0 RemainingValues,	
								ABS ((data_payment.PaymentAmount + data_payment.PaymentFee) - 
							   (case when data_payment.paymentid = (select top 1 paymentid
																	from data_payment
																	where transactionid = RR_DATA_REVENUE.Transactionid
																		and data_payment.paymentamount &gt; (select sum(Change) *-1
																									from data_transaction
																									where data_transaction.transactionid = RR_DATA_REVENUE.Transactionid))
									then (select sum(Change) *-1
																									from data_transaction
																									where data_transaction.transactionid = RR_DATA_REVENUE.Transactionid)
									else 0
								end ))
								as RevenueAmount,
							--	p.Accountingtype,		
								case    when DATA_Transaction.TransactionType in (5, 8, 17, 18, 20, 22, 30) and p.Accountingtype = 1 then 2
										when DATA_Transaction.TransactionType in (5, 8, 17, 18, 20, 22, 30) and p.Accountingtype = 2 then 1
										when DATA_Transaction.TransactionType in (7) and (RR_DATA_REVENUE.revenueAmount) &lt;= 0  then 1
										when DATA_Transaction.TransactionType in (7) and (RR_DATA_REVENUE.revenueAmount) &gt; 0  then 2
										else p.Accountingtype
								end Accountingtype,
							   p.RRCalcTypeTrigger,
							   p.RRPercentage,
							   p.Days,
							   RR_DATA_REVENUE.attributeids

					from RR_DATA_REVENUE
									INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
									INNER JOIN (select '1' as PCOAAccountid, 
													   coa_cnf_accountConfig.Siteid, 
													   RR_CNF_RevenueRecognitionRule.Enabled, 
													   RR_CNF_RevenueRecognitionRule.FromDate, 
													   RR_CNF_RevenueRecognitionRule.ToDate,
													   COA_CNF_AccountConfig.RemainingValues,
													   coa_cnf_account.coaaccountid,
													   COA_CNF_AccountConfig.Price,
													   COA_CNF_AccountConfig.Percentage,
													   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
													   RR_CNF_RevenueRecognitionRule.code,		   
													   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
													   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
													   COA_CNF_AccountConfig.COAAccountConfigId,
													   coa_cnf_account.COAAccountTypeId,
													   coa_cnf_account.Code as accountcode,
													   coa_cnf_accountconfig.Accountingtype,
													   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
													   RR_CNF_RevenueRecognitionRule.Percentage rrPercentage,
													   RR_CNF_RevenueRecognitionRule.Days	

													from RR_CNF_RevenueRecognitionRule	
													INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
													INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid and coa_cnf_account.Enabled = 1
													INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
												where  RR_CNF_RevenueRecognitionRule.Enabled = 1
												and coa_cnf_account.coaaccountid in (@ACCPaymentMethod)) p				on p.PCOAAccountid = rr_data_revenue.coaaccountid 
							INNER JOIN data_payment							on data_payment.transactionid = rr_data_revenue.transactionid
							left  JOIN DATA_PaymentCard						on data_paymentcard.paymentid = data_payment.PaymentId
							left JOIN CNF_PaymentCard						on cnf_paymentcard.paymentcardid = data_paymentcard.paymentcardid
							INNER JOIN CNF_PaymentMethod					on CNF_PaymentMethod.PaymentMethodId = data_payment.PaymentMethodId
							INNER JOIN COA_CNF_Account COA					on COA.COAAccountid = ISNULL(cnf_paymentcard.coaaccountid, CNF_PaymentMethod.COAAccountid)


						where data_payment.paymentstatus = 1
						and DATA_Transaction.TransactionType in (select transactionid
																from #TransactionIDs)
						and RR_DATA_REVENUE.fcalcdate = @BatchDate
						and @BatchDate between p.FromDate and p.ToDate
						AND data_payment.Transactionid not in (select distinct transactionid
													from rr_Data_Revenue
													where coaaccountid in (select distinct coaaccountid
																				from cnf_paymentmethod CP
																				where coaaccountid is not null
																				union all
																				select distinct coaaccountid
																				from cnf_paymentcard pc
																				where coaaccountid is not null
																			)
													)
						AND data_payment.Transactionid in (select distinct transactionid
													from rr_Data_Revenue
													where coaaccountid in (@ACCPaymentMethod)
													)
						 AND RR_DATA_REVENUE.coaaccountid not in (@ACCPaymentMethod)


----Breakage for Fixed Vouchers.   The left over money.
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])				    
					select distinct COA.COAAccountId, 
						   p.RevenueRecognitionRuleId,
						   p.RRCode,		   
						   p.RRCalcTypeWhere,
						   p.RRCalcTypeMethod,	   
						   p.COAAccountConfigId,
						   COA.COAAccountTypeId,
						   COA.Code,
						   RR_DATA_REVENUE.Transactionid as Transactionid,
						   RR_DATA_REVENUE.saleid as Saleid,
						   RR_DATA_REVENUE.Siteid as SiteID,
						   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
						   RR_DATA_REVENUE.Workstationid as Workstationid,
						   RR_DATA_REVENUE.UserGroupid as UserGroupID,
						   RR_DATA_REVENUE.UserId as userID,
						   @BatchDate,
						   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
							    else DATA_Transaction.transactiondate
						   end as TransDate,
						   0,
						   0,
						   0,
						   0,
						   100,
						   0,  	
						  ABS(DATA_Transaction.Tip) as RevenueAmount,
							2 accountingtype,		
							p.RRCalcTypeTrigger,
							p.RRPercentage,
							p.RRDays

						from RR_DATA_REVENUE

							INNER JOIN data_transaction		on data_transaction.transactionid = rr_data_revenue.transactionid
							INNER JOIN DATA_Payment			on data_payment.transactionid = data_transaction.transactionid
							INNER JOIN CNF_PaymentMethod	on cnf_paymentmethod.paymentmethodid = data_payment.paymentmethodid
							INNER JOIN CNF_Driver			on cnf_driver.driverID = cnf_paymentmethod.driverid
							INNER JOIN COA_CNF_Account COA	on COA.COAAccountid = CNF_PaymentMethod.FixedVoucherCOAAccountId


							INNER JOIN (select transactionid, RevenueRecognitionRuleId, RR_DATA_Revenue.RRCode, RRCalcTypeWhere, 
																	RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount,  Accountingtype
																	from RR_DATA_Revenue
																	INNER JOIN COA_CNF_Account		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
																	where COA_CNF_Account.coaAccountID = @ACCPaymentMethod
																)p    on p.transactionid = 	data_payment.transactionid


						where data_payment.paymentstatus = 1
						  and TransactionType in (select transactionid
														from #TransactionIDs)
							and DATA_Transaction.tip &lt;&gt; 0
							and RR_DATA_REVENUE.fcalcdate = @BatchDate


		----Normal Sale Split out the Payments to Payment Fees
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays]
				   ,[attributeids])				    
				select distinct COA.COAAccountId, 
						   p.RevenueRecognitionRuleId,
						   p.RRCode,		   
						   p.RRCalcTypeWhere,
						   p.RRCalcTypeMethod,	   
						   p.COAAccountConfigId,
						   COA.COAAccountTypeId,
						   COA.Code,
						   RR_DATA_REVENUE.Transactionid as Transactionid,
						   RR_DATA_REVENUE.saleid as Saleid,
						   RR_DATA_REVENUE.Siteid as SiteID,
						   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
						   RR_DATA_REVENUE.Workstationid as Workstationid,
						   RR_DATA_REVENUE.UserGroupid as UserGroupID,
						   RR_DATA_REVENUE.UserId as userID,
						   @BatchDate,
						   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
							    else DATA_Transaction.transactiondate
						   end as TransDate,
						   0,
						   0,
						   0,
						   0,
						   100,
						   0,  	
						   data_payment.paymentfee as RevenueAmount,
						   case when data_payment.paymentfee &gt;= 0 then 2
						        else 1
							end accountingtype,		
						   p.RRCalcTypeTrigger,
						   p.RRPercentage,
						   p.RRDays,
						   RR_DATA_REVENUE.AttributeIDs

						from RR_DATA_REVENUE
						inner join rr_cnf_Product						ON ((RR_DATA_REVENUE.MATRIXCELLID = rr_cnf_Product.MATRIXCELLID) 
                                            or (RR_DATA_REVENUE.MatrixSheetId = rr_cnf_Product.MatrixSheetId)
											or (rr_cnf_product.Attributeid in (select top 1 Attributeid
																				from rr_cnf_product
																				where Attributeid in (select Value
																										from dbo.split((select rr.Attributeids
																														from rr_data_revenue rr
																														where rr.revenuerecognitiondataid = RR_DATA_REVENUE.revenuerecognitiondataid), '.')
																										)
																			)
												))
											and rr_cnf_Product.Enabled = 1
						inner join RR_CNF_RevenueRecognitionRule		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_cnf_Product.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  
						INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
						INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
						INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 
						INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
						INNER JOIN data_payment							on data_payment.transactionid = rr_data_revenue.transactionid
						left  JOIN DATA_PaymentCard						on data_paymentcard.paymentid = data_payment.PaymentId
						left JOIN CNF_PaymentCard						on cnf_paymentcard.paymentcardid = data_paymentcard.paymentcardid
						INNER JOIN CNF_PaymentMethod					on CNF_PaymentMethod.PaymentMethodId = data_payment.PaymentMethodId
						INNER JOIN COA_CNF_Account COA					on COA.COAAccountid = CNF_PaymentMethod.FeeCOAAccountId

						INNER JOIN (select transactionid, RevenueRecognitionRuleId, RR_DATA_Revenue.RRCode, RRCalcTypeWhere, 
											RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount,  Accountingtype
											from RR_DATA_Revenue
											INNER JOIN COA_CNF_Account		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
											where COA_CNF_Account.coaAccountID = @ACCPaymentMethod
										)p    on p.transactionid = 	data_payment.transactionid

					where data_payment.paymentstatus = 1
					and DATA_Transaction.TransactionType in (select transactionid
																from #TransactionIDs)
					and data_payment.paymentfee &lt;&gt; 0
					and RR_DATA_REVENUE.fcalcdate = @BatchDate
					and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
					AND data_payment.Transactionid not in (select distinct transactionid
												from rr_Data_Revenue
												where coaaccountid in (select distinct FeeCOAAccountId
																			from cnf_paymentmethod CP
																		)
												)
					AND data_payment.Transactionid in (select distinct transactionid
												from rr_Data_Revenue
												where coaaccountid in (@ACCPaymentMethod)
												)


							


		--	--Normal Transactions Reverse out of PaymentMethods
			INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays]
				   ,[AttributeIDs])				    					
				   select COAAccountId, 
						   Max(RevenueRecognitionRuleId),
						   Max(RRCode),		   
						   RRCalcTypeWhere,
						   RRCalcTypeMethod,	   
						   Max(COAAccountConfigId),
						   COAAccountTypeId,
						   COAAccountCode,
						   Transactionid,
						   saleid,
						   Siteid,
						   OperatingAreaId,
						   Workstationid,
						   UserGroupid,
						   UserId,
						   batchdate,
						   TransDate,
						   0,
						   0,
						   0,						
						   0,
						   0,
						   0,
						   ABS(sum(RevenueAmount)) as RevenueAmount,
				           case when accountingtype = 1 then 2
					        else 1
						   end Accountingtype,		
						   RRCalcTypeTrigger,
						   RRPercentage,
						   RRDays,
						   AttributeIDs
						   from (
							select distinct 
								       p.COAAccountId, 
									   p.RevenueRecognitionRuleId,
									   p.RRCode,		   
									   p.RRCalcTypeWhere,
									   p.RRCalcTypeMethod,	   
									   p.COAAccountConfigId,
									  p.COAAccountTypeId,
									   p.COAAccountCode,
									   rr_data_Revenue.Transactionid Transactionid,
									   rr_data_Revenue.saleid saleid,
									   rr_data_Revenue.Siteid siteid,
									   rr_data_Revenue.OperatingAreaId OperatingAreaid,
									   rr_data_Revenue.Workstationid workstationid,
									   rr_data_Revenue.UserGroupid usergroupid,
									   rr_data_Revenue.UserId userid,
									   @BatchDate batchdate,
									   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
											else DATA_Transaction.transactiondate
									   end as TransDate,
									   rr_data_Revenue.RevenueAmount *-1  as RevenueAmount,
								       p.Accountingtype,
									   transactiontype,		
									   p.RRCalcTypeTrigger,
									   p.RRPercentage,
									   p.RRDays,
									   rr_data_Revenue.AttributeIDs
							FROM rr_data_Revenue   				        WITH (NOLOCK)
								   INNER JOIN (select saleid, transactionid, RevenueRecognitionRuleId, RR_DATA_Revenue.RRCode, RRCalcTypeWhere, Saleitemid, RR_DATA_Revenue.COAAccountId, 
													   RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount, COA_CNF_Account.COAAccountTypeId,  Accountingtype,
													   RR_DATA_Revenue.COAAccountCode
													  from RR_DATA_Revenue
														INNER JOIN COA_CNF_Account		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
													 where COA_CNF_Account.coaAccountID = @ACCPaymentMethod
													   --and rr_data_revenue.RRCalcTypeTrigger = @Trigger
													)p								ON p.transactionid = 	rr_data_Revenue.transactionid
									INNER JOIN DATA_Transaction			on data_transaction.transactionid = rr_data_revenue.transactionid
							where RR_DATA_REVENUE.fcalcdate = @BatchDate
							  and DATA_Transaction.TransactionType in (select transactionid
																from #TransactionIDs)
							  and rr_data_Revenue.coaaccountid in (select distinct coaaccountid
																	 from cnf_paymentmethod
																	 where coaaccountid is not null
																	union all
																   select distinct coaaccountid
																	 from cnf_paymentcard
																	 where coaaccountid is not null
																  )
						)r	
							group by	 COAAccountId, 		   
									   RRCalcTypeWhere,
									   RRCalcTypeMethod,	   
									   COAAccountTypeId,
									   COAAccountCode,
									   Transactionid,
									   saleid,
									   Siteid,
									   OperatingAreaId,
									   Workstationid,
									   UserGroupid,
									   UserId,
									   batchdate,
									   TransDate,					
									   Accountingtype,		
									   RRCalcTypeTrigger,
									   RRPercentage,
									   RRDays, 
									   TransactionType, 
									   AttributeIDs


----Normal Sale Split out the Payments to Payment Fees
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays]
				   ,[AttributeIDs])				    
				select distinct COA.COAAccountId, 
						   p.RevenueRecognitionRuleId,
						   p.RRCode,		   
						   p.RRCalcTypeWhere,
						   p.RRCalcTypeMethod,	   
						   p.COAAccountConfigId,
						   COA.COAAccountTypeId,
						   COA.Code,
						   RR_DATA_REVENUE.Transactionid as Transactionid,
						   RR_DATA_REVENUE.saleid as Saleid,
						   RR_DATA_REVENUE.Siteid as SiteID,
						   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
						   RR_DATA_REVENUE.Workstationid as Workstationid,
						   RR_DATA_REVENUE.UserGroupid as UserGroupID,
						   RR_DATA_REVENUE.UserId as userID,
						   @BatchDate,
						   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
							    else DATA_Transaction.transactiondate
						   end as TransDate,
						   0,
						   0,
						   0,
						   0,
						   100,
						   0,  	
						  ABS(data_ledger.entryAmount) as RevenueAmount,
							case when data_ledger.entryAmount &gt;= 0 then 1
								else 2
							end accountingtype,		
							p.RRCalcTypeTrigger,
							p.RRPercentage,
							p.RRDays,
							RR_DATA_Revenue.AttributeIDs

						from RR_DATA_REVENUE
						inner join rr_cnf_Product						ON ((RR_DATA_REVENUE.MATRIXCELLID = rr_cnf_Product.MATRIXCELLID) 
                                            or (RR_DATA_REVENUE.MatrixSheetId = rr_cnf_Product.MatrixSheetId)
											or (rr_cnf_product.Attributeid in (select top 1 Attributeid
																				from rr_cnf_product
																				where Attributeid in (select Value
																										from dbo.split((select rr.Attributeids
																														from rr_data_revenue rr
																														where rr.revenuerecognitiondataid = RR_DATA_REVENUE.revenuerecognitiondataid), '.')
																										)
																			)
												))
											and rr_cnf_Product.Enabled = 1
						inner join RR_CNF_RevenueRecognitionRule		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_cnf_Product.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  

						INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
						INNER JOIN data_payment							on data_payment.transactionid = rr_data_revenue.transactionid
						left  JOIN DATA_PaymentCard						on data_paymentcard.paymentid = data_payment.PaymentId
						left JOIN CNF_PaymentCard						on cnf_paymentcard.paymentcardid = data_paymentcard.paymentcardid
						INNER JOIN CNF_PaymentMethod					on CNF_PaymentMethod.PaymentMethodId = data_payment.PaymentMethodId
						INNER JOIN COA_CNF_Account COA					on COA.COAAccountid = CNF_PaymentMethod.returnedcheckcoaaccountid
						INNER JOIN data_ledger							ON data_ledger.transactionid = data_transaction.transactionid
						INNER JOIN cnf_ledgeraccount					ON cnf_ledgeraccount.LedgerAccountId = data_ledger.ledgeraccountid
												INNER JOIN (select transactionid, RevenueRecognitionRuleId, RR_DATA_Revenue.RRCode, RRCalcTypeWhere, 
																	RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount,  Accountingtype
																	from RR_DATA_Revenue
																	INNER JOIN COA_CNF_Account		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
																	where COA_CNF_Account.coaAccountID = @ACCPaymentMethod
																)p    on p.transactionid = 	data_payment.transactionid


						where data_payment.paymentstatus = 1
							and DATA_Transaction.TransactionType in (select transactionid
																from #TransactionIDs)
							and DATA_Transaction.tip &lt;&gt; 0
							and RR_DATA_REVENUE.fcalcdate = @BatchDate
							and systemaccounttable = 119
							and systemaccountid = 15
							and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
							
																			
		End
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_RR_RevenueData_PaymentMethodTaxDiscounts]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_RR_RevenueData_PaymentMethodTaxDiscounts
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE Procedure dbo.otn_sp_RR_RevenueData_PaymentMethodTaxDiscounts
	@BatchDate Date,
	@Transactions varchar(500),
	@Trigger int,
	@RRTransDateType integer
AS 
BEGIN
	 
	Create Table #TransactionIDs(
	TransactionId Int NOT NULL)

	DECLARE @DelimPosition INT

    SET @DelimPosition = CHARINDEX(',', @Transactions)

    WHILE @DelimPosition &gt; 0
    BEGIN
        INSERT INTO #TransactionIDs(TransactionId)
            VALUES(CAST(RTRIM(LEFT(@Transactions, @DelimPosition - 1)) AS INT))
        SET @Transactions = right(@Transactions, len(@Transactions) - @DelimPosition)

        SET @DelimPosition = CHARINDEX(',', @Transactions)
    END

	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer

	Declare @OnCreditWriteoff Integer = 9
	Declare @StartTime DateTime

	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1
	

		--	--	--Normal Sale Split out the Payments to Smaller Subset.
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])				    
						select distinct COA.COAAccountId, 
						   p.RevenueRecognitionRuleId,
						   p.RRCode,		   
						   p.RRCalcTypeWhere,
						   p.RRCalcTypeMethod,	   
						   p.COAAccountConfigId,
						   COA.COAAccountTypeId,
						   COA.Code,
						   RR_DATA_REVENUE.Transactionid as Transactionid,
						   RR_DATA_REVENUE.saleid as Saleid,
						   RR_DATA_REVENUE.Siteid as SiteID,
						   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
						   RR_DATA_REVENUE.Workstationid as Workstationid,
						   RR_DATA_REVENUE.UserGroupid as UserGroupID,
						   RR_DATA_REVENUE.UserId as userID,
						   @BatchDate,
						   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
							    else DATA_Transaction.transactiondate
						   end as TransDate,
						   0,
						   0,
						   0,
						   0,
						   100,
						   0, 	
						   ABS ((data_payment.PaymentAmount) -
						   (case when data_payment.paymentid = (select top 1 paymentid
																from data_payment
																where transactionid = RR_DATA_REVENUE.Transactionid
																	and data_payment.paymentamount &gt; (select sum(Change) *-1
																								from data_transaction
																								where data_transaction.transactionid = RR_DATA_REVENUE.Transactionid))
								then (select sum(Change) *-1
																								from data_transaction
																								where data_transaction.transactionid = RR_DATA_REVENUE.Transactionid)
								else 0
							end ))
							as RevenueAmount,
							p.Accountingtype,		
						    p.RRCalcTypeTrigger,
						    p.RRPercentage,
						    p.RRDays

						from RR_DATA_REVENUE
						INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
						INNER JOIN data_payment							on data_payment.transactionid = rr_data_revenue.transactionid
						left  JOIN DATA_PaymentCard						on data_paymentcard.paymentid = data_payment.PaymentId
						left JOIN CNF_PaymentCard						on cnf_paymentcard.paymentcardid = data_paymentcard.paymentcardid
						INNER JOIN CNF_PaymentMethod					on CNF_PaymentMethod.PaymentMethodId = data_payment.PaymentMethodId
						INNER JOIN COA_CNF_Account COA					on COA.COAAccountid = ISNULL(cnf_paymentcard.coaaccountid, CNF_PaymentMethod.COAAccountid)

						INNER JOIN (select transactionid, RevenueRecognitionRuleId, RR_DATA_Revenue.RRCode, RRCalcTypeWhere, 
											RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount,  Accountingtype
											from RR_DATA_Revenue
											INNER JOIN COA_CNF_Account		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
											where COA_CNF_Account.coaAccountID = @ACCPaymentMethod
											--and RR_DATA_Revenue.RRCalcTypeTrigger = @Trigger
											and RR_DATA_REVENUE.fcalcdate = @BatchDate
										)p    on p.transactionid = 	data_payment.transactionid

					where data_payment.paymentstatus = 1
					and DATA_Transaction.TransactionType in (select transactionid
																from #TransactionIDs)
					and RR_DATA_REVENUE.fcalcdate = @BatchDate
					AND data_payment.Transactionid not in (select distinct transactionid
												from rr_Data_Revenue
												where coaaccountid in (select distinct coaaccountid
																			from cnf_paymentmethod CP
																			where coaaccountid is not null
																			union all
																			select distinct coaaccountid
																			from cnf_paymentcard pc
																			where coaaccountid is not null
																		)
												)
					AND data_payment.Transactionid in (select distinct transactionid
												from rr_Data_Revenue
												where coaaccountid in (@ACCPaymentMethod)
												)
					 AND RR_DATA_REVENUE.coaaccountid not in (@ACCPaymentMethod)


		----Normal Sale Split out the Payments to Payment Fees
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])				    
				select distinct COA.COAAccountId, 
						   p.RevenueRecognitionRuleId,
						   p.RRCode,		   
						   p.RRCalcTypeWhere,
						   p.RRCalcTypeMethod,	   
						   p.COAAccountConfigId,
						   COA.COAAccountTypeId,
						   COA.Code,
						   RR_DATA_REVENUE.Transactionid as Transactionid,
						   RR_DATA_REVENUE.saleid as Saleid,
						   RR_DATA_REVENUE.Siteid as SiteID,
						   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
						   RR_DATA_REVENUE.Workstationid as Workstationid,
						   RR_DATA_REVENUE.UserGroupid as UserGroupID,
						   RR_DATA_REVENUE.UserId as userID,
						   @BatchDate,
						   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
							    else DATA_Transaction.transactiondate
						   end as TransDate,
						   0,
						   0,
						   0,
						   0,
						   100,
						   0,  	
						   data_payment.paymentfee as RevenueAmount,
						   case when data_payment.paymentfee &gt;= 0 then 2
						        else 1
							end accountingtype,		
						   p.RRCalcTypeTrigger,
						   p.RRPercentage,
						   p.RRDays

						from RR_DATA_REVENUE
						INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
						INNER JOIN data_payment							on data_payment.transactionid = rr_data_revenue.transactionid
						left  JOIN DATA_PaymentCard						on data_paymentcard.paymentid = data_payment.PaymentId
						left JOIN CNF_PaymentCard						on cnf_paymentcard.paymentcardid = data_paymentcard.paymentcardid
						INNER JOIN CNF_PaymentMethod					on CNF_PaymentMethod.PaymentMethodId = data_payment.PaymentMethodId
						INNER JOIN COA_CNF_Account COA					on COA.COAAccountid = CNF_PaymentMethod.FeeCOAAccountId

						INNER JOIN (select transactionid, RevenueRecognitionRuleId, RR_DATA_Revenue.RRCode, RRCalcTypeWhere, 
											RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount,  Accountingtype
											from RR_DATA_Revenue
											INNER JOIN COA_CNF_Account		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
											where COA_CNF_Account.coaAccountID = @ACCPaymentMethod
										)p    on p.transactionid = 	data_payment.transactionid

					where data_payment.paymentstatus = 1
					and DATA_Transaction.TransactionType in (select transactionid
																from #TransactionIDs)
					and data_payment.paymentfee &lt;&gt; 0
					and RR_DATA_REVENUE.fcalcdate = @BatchDate
					--and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
					AND data_payment.Transactionid not in (select distinct transactionid
												from rr_Data_Revenue
												where coaaccountid in (select distinct FeeCOAAccountId
																			from cnf_paymentmethod CP
																		)
												)
					AND data_payment.Transactionid in (select distinct transactionid
												from rr_Data_Revenue
												where coaaccountid in (@ACCPaymentMethod)
												)


		--	--Normal Transactions Reverse out of PaymentMethods
			INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])				    					
					select COAAccountId, 
						   Max(RevenueRecognitionRuleId),
						   Max(RRCode),		   
						   RRCalcTypeWhere,
						   RRCalcTypeMethod,	   
						   Max(COAAccountConfigId),
						   COAAccountTypeId,
						   COAAccountCode,
						   Transactionid,
						   saleid,
						   Siteid,
						   OperatingAreaId,
						   Workstationid,
						   UserGroupid,
						   UserId,
						   batchdate,
						   TransDate,
						   0,
						   0,
						   0,						
						   0,
						   0,
						   0,
						   ABS(sum(RevenueAmount)) as RevenueAmount,
						   case when accountingtype = 1 then 2
								else 1
							end Accountingtype,		
						   RRCalcTypeTrigger,
						   RRPercentage,
						   RRDays
						   from (
			select distinct rr_data_Revenue.coaaccountid as rrcoaaccountid,
								       p.COAAccountId, 
									   p.RevenueRecognitionRuleId,
									   p.RRCode,		   
									   p.RRCalcTypeWhere,
									   p.RRCalcTypeMethod,	   
									   p.COAAccountConfigId,
									   p.COAAccountTypeId,
									   p.COAAccountCode,
									   rr_data_Revenue.Transactionid Transactionid,
									   rr_data_Revenue.saleid saleid,
									   rr_data_Revenue.Siteid siteid,
									   rr_data_Revenue.OperatingAreaId OperatingAreaid,
									   rr_data_Revenue.Workstationid workstationid,
									   rr_data_Revenue.UserGroupid usergroupid,
									   rr_data_Revenue.UserId userid,
									   @BatchDate batchdate,
									   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
											else DATA_Transaction.transactiondate
									   end as TransDate,
									   rr_data_Revenue.RevenueAmount  as RevenueAmount,
								       p.Accountingtype,
									   transactiontype,		
									   p.RRCalcTypeTrigger,
									   p.RRPercentage,
									   p.RRDays
							FROM rr_data_Revenue   				        WITH (NOLOCK)
								   INNER JOIN (select saleid, transactionid, RevenueRecognitionRuleId, RR_DATA_Revenue.RRCode, RRCalcTypeWhere, Saleitemid, RR_DATA_Revenue.COAAccountId, 
													   RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount, COA_CNF_Account.COAAccountTypeId,  Accountingtype,
													   RR_DATA_Revenue.COAAccountCode
													  from RR_DATA_Revenue
														INNER JOIN COA_CNF_Account		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
													 where COA_CNF_Account.coaAccountID = @ACCPaymentMethod
													-- and rr_data_Revenue.RRCalcTypeTrigger = @Trigger
													)p								ON p.transactionid = 	rr_data_Revenue.transactionid
									INNER JOIN DATA_Transaction			on data_transaction.transactionid = rr_data_revenue.transactionid
							where RR_DATA_REVENUE.fcalcdate = @BatchDate
							  
							  and DATA_Transaction.TransactionType in (select transactionid
																from #TransactionIDs)
							  and rr_data_Revenue.coaaccountid in (select distinct coaaccountid
																	 from cnf_paymentmethod
																	 where coaaccountid is not null
																	union all
																   select distinct coaaccountid
																	 from cnf_paymentcard
																	 where coaaccountid is not null

																  )
						)r	
							group by	 COAAccountId, 		   
									   RRCalcTypeWhere,
									   RRCalcTypeMethod,	   
									   COAAccountTypeId,
									   COAAccountCode,
									   Transactionid,
									   saleid,
									   Siteid,
									   OperatingAreaId,
									   Workstationid,
									   UserGroupid,
									   UserId,
									   batchdate,
									   TransDate,					
									   Accountingtype,		
									   RRCalcTypeTrigger,
									   RRPercentage,
									   RRDays, 
									   TransactionType
							

----Normal Sale Split out the Payments to returned Checks
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])				    
				select distinct COA.COAAccountId, 
						   p.RevenueRecognitionRuleId,
						   p.RRCode,		   
						   p.RRCalcTypeWhere,
						   p.RRCalcTypeMethod,	   
						   p.COAAccountConfigId,
						   COA.COAAccountTypeId,
						   COA.Code,
						   RR_DATA_REVENUE.Transactionid as Transactionid,
						   RR_DATA_REVENUE.saleid as Saleid,
						   RR_DATA_REVENUE.Siteid as SiteID,
						   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
						   RR_DATA_REVENUE.Workstationid as Workstationid,
						   RR_DATA_REVENUE.UserGroupid as UserGroupID,
						   RR_DATA_REVENUE.UserId as userID,
						   @BatchDate,
						   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
							    else DATA_Transaction.transactiondate
						   end as TransDate,
						   0,
						   0,
						   0,
						   0,
						   100,
						   0,  	
						  ABS(data_ledger.entryAmount) as RevenueAmount,
							case when data_ledger.entryAmount &gt;= 0 then 1
								else 2
							end accountingtype,		
							p.RRCalcTypeTrigger,
							p.RRPercentage,
							p.RRDays

						from RR_DATA_REVENUE
						INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
						INNER JOIN data_payment							on data_payment.transactionid = rr_data_revenue.transactionid
						left  JOIN DATA_PaymentCard						on data_paymentcard.paymentid = data_payment.PaymentId
						left JOIN CNF_PaymentCard						on cnf_paymentcard.paymentcardid = data_paymentcard.paymentcardid
						INNER JOIN CNF_PaymentMethod					on CNF_PaymentMethod.PaymentMethodId = data_payment.PaymentMethodId
						INNER JOIN COA_CNF_Account COA					on COA.COAAccountid = CNF_PaymentMethod.returnedcheckcoaaccountid
						INNER JOIN data_ledger							ON data_ledger.transactionid = data_transaction.transactionid
						INNER JOIN cnf_ledgeraccount					ON cnf_ledgeraccount.LedgerAccountId = data_ledger.ledgeraccountid
												INNER JOIN (select transactionid, RevenueRecognitionRuleId, RR_DATA_Revenue.RRCode, RRCalcTypeWhere, 
																	RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount,  Accountingtype
																	from RR_DATA_Revenue
																	INNER JOIN COA_CNF_Account		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
																	where COA_CNF_Account.coaAccountID = @ACCPaymentMethod
																)p    on p.transactionid = 	data_payment.transactionid


						where data_payment.paymentstatus = 1
							and DATA_Transaction.TransactionType in (select transactionid
																from #TransactionIDs)
							and DATA_Transaction.tip &lt;&gt; 0
							and RR_DATA_REVENUE.fcalcdate = @BatchDate
							and systemaccounttable = 119
							and systemaccountid = 15

----Breakage for Fixed Vouchers.   The left over money.
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])				    
					select distinct COA.COAAccountId, 
						   p.RevenueRecognitionRuleId,
						   p.RRCode,		   
						   p.RRCalcTypeWhere,
						   p.RRCalcTypeMethod,	   
						   p.COAAccountConfigId,
						   COA.COAAccountTypeId,
						   COA.Code,
						   RR_DATA_REVENUE.Transactionid as Transactionid,
						   RR_DATA_REVENUE.saleid as Saleid,
						   RR_DATA_REVENUE.Siteid as SiteID,
						   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
						   RR_DATA_REVENUE.Workstationid as Workstationid,
						   RR_DATA_REVENUE.UserGroupid as UserGroupID,
						   RR_DATA_REVENUE.UserId as userID,
						   @BatchDate,
						   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
							    else DATA_Transaction.transactiondate
						   end as TransDate,
						   0,
						   0,
						   0,
						   0,
						   100,
						   0,  	
						  ABS(DATA_Transaction.Tip) as RevenueAmount,
							2 accountingtype,		
							p.RRCalcTypeTrigger,
							p.RRPercentage,
							p.RRDays

						from RR_DATA_REVENUE

							INNER JOIN data_transaction		on data_transaction.transactionid = rr_data_revenue.transactionid
							INNER JOIN DATA_Payment			on data_payment.transactionid = data_transaction.transactionid
							INNER JOIN CNF_PaymentMethod	on cnf_paymentmethod.paymentmethodid = data_payment.paymentmethodid
							INNER JOIN CNF_Driver			on cnf_driver.driverID = cnf_paymentmethod.driverid
							INNER JOIN COA_CNF_Account COA	on COA.COAAccountid = CNF_PaymentMethod.FixedVoucherCOAAccountId


							INNER JOIN (select transactionid, RevenueRecognitionRuleId, RR_DATA_Revenue.RRCode, RRCalcTypeWhere, 
																	RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount,  Accountingtype
																	from RR_DATA_Revenue
																	INNER JOIN COA_CNF_Account		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
																	where COA_CNF_Account.coaAccountID = @ACCPaymentMethod
																)p    on p.transactionid = 	data_payment.transactionid


						where data_payment.paymentstatus = 1
						  and TransactionType in (select transactionid
														from #TransactionIDs)
							and DATA_Transaction.tip &lt;&gt; 0
							and RR_DATA_REVENUE.fcalcdate = @BatchDate


				--Normal Transaction break out Tax
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])				    
						  select COAAccountId, 
						   MIN(p.RevenueRecognitionRuleId),
						   MIN(p.RRCode),		   
						   RRCalcTypeWhere,
						   RRCalcTypeMethod,	   
						   COAAccountConfigId,
						   COAAccountTypeId,
						   COACODE,
						   Transactionid,
						   saleid,
						   Siteid,
						   OperatingAreaId,
						   Workstationid,
						   UserGroupid,
						   UserId,
						   batchdate,
						   TransDate,
						   0,
						   0,
						   0,						
						   price,
						   percentage,
						   test,
						   ABS(sum(RevenueAmount)) as RevenueAmount,
				           case when TransactionType in (5, 17, 18, 20, 22, 30) and sum(RevenueAmount) &lt;= 0  then 1
						        when TransactionType in (5, 17, 18, 20, 22, 30) and sum(RevenueAmount) &lt;= 0  then 2
								when TransactionType in (7) and sum(RevenueAmount) &lt;= 0  then 1
								when TransactionType in (7) and sum(RevenueAmount) &gt; 0  then 2
								else Accountingtype
							end Accountingtype,		
						   RRCalcTypeTrigger,
						   RRPercentage,
						   RRDays
						   
						   from (
						  select distinct COA.COAAccountId, 
						   min(p.RevenueRecognitionRuleId) RevenueRecognitionRuleId,
						   min(p.rrcode) rrcode,		   
						   RR_DATA_REVENUE.RRCalcTypeWhere,
						   RR_DATA_REVENUE.RRCalcTypeMethod,	   
						   RR_DATA_REVENUE.COAAccountConfigId,
						   COA.COAAccountTypeId,
						   COA.Code COACODE,
						   RR_DATA_REVENUE.Transactionid as Transactionid,
						   RR_DATA_REVENUE.saleid as Saleid,
						   RR_DATA_REVENUE.Siteid as SiteID,
						   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
						   RR_DATA_REVENUE.Workstationid as Workstationid,
						   RR_DATA_REVENUE.UserGroupid as UserGroupID,
						   RR_DATA_REVENUE.UserId as userID,
						   @BatchDate as batchdate,
						   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
							    else DATA_Transaction.transactiondate
						   end as TransDate,
						   0 as Quantity,
						   0 as GrossAmount,
						   0 as NetAmount,
						   0 as price,
						   100 as percentage,
						   0 as test, 	
						   taxamount RevenueAmount,
						   Transactiontype,
							p.Accountingtype,					   		
						   RR_DATA_REVENUE.RRCalcTypeTrigger,
						   RR_DATA_REVENUE.RRPercentage,
						   RR_DATA_REVENUE.RRDays

					from RR_DATA_REVENUE
						INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
						INNER JOIN DATA_TransactionTax					on data_transactiontax.transactionid = data_transaction.transactionid
						INNER JOIN CNF_Tax								on cnf_tax.taxid = DATA_TransactionTax.taxid
						INNER JOIN coa_cnf_account coa					on coa.coaaccountid = cnf_tax.coaaccountid
							INNER JOIN (select saleid, transactionid, RevenueRecognitionRuleId, RR_DATA_Revenue.RRCode, RRCalcTypeWhere, Saleitemid, RR_DATA_Revenue.coaaccountid,
												RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount,  Accountingtype
												from RR_DATA_Revenue
												INNER JOIN COA_CNF_Account		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
												where COA_CNF_Account.coaAccountID = @TaxAccountID
												--and rr_data_Revenue.RRCalcTypeTrigger = @Trigger
												and RR_DATA_REVENUE.fcalcdate = @BatchDate
											)p    on p.transactionid = 	data_transactiontax.transactionid
					where RR_DATA_REVENUE.coaaccountid = 1
					and RR_DATA_REVENUE.fcalcdate = @BatchDate
					and TransactionType in (select transactionid
														from #TransactionIDs)
					AND DATA_Transaction.Transactionid not in (select distinct transactionid
																	from rr_Data_Revenue
																	where coaaccountid in (select distinct coaaccountid
																								from cnf_tax 
																							)
																	)
					group by COA.COAAccountId,    
						   RR_DATA_REVENUE.RRCalcTypeWhere,
						   RR_DATA_REVENUE.RRCalcTypeMethod,	   
						   RR_DATA_REVENUE.COAAccountConfigId,
						   COA.COAAccountTypeId,
						   COA.Code,
						   RR_DATA_REVENUE.Transactionid,
						   RR_DATA_REVENUE.saleid,
						   RR_DATA_REVENUE.Siteid,
						   RR_DATA_REVENUE.OperatingAreaId,
						   RR_DATA_REVENUE.Workstationid,
						   RR_DATA_REVENUE.UserGroupid,
						   RR_DATA_REVENUE.UserId,
						   DATA_Transaction.ftransactiondate, 
						   DATA_Transaction.transactiondate,
						   taxamount,
						   Transactiontype,
							p.Accountingtype,					   		
						   RR_DATA_REVENUE.RRCalcTypeTrigger,
						   RR_DATA_REVENUE.RRPercentage,
						   RR_DATA_REVENUE.RRDays

					)p
					where revenueamount &lt;&gt; 0
					group by COAAccountId, 	   
							RRCalcTypeWhere,
							RRCalcTypeMethod,	   
							COAAccountConfigId,
							COAAccountTypeId,
							COACODE,
							Transactionid,
							saleid,
							Siteid,
							OperatingAreaId,
							Workstationid,
							UserGroupid,
							UserId,
							TransDate,
							Accountingtype,		
							RRCalcTypeTrigger,
							RRPercentage,
							RRDays,
							price,
							percentage,
							test,
							batchdate,
							TransactionType


																									
		--	--------Reverse Tax Out
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])	
				      select  COAAccountId, 
									   RevenueRecognitionRuleId,
									   RRCode,		   
									   RRCalcTypeWhere,
									   RRCalcTypeMethod,	   
									   COAAccountConfigId,
									   COAAccountTypeId,
									   COAAccountCode,
									   Transactionid,
									   saleid,
									   siteid,
									   OperatingAreaid,
									   workstationid,
									   usergroupid,
									   userid,
									   batchdate,
									   TransDate,
									   Quantity,
									   grossamount,
									   netamount,
									   price,
									   percentage,
									   tax,
									   ABS(sum(RevenueAmount))  as RevenueAmount,
									    case when p.accountingtype = 1 then 2
											else 1
										end Accountingtype,	
									   RRCalcTypeTrigger,
									   RRPercentage,
									   RRDays
					  from (		    
				             select distinct 
								       p.COAAccountId, 
									   p.RevenueRecognitionRuleId,
									   p.RRCode,		   
									   p.RRCalcTypeWhere,
									   p.RRCalcTypeMethod,	   
									   p.COAAccountConfigId,
									   p.COAAccountTypeId,
									   p.COAAccountCode,
									   rr_data_Revenue.Transactionid Transactionid,
									   rr_data_Revenue.saleid saleid,
									   rr_data_Revenue.Siteid siteid,
									   rr_data_Revenue.OperatingAreaId OperatingAreaid,
									   rr_data_Revenue.Workstationid workstationid,
									   rr_data_Revenue.UserGroupid usergroupid,
									   rr_data_Revenue.UserId userid,
									   @BatchDate batchdate,
									   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
											else DATA_Transaction.transactiondate
									   end as TransDate,
									   rr_data_Revenue.Quantity Quantity,
									   rr_data_Revenue.GrossAmount grossamount,
									   rr_data_Revenue.NetAmount netamount,
									   0 price,
									   100 percentage,
									   0 tax,
									   rr_data_Revenue.RevenueAmount  as RevenueAmount,
									   data_transaction.transactiontype,
								       p.Accountingtype,		
									   p.RRCalcTypeTrigger,
									   p.RRPercentage,
									   p.RRDays
							FROM rr_data_Revenue   				        WITH (NOLOCK)
								   INNER JOIN (select saleid, transactionid, RevenueRecognitionRuleId, RR_DATA_Revenue.RRCode, RRCalcTypeWhere, Saleitemid, RR_DATA_Revenue.COAAccountId, 
													   RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount, COA_CNF_Account.COAAccountTypeId,  Accountingtype,
													   RR_DATA_Revenue.COAAccountCode
													  from RR_DATA_Revenue
														INNER JOIN COA_CNF_Account		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
													 where COA_CNF_Account.coaAccountID = @TaxAccountID
													)p								ON p.Transactionid = 	rr_data_Revenue.Transactionid
									INNER JOIN data_transaction						on data_transaction.transactionid = rr_data_revenue.transactionid

							where RR_DATA_REVENUE.fcalcdate = @BatchDate
							  and rr_data_Revenue.RRCalcTypeTrigger = @Trigger
							  and DATA_Transaction.TransactionType in (select transactionid
																		from #TransactionIDs)
							  and rr_data_Revenue.coaaccountid in (select distinct coaaccountid
						                                             from cnf_tax
																    where coaaccountid is not null
															      )
							)p
							group by   COAAccountId, 
									   RevenueRecognitionRuleId,
									   RRCode,		   
									   RRCalcTypeWhere,
									   RRCalcTypeMethod,	   
									   COAAccountConfigId,
									   COAAccountTypeId,
									   COAAccountCode,
									   Transactionid,
									   saleid,
									   siteid,
									   OperatingAreaid,
									   workstationid,
									   usergroupid,
									   userid,
									   batchdate,
									   TransDate,
									   Quantity,
									   grossamount,
									   netamount,
									   price,
									   percentage,
									   tax,
								       Accountingtype,		
									   RRCalcTypeTrigger,
									   RRPercentage,
									   RRDays,
									   TransactionType


		------		--Normal Transaction Break out the discounts
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])
				   select COAAccountId, 
						   RevenueRecognitionRuleId,
						   RRCode,		   
						   RRCalcTypeWhere,
						   RRCalcTypeMethod,	   
						   COAAccountConfigId,
						   COAAccountTypeId,
						   Code,
						   Transactionid,
						   Saleid,
						   SiteID,
						   OperatingAreaID,
						   Workstationid,
						   UserGroupID,
						   userID,
						   batchdate,
						   TransDate,
						   quantity,
						   grossamount,
						   netamount,
						   price,
						   percentage,
						   remaningValues, 	
						   RevenueAmount,
						   Accountingtype,		
						   RRCalcTypeTrigger,
						   RRPercentage,
						   RRDays
				   from (				    
						select distinct 
						   COA.COAAccountId, 
						   RR_DATA_REVENUE.RevenueRecognitionRuleId,
						   RR_DATA_REVENUE.RRCode,		   
						   RR_DATA_REVENUE.RRCalcTypeWhere,
						   RR_DATA_REVENUE.RRCalcTypeMethod,	   
						   RR_DATA_REVENUE.COAAccountConfigId,
						   COA.COAAccountTypeId,
						   COA.Code,
						   RR_DATA_REVENUE.Transactionid as Transactionid,
						   RR_DATA_REVENUE.saleid as Saleid,
						   RR_DATA_REVENUE.Siteid as SiteID,
						   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
						   RR_DATA_REVENUE.Workstationid as Workstationid,
						   RR_DATA_REVENUE.UserGroupid as UserGroupID,
						   RR_DATA_REVENUE.UserId as userID,
						   @BatchDate as batchdate,
						   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
							    else DATA_Transaction.transactiondate
						   end as TransDate,
						   0 as quantity,
						   0 as grossamount,
						   0 as netamount,
						   0 as price,
						   100 as percentage,
						   0 as remaningValues, 	
						   abs(DATA_SaleItemRule.discountamount)
							as RevenueAmount,
						   p.Accountingtype,		
						   RR_DATA_REVENUE.RRCalcTypeTrigger,
						   RR_DATA_REVENUE.RRPercentage,
						   RR_DATA_REVENUE.RRDays,
						   DATA_SaleItemRule.SaleItemRuleId


					from RR_DATA_REVENUE

						INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
						LEFT  JOIN DATA_Sale				            ON DATA_Sale.SaleID = data_transaction.SaleID
						LEFT  JOIN DATA_SaleItem			            ON DATA_SaleItem.saleitemid = RR_DATA_REVENUE.saleitemid
						LEFT JOIN DATA_SaleItemRule						ON data_saleitemrule.saleitemid = DATA_SaleItem.saleitemid	 
						LEFT JOIN CNF_PromotionItemRule					ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
						LEFT JOIN CNF_PromotionItem						ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
						LEFT JOIN CNF_Promotion							ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId	
						LEFT JOIN COA_CNF_Account	COA			        ON COA.coaaccountid = CNF_Promotion.coaaccountid
						
						
						INNER JOIN (select transactionid, RevenueRecognitionRuleId, RR_DATA_Revenue.RRCode, RRCalcTypeWhere, 
											RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount,  Accountingtype
											from RR_DATA_Revenue
											INNER JOIN COA_CNF_Account		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
											where COA_CNF_Account.coaAccountID = @DiscountAccountID
										)p    on p.transactionid = 	DATA_Transaction.transactionid



					where RR_DATA_REVENUE.coaaccountid = 1
					and DATA_Transaction.TransactionType in (select transactionid
																from #TransactionIDs)
					and RR_DATA_REVENUE.fcalcdate = @BatchDate
					AND DATA_Transaction.Transactionid not in (select distinct transactionid
																	from rr_Data_Revenue
																	where coaaccountid in (select distinct coaaccountid
																								from CNF_Promotion
																								where coaaccountid is not null 
																							)
																	)	
					)p
					where revenueamount &lt;&gt; 0	
					  and coaaccountid is not null													
																																								
		--		--Reverse out Discounts														
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])	
				   select COAAccountId, 
						   RevenueRecognitionRuleId,
						   RRCode,		   
						   RRCalcTypeWhere,
						   RRCalcTypeMethod,	   
						   COAAccountConfigId,
						   COAAccountTypeId,
						   COAAccountCode,
						   Transactionid,
						   Saleid,
						   SiteID,
						   OperatingAreaID,
						   Workstationid,
						   UserGroupID,
						   userID,
						   batchdate,
						   TransDate,
						   quantity,
						   grossamount,
						   netamount,
						   price,
						   percentage,
						   remaningValues, 	
						   sum(RevenueAmount),
						   Accountingtype,		
						   RRCalcTypeTrigger,
						   RRPercentage,
						   RRDays
				   from (		    
				select distinct 				           
				           p.RevenueRecognitionDataId,
                           p.COAAccountId, 
						   p.RevenueRecognitionRuleId,
						   p.RRCode,		   
						   p.RRCalcTypeWhere,
						   p.RRCalcTypeMethod,	   
						   p.COAAccountConfigId,
						   p.COAAccountTypeId,
						   p.COAAccountCode,
						   rr_data_Revenue.Transactionid,
						   rr_data_Revenue.saleid,
						   rr_data_Revenue.saleitemid,
						   rr_data_Revenue.Siteid,
						   rr_data_Revenue.OperatingAreaId,
						   rr_data_Revenue.Workstationid,
						   rr_data_Revenue.UserGroupid,
						   rr_data_Revenue.UserId,
						   @BatchDate batchdate,
						   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
							    else DATA_Transaction.transactiondate
						   end as TransDate,
							0 as quantity,
						   0 as grossamount,
						   0 as netamount,
						   0 as price,
						   100 as percentage,
						   0 as remaningValues,
						   rr_data_Revenue.RevenueAmount  as RevenueAmount,
						   case when p.accountingtype = 1 then 2
					        else 1
						   end Accountingtype,
						   p.RRCalcTypeTrigger,
						   p.RRPercentage,
						   p.RRDays

						  FROM rr_data_Revenue   				        WITH (NOLOCK)
								   INNER JOIN (select saleid, transactionid, RevenueRecognitionRuleId, RR_DATA_Revenue.RRCode, RRCalcTypeWhere, Saleitemid, RR_DATA_Revenue.COAAccountId, 
													   RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount, COA_CNF_Account.COAAccountTypeId,  Accountingtype,
													   RR_DATA_Revenue.COAAccountCode, rr_data_Revenue.RevenueRecognitionDataId
													  from RR_DATA_Revenue
														INNER JOIN COA_CNF_Account		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
													 where COA_CNF_Account.coaAccountID = @DiscountAccountID
													)p								ON p.saleid = 	rr_data_Revenue.saleid
								INNER JOIN data_transaction        on data_transaction.transactionid = rr_data_revenue.transactionid

						where  rr_data_Revenue.coaaccountid in (select distinct coaaccountid
						                                         from CNF_Promotion
															  )
						 and RR_DATA_REVENUE.fcalcdate = @BatchDate
						 and DATA_Transaction.TransactionType in (select transactionid
															from #TransactionIDs)
						)p		
						
						group by  COAAccountId, 
						   RevenueRecognitionRuleId,
						   RRCode,		   
						   RRCalcTypeWhere,
						   RRCalcTypeMethod,	   
						   COAAccountConfigId,
						   COAAccountTypeId,
						   COAAccountCode,
						   Transactionid,
						   Saleid,
						   SiteID,
						   OperatingAreaID,
						   Workstationid,
						   UserGroupID,
						   userID,
						   batchdate,
						   TransDate,
						   quantity,
						   grossamount,
						   netamount,
						   price,
						   percentage,
						   remaningValues, 	
						   Accountingtype,		
						   RRCalcTypeTrigger,
						   RRPercentage,
						   RRDays																																																																																			

		
		End
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_RR_RevenueData_OnTicketUsageTrigger]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_RR_RevenueData_OnTicketUsageTrigger
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE Procedure dbo.otn_sp_RR_RevenueData_OnTicketUsageTrigger
	@BatchDate Date,
	@RRTransDateType Integer
AS 
BEGIN
	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer
	Declare @TicketUsageTrigger Integer = 2	

	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1



	BEGIN

		--Normal TicketExpired No Remaining Value
			INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[SaleId]
				   ,[UsageID]
				   ,[Ticketid]
				   ,[MatrixCellid]
				   ,[MatrixCellCode]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				   ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]			
				   ,[RRDays]
				   ,[AttributeIDs])
				   select *
				   from (
				     select distinct coa_cnf_account.COAAccountId, 
							RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
							RR_CNF_RevenueRecognitionRule.code,		   
							RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
							RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
							COA_CNF_AccountConfig.COAAccountConfigId,
							coa_cnf_account.COAAccountTypeId,
							coa_cnf_account.Code as AccountCode,
							p.saleid as Saleid,
							p.Usageid,
							p.Ticketid as SaleitemID,
							p.Matrixcellid as Matrixcell,
							p.Code as MatrixCode,
							p.MatrixSheetId as MatrixSheetID,
							CASE When RR_CNF_RevenueRecognitionRule.rrCalcTypeWhere = 1 then p.AdmSiteid 
							else p.SaleSite
							end as SiteID,
							p.OperatingAreaId as OperatingAreaID,
							p.Workstationid as Workstationid,
							p.UserId as userID,
							@BatchDate as BatchDate,
							@BatchDate as TransDate,
							1 as Quantity,
							p.GrossAmount as GrossAmount,
							p.NetPrice as NetAmount,
							COA_CNF_AccountConfig.Price as ConfigPrice,
							COA_CNF_AccountConfig.Percentage as ConfigPercentage,
							COA_CNF_AccountConfig.RemainingValues,
							
							case when RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod &lt;&gt; 3 then															   
										Case when COA_CNF_AccountConfig.Price &gt; 0 then (COA_CNF_AccountConfig.Price) 
											 else case when (((p.NetPrice - ISNULL(TotalUsed, 0)) &gt; 0) and (p.NetPrice - ISNULL(TotalUsed, 0)) &gt;= (((p.NetPrice * RR_CNF_RevenueRecognitionRule.Percentage)/100 * COA_CNF_AccountConfig.Percentage)/100)) 
															then (((p.NetPrice * RR_CNF_RevenueRecognitionRule.Percentage)/100 * COA_CNF_AccountConfig.Percentage)/100)
													   else 0
												   end
										end 
								 else p.optionValue
							end as RevenueAmount,

							COA_CNF_AccountConfig.AccountingType,
							RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
							RR_CNF_RevenueRecognitionRule.Percentage,
							RR_CNF_RevenueRecognitionRule.Days,
							AttributeIDs
						from (			
								select  data_ticketusage.ticketid,
								        data_ticketusage.UsageID,
										1 as Quantity, 
										case when data_ticket.ProductTaxType = 1 then (rawPrice - data_ticket.taxes) 
										     else rawPrice
										end NetPrice,
										data_ticketusageoption.OptionValue,
										DATA_Ticket.Price as GrossAmount,
										CNF_MatrixCell.matrixcellid, 
										CNF_MatrixCell.code,
										CNF_MatrixCell.matrixsheetid, 
										DATA_Ticket.Siteid SaleSite,	  
										cnf_workstation.OperatingAreaId,
										cnf_workstation.workstationid,
										(select top 1 DATA_Sale.userid
											from data_saleitem
											INNER JOIN DATA_Sale		on data_sale.saleid = data_saleitem.saleid
											where data_saleitem.saleitemid = data_ticket.saleitemid
										) as userid,
										(select top 1 data_saleitem.saleid
											from data_saleitem
											where data_saleitem.saleitemid = data_ticket.saleitemid
										) as Saleid,
										(DATA_Ticket.RawPrice) as TicketPrice,
										CNF_Location.Siteid as AdmSiteid,
										CNF_AttributeSet.AttributeIDs,
										CNF_AttributeSet.AttributeSetId
								from data_ticketusage
								    LEFT  JOIN data_ticketusageoption								on data_ticketusageoption.usageid = data_ticketusage.usageid and data_ticketusageoption.optiontype = 7
									INNER JOIN DATA_Ticket											on DATA_Ticket.ticketid = data_ticketusage.ticketid
									INNER JOIN CNF_MatrixCell										on cnf_matrixcell.matrixcellid = data_ticket.matrixcellid
									INNER JOIN CNF_AttributeSet										on cnf_attributeset.AttributeSetId = CNF_MatrixCell.AttributeSetId
									INNER JOIN CNF_Workstation										on cnf_workstation.workstationid = data_ticket.WorkstationId
									INNER JOIN ADM_Gate												on ADM_Gate.gateid = data_ticketusage.gateid
									INNER JOIN CNF_Location											on CNF_Location.locationid = ADM_Gate.locationid
								where  data_ticketusage.validateResult &lt;=99
								and data_ticketusage.UsageType = 1							
								and cast(fusagedate as date) = @batchdate
						)p 
						INNER JOIN rr_cnf_product						ON ((RR_CNF_Product.matrixcellid = p.matrixcellid) or (RR_CNF_Product.matrixsheetid = p.matrixsheetid)
																				or (rr_cnf_product.Attributeid in (select Value
																										from dbo.split((select Attributeids
																														from CNF_AttributeSet
																														where CNF_AttributeSet.AttributeSetId = p.AttributeSetId), '.')
																										)
																					    
															))
						INNER JOIN RR_CNF_RevenueRecognitionRule			ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_cnf_product.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @TicketUsageTrigger
						INNER JOIN COA_CNF_AccountConfig					ON COA_CNF_AccountConfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
						INNER JOIN COA_CNF_Account							ON COA_CNF_Account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
						LEFT JOIN (select ticketid, AccountingType, sum(revenueamount) as TotalUsed
									from rr_data_revenue
									where rr_data_revenue.RRCalcTypeTrigger = @TicketUsageTrigger
									group by ticketid, AccountingType
									)rdata									ON rdata.ticketid = p.ticketid	and rdata.AccountingType = coa_cnf_accountconfig.AccountingType
						where p.TicketPrice &lt;&gt; 0
							and RR_CNF_RevenueRecognitionRule.Enabled = 1
							and RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod &lt;&gt; 3
							and coa_cnf_account.Enabled = 1
							and COA_CNF_AccountConfig.Enabled = 1
							and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
							and COA_CNF_AccountConfig.RemainingValues &lt;&gt; 1
							and (((RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere = 1) and ((coa_cnf_accountConfig.Siteid = p.AdmSiteid) or (coa_cnf_accountConfig.Siteid is null)))
							or (RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere = 2) and ((coa_cnf_accountConfig.Siteid = p.SaleSite) or (coa_cnf_accountConfig.Siteid is null))) 
						)k
						where RevenueAmount &lt;&gt; 0




		--Normal TicketExpired with Remaining Value
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[SaleId]
				   ,[UsageID]
				   ,[Ticketid]
				   ,[MatrixCellid]
				   ,[MatrixCellCode]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				   ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays]
				   ,[AttributeIDs])
				   select *
				   from (
						select   distinct	coa_cnf_account.COAAccountId, 
									RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
									RR_CNF_RevenueRecognitionRule.code,		   
									RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
									RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
									COA_CNF_AccountConfig.COAAccountConfigId,
									coa_cnf_account.COAAccountTypeId,
									coa_cnf_account.Code as AccountCode,
									p.saleid as Saleid,
									p.Usageid,
									p.Ticketid as SaleitemID,
									p.Matrixcellid as Matrixcell,
									p.Code as MatrixCode,
									p.MatrixSheetId as MatrixSheetID,
									CASE When RR_CNF_RevenueRecognitionRule.rrCalcTypeWhere = 1 then p.AdmSiteid 
									else p.SaleSite
									end as SiteID,
									p.OperatingAreaId as OperatingAreaID,
									p.Workstationid as Workstationid,
									p.UserId as userID,
									@BatchDate as BatchDate,
									@BatchDate as TransDate,
									1 as Quantity,
									p.GrossAmount as GrossAmount,
									p.NetPrice as NetAmount,
									COA_CNF_AccountConfig.Price as ConfigPrice,
									COA_CNF_AccountConfig.Percentage as ConfigPercentage,
									COA_CNF_AccountConfig.RemainingValues,
									case when RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod &lt;&gt; 3 then															   
										case when (((p.NetPrice - ISNULL(TotalUsed, 0)) &gt; 0) and ((
																					((p.NetPrice *  RR_CNF_RevenueRecognitionRule.Percentage)/100) -  
																						((
																						((p.NetPrice *  RR_CNF_RevenueRecognitionRule.Percentage)/100) * (select sum(percentage)
																																							from coa_cnf_accountconfig AC
																																							where AC.revenuerecognitionruleid = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																																							and ac.accountingtype = coa_cnf_accountconfig.accountingtype
																																							)
																						)/100)) &lt;= (p.NetPrice - ISNULL(TotalUsed, 0))))







														then 
														(((p.NetPrice *  RR_CNF_RevenueRecognitionRule.Percentage)/100) -  (((p.NetPrice *  RR_CNF_RevenueRecognitionRule.Percentage)/100) * (select sum(percentage)
																																from coa_cnf_accountconfig AC
																																where AC.revenuerecognitionruleid = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																																and ac.accountingtype = coa_cnf_accountconfig.accountingtype
																																))/100)
													else 0
												end 
									else p.optionValue
									end as RevenueAmount,
									COA_CNF_AccountConfig.AccountingType,
									RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
									RR_CNF_RevenueRecognitionRule.Percentage,
									RR_CNF_RevenueRecognitionRule.Days,
									AttributeIDs
								from (			
										select  data_ticketusage.ticketid,
										data_ticketusage.UsageID,
												1 as Quantity, 
												case when data_ticket.ProductTaxType = 1 then (rawPrice - data_ticket.taxes) 
													 else rawPrice
												end NetPrice,
												data_ticketusageoption.OptionValue,
												DATA_Ticket.Price as GrossAmount,
												CNF_MatrixCell.matrixcellid, 
												CNF_MatrixCell.code,
												CNF_MatrixCell.matrixsheetid, 
												DATA_Ticket.Siteid SaleSite,	  
												cnf_workstation.OperatingAreaId,
												cnf_workstation.workstationid,
												(select top 1 DATA_Sale.userid
													from data_saleitem
													INNER JOIN DATA_Sale		on data_sale.saleid = data_saleitem.saleid
													where data_saleitem.saleitemid = data_ticket.saleitemid
												) as userid,
												(select top 1 data_saleitem.saleid
													from data_saleitem
													where data_saleitem.saleitemid = data_ticket.saleitemid
												) as Saleid,
												(DATA_Ticket.RawPrice) as TicketPrice,
												CNF_Location.Siteid as AdmSiteid,
												CNF_AttributeSet.AttributeIDs,
												CNF_AttributeSet.AttributeSetId
										from data_ticketusage
										    LEFT  JOIN data_ticketusageoption								on data_ticketusageoption.usageid = data_ticketusage.usageid and data_ticketusageoption.optiontype = 7
											INNER JOIN DATA_Ticket											on DATA_Ticket.ticketid = data_ticketusage.ticketid
											INNER JOIN CNF_MatrixCell										on cnf_matrixcell.matrixcellid = data_ticket.matrixcellid
											INNER JOIN CNF_AttributeSet										on cnf_attributeset.AttributeSetId = CNF_MatrixCell.AttributeSetId
											INNER JOIN CNF_Workstation										on cnf_workstation.workstationid = data_ticket.WorkstationId
											INNER JOIN ADM_Gate												on ADM_Gate.gateid = data_ticketusage.gateid
											INNER JOIN CNF_Location											on CNF_Location.locationid = ADM_Gate.locationid
										where data_ticketusage.validateResult &lt;=99
										and data_ticketusage.UsageType = 1
										and cast(fusagedate as date) = @batchdate
								)p 
								INNER JOIN rr_cnf_product						ON ((RR_CNF_Product.matrixcellid = p.matrixcellid) or (RR_CNF_Product.matrixsheetid = p.matrixsheetid)
																				or (rr_cnf_product.Attributeid in (select Value
																										from dbo.split((select Attributeids
																														from CNF_AttributeSet
																														where CNF_AttributeSet.AttributeSetId = p.AttributeSetId), '.')
																										)
																					    
															))
								INNER JOIN RR_CNF_RevenueRecognitionRule			ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_cnf_product.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @TicketUsageTrigger
								INNER JOIN COA_CNF_AccountConfig					ON COA_CNF_AccountConfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
								INNER JOIN COA_CNF_Account							ON COA_CNF_Account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
								LEFT JOIN (select ticketid, accountingtype, sum(revenueamount) as TotalUsed
											from rr_data_revenue
											where rr_data_revenue.RRCalcTypeTrigger = @TicketUsageTrigger
											group by ticketid, accountingtype
											)rdata									ON rdata.ticketid = p.ticketid	and rdata.accountingtype = COA_CNF_AccountConfig.accountingtype
								where p.TicketPrice &lt;&gt; 0
									and RR_CNF_RevenueRecognitionRule.Enabled = 1
									and RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod &lt;&gt; 3
									and coa_cnf_account.Enabled = 1
									and COA_CNF_AccountConfig.Enabled = 1
									and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
									and COA_CNF_AccountConfig.RemainingValues = 1
									and (((RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere = 1) and ((coa_cnf_accountConfig.Siteid = p.AdmSiteid) or (coa_cnf_accountConfig.Siteid is null)))
									or (RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere = 2) and ((coa_cnf_accountConfig.Siteid = p.SaleSite) or (coa_cnf_accountConfig.Siteid is null))) 
						)k
						where RevenueAmount &lt;&gt; 0

	end

END
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_RR_RevenueData_OnTicketExpiredTrigger]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_RR_RevenueData_OnTicketExpiredTrigger
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE Procedure dbo.otn_sp_RR_RevenueData_OnTicketExpiredTrigger
	@BatchDate Date,
	@RRTransDateType Integer
AS 
BEGIN

	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer
	Declare @TicketExpiredTrigger Integer = 3	

	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1

	BEGIN
		--Normal TicketExpired No Remaining Value
			INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[Ticketid]
				   ,[MatrixCellid]
				   ,[MatrixCellCode]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				   ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays]
				   ,[AttributeIDs])
				   select *
				   from(
				   select COA_CNF_AccountConfig.COAAccountId, 
												   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
												   RR_CNF_RevenueRecognitionRule.code,		   
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
												   COA_CNF_AccountConfig.COAAccountConfigId,
												   coa_cnf_account.COAAccountTypeId,
												   coa_cnf_account.Code as AccountCode,
												   p.Ticketid as Ticketid,
												   p.Matrixcellid as Matrixcell,
												   p.Code as MatrixCode,
												   p.MatrixSheetId as MatrixSheetID,
												   p.Siteid as SiteID,
												   @BatchDate as BatchDate,
												   p.ActiveTo,
												   1 as Quantity,
												   0 as GrossAmount,
												   0 as NetAmount,
												   COA_CNF_AccountConfig.Price as ConfigPrice,
												   COA_CNF_AccountConfig.Percentage as ConfigPercentage,
												   COA_CNF_AccountConfig.RemainingValues,									   
							case when p.netprice &gt; 0 then
								case when (select ISNULL(sum(round(RevenueAmount/rr_data_revenue.Quantity, 2)), 0)
											from rr_data_revenue 
											where rr_data_revenue.accountingtype = 1
											and ((rr_data_revenue.ticketid = p.TicketID)
													or (rr_data_revenue.saleitemid in (select saleitemid
																						from data_saleitem2Ticket
																					where data_saleitem2ticket.ticketid = p.TicketID)
																					))
											and rr_data_revenue.coaaccountid in (select coa_cnf_accountconfig.COAAccountId
																			from coa_cnf_accountconfig
																			where coa_cnf_accountconfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																				and coa_cnf_accountconfig.accountingtype = 1)) &gt; 0 
										and (p.NetPrice - (select ISNULL(sum(round(RevenueAmount/rr_data_revenue.Quantity, 2)), 0)
															from rr_data_revenue 
															where rr_data_revenue.accountingtype = 1
															and ((rr_data_revenue.ticketid = p.TicketID)
																	or (rr_data_revenue.saleitemid in (select saleitemid
																										from data_saleitem2Ticket
																									where data_saleitem2ticket.ticketid = p.TicketID)
																									))
															and rr_data_revenue.coaaccountid in (select coa_cnf_accountconfig.COAAccountId
																							from coa_cnf_accountconfig
																							where coa_cnf_accountconfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																								and coa_cnf_accountconfig.accountingtype = 1)))	&gt; 0
										THEN Case when COA_CNF_AccountConfig.Price &gt; 0 then (COA_CNF_AccountConfig.Price)
												  else (p.NetPrice - (select ISNULL(sum(round(RevenueAmount/rr_data_revenue.Quantity, 2)), 0)
																									from rr_data_revenue 
																									where rr_data_revenue.accountingtype = 1
																									and ((rr_data_revenue.ticketid = p.TicketID)
																											or (rr_data_revenue.saleitemid in (select saleitemid
																																				from data_saleitem2Ticket
																																			where data_saleitem2ticket.ticketid = p.TicketID)
																																			))
																									and rr_data_revenue.coaaccountid in (select coa_cnf_accountconfig.COAAccountId
																																	from coa_cnf_accountconfig
																																	where coa_cnf_accountconfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																																		and coa_cnf_accountconfig.accountingtype = 1))) * COA_CNF_AccountConfig.Percentage/100

												end
										when (select ISNULL(sum(round(RevenueAmount/rr_data_revenue.Quantity, 2)), 0)
																	from rr_data_revenue 
																	where rr_data_revenue.accountingtype = 1
																	and ((rr_data_revenue.ticketid = p.TicketID)
																			or (rr_data_revenue.saleitemid in (select saleitemid
																												from data_saleitem2Ticket
																											where data_saleitem2ticket.ticketid = p.TicketID)
																											))
																	and rr_data_revenue.coaaccountid in (select coa_cnf_accountconfig.COAAccountId
																									from coa_cnf_accountconfig
																									where coa_cnf_accountconfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																										and coa_cnf_accountconfig.accountingtype = 1)) &gt; 0 
											and (p.NetPrice - (select ISNULL(sum(round(RevenueAmount/rr_data_revenue.Quantity, 2)), 0)
															from rr_data_revenue 
															where rr_data_revenue.accountingtype = 1
															and ((rr_data_revenue.ticketid = p.TicketID)
																	or (rr_data_revenue.saleitemid in (select saleitemid
																										from data_saleitem2Ticket
																									where data_saleitem2ticket.ticketid = p.TicketID)
																									))
															and rr_data_revenue.coaaccountid in (select coa_cnf_accountconfig.COAAccountId
																							from coa_cnf_accountconfig
																							where coa_cnf_accountconfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																								and coa_cnf_accountconfig.accountingtype = 1)))	= 0
										   THEN Case when COA_CNF_AccountConfig.Price &gt; 0 then (COA_CNF_AccountConfig.Price)
													 else NetPrice - (select ISNULL(sum(round(RevenueAmount/rr_data_revenue.Quantity, 2)), 0)
																	from rr_data_revenue 
																	where rr_data_revenue.accountingtype = 2
																	and ((rr_data_revenue.ticketid = p.TicketID)
																			or (rr_data_revenue.saleitemid in (select saleitemid
																												from data_saleitem2Ticket
																											where data_saleitem2ticket.ticketid = p.TicketID)
																											))
																	and rr_data_revenue.coaaccountid in (select coa_cnf_accountconfig.COAAccountId
																									from coa_cnf_accountconfig
																									where coa_cnf_accountconfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																										and coa_cnf_accountconfig.accountingtype = 1)) * COA_CNF_AccountConfig.Percentage/100
											END

										when (select ISNULL(sum(round(RevenueAmount/rr_data_revenue.Quantity, 2)), 0)
																	from rr_data_revenue 
																	where rr_data_revenue.accountingtype = 1
																	and ((rr_data_revenue.ticketid = p.TicketID)
																			or (rr_data_revenue.saleitemid in (select saleitemid
																												from data_saleitem2Ticket
																											where data_saleitem2ticket.ticketid = p.TicketID)
																											))
																	and rr_data_revenue.coaaccountid in (select coa_cnf_accountconfig.COAAccountId
																									from coa_cnf_accountconfig
																									where coa_cnf_accountconfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																										and coa_cnf_accountconfig.accountingtype = 1)) = 0 
										 and (select ISNULL(sum(round(RevenueAmount/rr_data_revenue.Quantity, 2)), 0)
																	from rr_data_revenue 
																	where rr_data_revenue.accountingtype = 2
																	and ((rr_data_revenue.ticketid = p.TicketID)
																			or (rr_data_revenue.saleitemid in (select saleitemid
																												from data_saleitem2Ticket
																											where data_saleitem2ticket.ticketid = p.TicketID)
																											))
																	and rr_data_revenue.coaaccountid in (select coa_cnf_accountconfig.COAAccountId
																									from coa_cnf_accountconfig
																									where coa_cnf_accountconfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																										and coa_cnf_accountconfig.accountingtype = 1)) &gt; 0
										   THEN Case when COA_CNF_AccountConfig.Price &gt; 0 then (COA_CNF_AccountConfig.Price)
													 else (select ISNULL(sum(round(RevenueAmount/rr_data_revenue.Quantity, 2)), 0)
																	from rr_data_revenue 
																	where rr_data_revenue.accountingtype = 2
																	and ((rr_data_revenue.ticketid = p.TicketID)
																			or (rr_data_revenue.saleitemid in (select saleitemid
																												from data_saleitem2Ticket
																											where data_saleitem2ticket.ticketid = p.TicketID)
																											))
																	and rr_data_revenue.coaaccountid in (select coa_cnf_accountconfig.COAAccountId
																									from coa_cnf_accountconfig
																									where coa_cnf_accountconfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																										and coa_cnf_accountconfig.accountingtype = 1)) * COA_CNF_AccountConfig.Percentage/100
											END
											else 0							
											end 
											else Case when COA_CNF_AccountConfig.Price &gt; 0 then (COA_CNF_AccountConfig.Price)											
											       else (select ABS(ISNULL(sum(data_ledger.entryamount), 0))
														from data_ticket DT
															INNER JOIN data_ledger					on data_ledger.ticketid = DT.ticketid
														where DT.ticketid = p.TicketID
														group by data_ledger.ticketid) * COA_CNF_AccountConfig.Percentage/100
													END
											end as revenueamount,
									
							COA_CNF_AccountConfig.AccountingType,
							RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
												   RR_CNF_RevenueRecognitionRule.Percentage,
												   RR_CNF_RevenueRecognitionRule.Days,
												   p.AttributeIDs

				  from RR_CNF_RevenueRecognitionRule
					   INNER JOIN RR_CNF_Product						ON RR_CNF_Product.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
					   INNER JOIN COA_CNF_AccountConfig					ON COA_CNF_AccountConfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId 
					   INNER JOIN COA_CNF_Account						on coa_cnf_account.COAAccountId = COA_CNF_AccountConfig.coaaccountid and  COA_CNF_Account.enabled = 1
					   INNER JOIN (select	distinct CNF_MatrixCell.matrixcellid, DATA_Ticket.price, DATA_Ticket.rawprice, DATA_Ticket.ticketid, CNF_MatrixCell.AttributeSetId, AttributeIDs,
					                                 CNF_MatrixCell.Code, MatrixSheetId, DATA_Ticket.siteid, DAta_Ticket.ActiveTo, (data_ticket.price - data_ticket.taxes) NetPrice
														from DATA_Ticket
															INNER JOIN CNF_MatrixCell					on cnf_matrixcell.matrixcellid = data_ticket.matrixcellid
															INNER JOIN CNF_AttributeSet					on cnf_attributeset.AttributeSetId = CNF_MatrixCell.AttributeSetId
										
														where VoidType = 0
															and cast(data_ticket.activeto as date) = @batchdate
									)p  on						((p.matrixcellid   = rr_cnf_product.matrixcellid) or(p.matrixsheetid = rr_cnf_product.matrixsheetid)
																	or (rr_cnf_product.Attributeid in (select Value
																										from dbo.split((select Attributeids
																														from CNF_AttributeSet
																														where CNF_AttributeSet.AttributeSetId = p.AttributeSetId), '.')
																										)
																					    
															))
				where RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @TicketExpiredTrigger
				  and rr_cnf_revenuerecognitionRule.Enabled = 1
				  and COA_CNF_AccountConfig.Enabled = 1
				  and COA_CNF_AccountConfig.RemainingValues &lt;&gt; 1
				)p
				where RevenueAmount &lt;&gt; 0 



		--Normal TicketExpired with Remaining Value
			INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[Ticketid]
				   ,[MatrixCellid]
				   ,[MatrixCellCode]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				   ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays]
				   ,[AttributeIDs])
				   select *
				   from(
				   select COA_CNF_AccountConfig.COAAccountId, 
												   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
												   RR_CNF_RevenueRecognitionRule.code,		   
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
												   COA_CNF_AccountConfig.COAAccountConfigId,
												   coa_cnf_account.COAAccountTypeId,
												   coa_cnf_account.Code as AccountCode,
												   p.Ticketid as Ticketid,
												   p.Matrixcellid as Matrixcell,
												   p.Code as MatrixCode,
												   p.MatrixSheetId as MatrixSheetID,
												   p.Siteid as SiteID,
												   @BatchDate as BatchDate,
												   p.ActiveTo,
												   1 as Quantity,
												   0 as GrossAmount,
												   0 as NetAmount,
												   COA_CNF_AccountConfig.Price as ConfigPrice,
												   COA_CNF_AccountConfig.Percentage as ConfigPercentage,
												   COA_CNF_AccountConfig.RemainingValues,	
												   	case when p.netprice &gt; 0 then								   
												case when (select ISNULL(sum(round(RevenueAmount/rr_data_revenue.Quantity, 2)), 0)
													from rr_data_revenue 
													where rr_data_revenue.accountingtype = 1
													and ((rr_data_revenue.ticketid = p.TicketID)
															or (rr_data_revenue.saleitemid in (select saleitemid
																								from data_saleitem2Ticket
																							where data_saleitem2ticket.ticketid = p.TicketID)
																							))
													and rr_data_revenue.coaaccountid in (select coa_cnf_accountconfig.COAAccountId
																					from coa_cnf_accountconfig
																					where coa_cnf_accountconfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																						and coa_cnf_accountconfig.accountingtype = 1)) &gt; 0 
												and (p.NetPrice - (select ISNULL(sum(round(RevenueAmount/rr_data_revenue.Quantity, 2)), 0)
																	from rr_data_revenue 
																	where rr_data_revenue.accountingtype = 1
																	and ((rr_data_revenue.ticketid = p.TicketID)
																			or (rr_data_revenue.saleitemid in (select saleitemid
																												from data_saleitem2Ticket
																											where data_saleitem2ticket.ticketid = p.TicketID)
																											))
																	and rr_data_revenue.coaaccountid in (select coa_cnf_accountconfig.COAAccountId
																									from coa_cnf_accountconfig
																									where coa_cnf_accountconfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																										and coa_cnf_accountconfig.accountingtype = 1)))	&gt; 0
												THEN  (p.NetPrice - (select ISNULL(sum(round(RevenueAmount/rr_data_revenue.Quantity, 2)), 0)
																											from rr_data_revenue 
																											where rr_data_revenue.accountingtype = 1
																											and ((rr_data_revenue.ticketid = p.TicketID)
																													or (rr_data_revenue.saleitemid in (select saleitemid
																																						from data_saleitem2Ticket
																																					where data_saleitem2ticket.ticketid = p.TicketID)
																																					))
																											and rr_data_revenue.coaaccountid in (select coa_cnf_accountconfig.COAAccountId
																																			from coa_cnf_accountconfig
																																			where coa_cnf_accountconfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																																				and coa_cnf_accountconfig.accountingtype = 1)))
																																																								 
												when (select ISNULL(sum(round(RevenueAmount/rr_data_revenue.Quantity, 2)), 0)
																			from rr_data_revenue 
																			where rr_data_revenue.accountingtype = 1
																			and ((rr_data_revenue.ticketid = p.TicketID)
																					or (rr_data_revenue.saleitemid in (select saleitemid
																														from data_saleitem2Ticket
																													where data_saleitem2ticket.ticketid = p.TicketID)
																													))
																			and rr_data_revenue.coaaccountid in (select coa_cnf_accountconfig.COAAccountId
																											from coa_cnf_accountconfig
																											where coa_cnf_accountconfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																												and coa_cnf_accountconfig.accountingtype = 1)) &gt; 0 
													and (p.NetPrice - (select ISNULL(sum(round(RevenueAmount/rr_data_revenue.Quantity, 2)), 0)
																	from rr_data_revenue 
																	where rr_data_revenue.accountingtype = 1
																	and ((rr_data_revenue.ticketid = p.TicketID)
																			or (rr_data_revenue.saleitemid in (select saleitemid
																												from data_saleitem2Ticket
																											where data_saleitem2ticket.ticketid = p.TicketID)
																											))
																	and rr_data_revenue.coaaccountid in (select coa_cnf_accountconfig.COAAccountId
																									from coa_cnf_accountconfig
																									where coa_cnf_accountconfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																										and coa_cnf_accountconfig.accountingtype = 1)))	= 0
												   THEN Case when COA_CNF_AccountConfig.Price &gt; 0 then (COA_CNF_AccountConfig.Price)
															 else p.netprice - 	(ISNULL((select sum(RevenueAmount)
																					from rr_data_revenue 
																					where RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																					and ((rr_data_revenue.ticketid = p.Ticketid)
																									or (rr_data_revenue.saleitemid in (select saleitemid
																																		from data_saleitem2Ticket
																																	where data_saleitem2ticket.ticketid = p.Ticketid)
																																	))
																					and rr_data_revenue.accountingtype = COA_CNF_AccountConfig.accountingtype
																					and rr_data_revenue.coaaccountid in (select CC.COAAccountId
																															from coa_cnf_accountconfig CC
																															where CC.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																																and CC.accountingtype = coa_cnf_accountconfig.Accountingtype)
																				), 0))
													END

												when (select ISNULL(sum(round(RevenueAmount/rr_data_revenue.Quantity, 2)), 0)
																			from rr_data_revenue 
																			where rr_data_revenue.accountingtype = 1
																			and ((rr_data_revenue.ticketid = p.TicketID)
																					or (rr_data_revenue.saleitemid in (select saleitemid
																														from data_saleitem2Ticket
																													where data_saleitem2ticket.ticketid = p.TicketID)
																													))
																			and rr_data_revenue.coaaccountid in (select coa_cnf_accountconfig.COAAccountId
																											from coa_cnf_accountconfig
																											where coa_cnf_accountconfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																												and coa_cnf_accountconfig.accountingtype = 1)) = 0 
												 and (select ISNULL(sum(round(RevenueAmount/rr_data_revenue.Quantity, 2)), 0)
																			from rr_data_revenue 
																			where rr_data_revenue.accountingtype = 2
																			and ((rr_data_revenue.ticketid = p.TicketID)
																					or (rr_data_revenue.saleitemid in (select saleitemid
																														from data_saleitem2Ticket
																													where data_saleitem2ticket.ticketid = p.TicketID)
																													))
																			and rr_data_revenue.coaaccountid in (select coa_cnf_accountconfig.COAAccountId
																											from coa_cnf_accountconfig
																											where coa_cnf_accountconfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																												and coa_cnf_accountconfig.accountingtype = 1)) &gt; 0
												   THEN p.netprice - 	(ISNULL((select sum(RevenueAmount)
																					from rr_data_revenue 
																					where RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																					and ((rr_data_revenue.ticketid = p.Ticketid)
																									or (rr_data_revenue.saleitemid in (select saleitemid
																																		from data_saleitem2Ticket
																																	where data_saleitem2ticket.ticketid = p.Ticketid)
																																	))
																					and rr_data_revenue.accountingtype = COA_CNF_AccountConfig.accountingtype
																					and rr_data_revenue.coaaccountid in (select CC.COAAccountId
																															from coa_cnf_accountconfig CC
																															where CC.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																																and CC.accountingtype = coa_cnf_accountconfig.Accountingtype)
																				), 0))
											else 0							
											end 
											else  (select ABS(ISNULL(sum(data_ledger.entryamount), 0))
														from data_ticket DT
															INNER JOIN data_ledger					on data_ledger.ticketid = DT.ticketid
														where DT.ticketid = p.TicketID
														group by data_ledger.ticketid) - 
														(ISNULL((select sum(RevenueAmount)
																					from rr_data_revenue 
																					where RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																					and ((rr_data_revenue.ticketid = p.Ticketid)
																									or (rr_data_revenue.saleitemid in (select saleitemid
																																		from data_saleitem2Ticket
																																	where data_saleitem2ticket.ticketid = p.Ticketid)
																																	))
																					and rr_data_revenue.accountingtype = COA_CNF_AccountConfig.accountingtype
																					and rr_data_revenue.coaaccountid in (select CC.COAAccountId
																															from coa_cnf_accountconfig CC
																															where CC.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																																and CC.accountingtype = coa_cnf_accountconfig.Accountingtype)
																				), 0))
													
											end as revenueamount,
												   COA_CNF_AccountConfig.AccountingType,
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
												   RR_CNF_RevenueRecognitionRule.Percentage,
												   RR_CNF_RevenueRecognitionRule.Days,
												   p.AttributeIDs

				  from RR_CNF_RevenueRecognitionRule
					   INNER JOIN RR_CNF_Product						ON RR_CNF_Product.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
					   INNER JOIN COA_CNF_AccountConfig					ON COA_CNF_AccountConfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId 
					   INNER JOIN COA_CNF_Account						on coa_cnf_account.COAAccountId = COA_CNF_AccountConfig.coaaccountid and  COA_CNF_Account.enabled = 1
					   INNER JOIN (select	distinct CNF_MatrixCell.matrixcellid, DATA_Ticket.price, DATA_Ticket.rawprice, DATA_Ticket.ticketid, CNF_MatrixCell.AttributeSetId, AttributeIDs,
					                                 CNF_MatrixCell.Code, MatrixSheetId, DATA_Ticket.siteid, DAta_Ticket.ActiveTo, (data_ticket.price - data_ticket.taxes) NetPrice
														from DATA_Ticket
															INNER JOIN CNF_MatrixCell					on cnf_matrixcell.matrixcellid = data_ticket.matrixcellid
															INNER JOIN CNF_AttributeSet					on cnf_attributeset.AttributeSetId = CNF_MatrixCell.AttributeSetId
										
														where VoidType = 0
															and data_ticket.activeto = @batchdate
									)p  on						((p.matrixcellid   = rr_cnf_product.matrixcellid) or(p.matrixsheetid = rr_cnf_product.matrixsheetid)
																	or (rr_cnf_product.Attributeid in (select Value
																										from dbo.split((select Attributeids
																														from CNF_AttributeSet
																														where CNF_AttributeSet.AttributeSetId = p.AttributeSetId), '.')
																										)
																					    
															))

				where RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @TicketExpiredTrigger
				  and rr_cnf_revenuerecognitionRule.Enabled = 1
				  and COA_CNF_AccountConfig.Enabled = 1
				  and COA_CNF_AccountConfig.RemainingValues = 1
				)p
				where RevenueAmount &lt;&gt; 0 


	end
END
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_RR_RevenueData_batchJob]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_RR_RevenueData_batchJob
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE Procedure dbo.otn_sp_RR_RevenueData_batchJob	 
	@FromDate Date,
	@ToDate Date
AS 
BEGIN

	delete from rr_data_revenue
	where fcalcdate between @FromDate and @ToDate

	Declare @BatchDate Date
	Declare @RRTransDateType Integer

	Declare @SuspendRRRId Integer
	Declare @SuspendCOAAccountId Integer
	Declare @SuspendRRRCode varchar(10)
	Declare @SuspendRRCalcTypeTrigger Integer
	Declare @SuspendRRCalcTypeWhere Integer
	Declare @SuspendRRCalcTypeMethod Integer
	Declare @SuspendCOAAccountConfigId Integer
	Declare @SuspendCOAAccountTypeId Integer
	Declare @SuspendCOAAccountCode varchar(10)
	Declare @SuspendPercentage float
	Declare @SuspendDays Integer
	Declare @SuspendPrice float
	Declare @SuspendCOAAccount_Percentage Float
	Declare @SuspendRemainingValues Integer
	Declare @SuspendRRCOAAccountingType Integer
	Declare @SuspendAccountingType Integer

	Declare @PaymentRRRId Integer
	Declare @PaymentCOAAccountId Integer
	Declare @PaymentRRRCode varchar(10)
	Declare @PaymentRRCalcTypeTrigger Integer
	Declare @PaymentRRCalcTypeWhere Integer
	Declare @PaymentRRCalcTypeMethod Integer
	Declare @PaymentCOAAccountConfigId Integer
	Declare @PaymentCOAAccountTypeId Integer
	Declare @PaymentCOAAccountCode varchar(10)
	Declare @PaymentPercentage float
	Declare @PaymentDays Integer
	Declare @PaymentPrice float
	Declare @PaymentCOAAccount_Percentage Float
	Declare @PaymentRemainingValues Integer
	Declare @PaymentRRCOAAccountingType Integer
	Declare @PaymentAccountingType Integer


	Declare @TaxRRRId Integer
	Declare @TaxCOAAccountId Integer
	Declare @TaxRRRCode varchar(10)
	Declare @TaxRRCalcTypeTrigger Integer
	Declare @TaxRRCalcTypeWhere Integer
	Declare @TaxRRCalcTypeMethod Integer
	Declare @TaxCOAAccountConfigId Integer
	Declare @TaxCOAAccountTypeId Integer
	Declare @TaxCOAAccountCode varchar(10)
	Declare @TaxPercentage float
	Declare @TaxDays Integer
	Declare @TaxPrice float
	Declare @TaxCOAAccount_Percentage Float
	Declare @TaxRemainingValues Integer
	Declare @TaxRRCOAAccountingType Integer
	Declare @TaxAccountingType Integer


	Declare @DiscountRRRId Integer
	Declare @DiscountCOAAccountId Integer
	Declare @DiscountRRRCode varchar(10)
	Declare @DiscountRRCalcTypeTrigger Integer
	Declare @DiscountRRCalcTypeWhere Integer
	Declare @DiscountRRCalcTypeMethod Integer
	Declare @DiscountCOAAccountConfigId Integer
	Declare @DiscountCOAAccountTypeId Integer
	Declare @DiscountCOAAccountCode varchar(10)
	Declare @DiscountPercentage float
	Declare @DiscountDays Integer
	Declare @DiscountPrice float
	Declare @DiscountCOAAccount_Percentage Float
	Declare @DiscountRemainingValues Integer
	Declare @DiscountRRCOAAccountingType Integer
	Declare @DiscountAccountingType Integer

	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer

	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1


	select @RRTransDateType = RRTransDateType
      from cnf_system

--Begin Move Transactions to Suspend Account
	select TOP 1 @SuspendRRRId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
			@SuspendRRRCode = RR_CNF_RevenueRecognitionRule.code,
			@SuspendRRCalcTypeTrigger = RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
			@SuspendRRCalcTypeWhere = RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
			@SuspendRRCalcTypeMethod = RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
			@SuspendCOAAccountConfigId = COA_CNF_AccountConfig.COAAccountConfigId,
			@SuspendCOAAccountTypeId = COA_CNF_AccountType.COAAccountTypeId,
			@SuspendCOAAccountId = coa_cnf_account.COAAccountId,
			@SuspendPercentage = RR_CNF_RevenueRecognitionRule.Percentage,
			@SuspendDays = RR_CNF_RevenueRecognitionRule.Days,
			@SuspendPrice = COA_CNF_AccountConfig.Price,
			@SuspendCOAAccount_Percentage = COA_CNF_AccountConfig.Percentage,
			@SuspendRemainingValues = COA_CNF_AccountConfig.RemainingValues,
			@SuspendCOAAccountCode = coa_cnf_account.Code,
			@SuspendRRCOAAccountingType = COA_CNF_AccountConfig.AccountingType
	from coa_cnf_account
		INNER JOIN COA_CNF_AccountType				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
		INNER JOIN COA_CNF_AccountConfig			on COA_CNF_AccountConfig.COAAccountId = coa_cnf_account.COAAccountId
		INNER JOIN RR_CNF_RevenueRecognitionRule	on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId
	where coa_cnf_account.COAAccountID = @SuspendID
	 order by RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId

	select TOP 1 @PaymentRRRId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
			@PaymentRRRCode = RR_CNF_RevenueRecognitionRule.code,
			@PaymentRRCalcTypeTrigger = RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
			@PaymentRRCalcTypeWhere = RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
			@PaymentRRCalcTypeMethod = RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
			@PaymentCOAAccountConfigId = COA_CNF_AccountConfig.COAAccountConfigId,
			@PaymentCOAAccountTypeId = COA_CNF_AccountType.COAAccountTypeId,
			@PaymentCOAAccountId = coa_cnf_account.COAAccountId,
			@PaymentPercentage = RR_CNF_RevenueRecognitionRule.Percentage,
			@PaymentDays = RR_CNF_RevenueRecognitionRule.Days,
			@PaymentPrice = COA_CNF_AccountConfig.Price,
			@PaymentCOAAccount_Percentage = COA_CNF_AccountConfig.Percentage,
			@PaymentRemainingValues = COA_CNF_AccountConfig.RemainingValues,
			@PaymentCOAAccountCode = coa_cnf_account.Code,
			@PaymentRRCOAAccountingType = COA_CNF_AccountConfig.AccountingType
	from coa_cnf_account
		INNER JOIN COA_CNF_AccountType				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
		INNER JOIN COA_CNF_AccountConfig			on COA_CNF_AccountConfig.COAAccountId = coa_cnf_account.COAAccountId
		INNER JOIN RR_CNF_RevenueRecognitionRule	on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId
	where coa_cnf_account.COAAccountID = @ACCPaymentMethod
	 order by RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId

	select TOP 1 @TaxRRRId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
			@TaxRRRCode = RR_CNF_RevenueRecognitionRule.code,
			@TaxRRCalcTypeTrigger = RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
			@TaxRRCalcTypeWhere = RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
			@TaxRRCalcTypeMethod = RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
			@TaxCOAAccountConfigId = COA_CNF_AccountConfig.COAAccountConfigId,
			@TaxCOAAccountTypeId = COA_CNF_AccountType.COAAccountTypeId,
			@TaxCOAAccountId = coa_cnf_account.COAAccountId,
			@TaxPercentage = RR_CNF_RevenueRecognitionRule.Percentage,
			@TaxDays = RR_CNF_RevenueRecognitionRule.Days,
			@TaxPrice = COA_CNF_AccountConfig.Price,
			@TaxCOAAccount_Percentage = COA_CNF_AccountConfig.Percentage,
			@TaxRemainingValues = COA_CNF_AccountConfig.RemainingValues,
			@TaxCOAAccountCode = coa_cnf_account.Code,
			@TaxRRCOAAccountingType = COA_CNF_AccountConfig.AccountingType
	from coa_cnf_account
		INNER JOIN COA_CNF_AccountType				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
		INNER JOIN COA_CNF_AccountConfig			on COA_CNF_AccountConfig.COAAccountId = coa_cnf_account.COAAccountId
		INNER JOIN RR_CNF_RevenueRecognitionRule	on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId
	where coa_cnf_account.COAAccountID = @TaxAccountID
	 order by RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId

	select TOP 1 @DiscountRRRId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
			@DiscountRRRCode = RR_CNF_RevenueRecognitionRule.code,
			@DiscountRRCalcTypeTrigger = RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
			@DiscountRRCalcTypeWhere = RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
			@DiscountRRCalcTypeMethod = RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
			@DiscountCOAAccountConfigId = COA_CNF_AccountConfig.COAAccountConfigId,
			@DiscountCOAAccountTypeId = COA_CNF_AccountType.COAAccountTypeId,
			@DiscountCOAAccountId = coa_cnf_account.COAAccountId,
			@DiscountPercentage = RR_CNF_RevenueRecognitionRule.Percentage,
			@DiscountDays = RR_CNF_RevenueRecognitionRule.Days,
			@DiscountPrice = COA_CNF_AccountConfig.Price,
			@DiscountCOAAccount_Percentage = COA_CNF_AccountConfig.Percentage,
			@DiscountRemainingValues = COA_CNF_AccountConfig.RemainingValues,
			@DiscountCOAAccountCode = coa_cnf_account.Code,
			@DiscountRRCOAAccountingType = COA_CNF_AccountConfig.AccountingType
	from coa_cnf_account
		INNER JOIN COA_CNF_AccountType				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
		INNER JOIN COA_CNF_AccountConfig			on COA_CNF_AccountConfig.COAAccountId = coa_cnf_account.COAAccountId
		INNER JOIN RR_CNF_RevenueRecognitionRule	on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId
	where coa_cnf_account.COAAccountID = @DiscountAccountID
	 order by RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId

	Declare @Temp table (BatchDate date)

	;with dates_CTE (date) as (
			select @FromDate 
		Union ALL
			select DATEADD(day, 1, date)
			from dates_CTE
			where date &lt; @ToDate
	) 
	INSERT INTO @Temp (
	BatchDate
	) 
	select *
	from dates_CTE 

	DECLARE date_Cursor CURSOR LOCAL FOR
				select * from @Temp

	OPEN date_Cursor

	FETCH NEXT FROM date_Cursor INTO
		@BatchDate

	WHILE @@FETCH_STATUS = 0
	BEGIN

				INSERT INTO [dbo].[RR_DATA_Revenue]
								([COAAccountId]
								,[RevenueRecognitionRuleId]
								,[RRCode]
								,[RRCalcTypeWhere]
								,[RRCalcTypeMethod]
								,[COAAccountConfigId]
								,[COAAccountType]
								,[COAAccountCode]
								,[TransactionId]
								,[SaleId]
								,[SaleItemId]
								,[MatrixCellId]
								,[MatrixCellCode]
								,[MatrixSheetID]
								,[SiteId]
								,[OperatingAreaId]
								,[WorkstationId]
								,[UserGroupId]
								,[UserId]
								,[FCalcDate]
								,[FRevenueDate]
								,[Quantity]
								,[UnitAmount]
								,[GrossAmount]
								,[NetAmount]
								,[Price]
								,[Percentage]
								,[RemaningValues]
								,[RevenueAmount]
								,[AccountingType]
								,[RRCalcTypeTrigger]
								,[RRPercentage]
								,[RRDays]
								,[AttributeIDS])
						select @SuspendCOAAccountId,
								@SuspendRRRId,
								@SuspendRRRCode,
								@SuspendRRCalcTypeWhere,
								@SuspendRRCalcTypeMethod,
								@SuspendCOAAccountConfigId,
								@SuspendCOAAccountTypeId,
								@SuspendCOAAccountCode,
								data_transaction.transactionid, 
								data_transaction.saleid,
								DATA_TransactionItem.saleitemid,
								DATA_SaleItem.Matrixcellid,
								CNF_MatrixCell.Code,
								CNF_MatrixCell.MatrixSheetid,
								data_transaction.Siteid,
								data_transaction.OperatingAreaId,
								data_transaction.Workstationid,
								data_transaction.UserGroupid,
								data_transaction.UserId,
								@BatchDate,
								CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
									 else data_transaction.TransactionDate
								end TransactionDate,
								Coalesce(DATA_TransactionItem.Quantity, 1),
								DATA_SaleItem.UnitPrice,
								case when isnull(DATA_TransactionItem.TotalAmount, 0) &lt;&gt; 0 then DATA_TransactionItem.TotalAmount
									when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
									else DATA_Sale.TotalAmount
								end,
								case when isnull((DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes)
									when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
									else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
								end as NetAmount,
								@SuspendPrice,
								@SuspendCOAAccount_Percentage,
								@SuspendRemainingValues,
								case    when (data_saleitem.ProductTaxType &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice ) * DATA_SaleItem.Quantity)
										when (data_saleitem.ProductTaxType = 1) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice - DATA_SaleItem.unittaxes) * DATA_SaleItem.Quantity)
										when (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 then 0				
										when isnull((data_transaction.TotalAmount), 0) &lt;&gt; 0 then data_transaction.TotalAmount
										when isnull((DATA_Sale.TotalAmount), 0) &lt;&gt; 0 then DATA_Sale.TotalAmount
										else (data_transaction.Revenue)
								end,
								case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
										when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
										when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 1
										when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 2
										else @SuspendRRCOAAccountingType
								end Accountingtype,
								@SuspendRRCalcTypeTrigger,
								@SuspendPercentage,
								@SuspendDays,
								CNF_AttributeSet.Attributeids
	   
						from DATA_Sale
							inner join data_transaction			on data_transaction.TransactionId = DATA_Sale.PaidTransactionId
							left join DATA_TransactionItem		on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
							left join DATA_SaleItem			    on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
							left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
							left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

						where DATA_Sale.Paid = 1
							and data_transaction.transactiontype in (14)
							and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
							   OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
							and data_transaction.transactionid in (select transactionid
																	from data_payment
																	where PaymentStatus = 1
																	and PaymentAmount &lt;&gt; 0
																)

				INSERT INTO [dbo].[RR_DATA_Revenue]
								([COAAccountId]
								,[RevenueRecognitionRuleId]
								,[RRCode]
								,[RRCalcTypeWhere]
								,[RRCalcTypeMethod]
								,[COAAccountConfigId]
								,[COAAccountType]
								,[COAAccountCode]
								,[TransactionId]
								,[SaleId]
								,[SaleItemId]
								,[MatrixCellId]
								,[MatrixCellCode]
								,[MatrixSheetID]
								,[SiteId]
								,[OperatingAreaId]
								,[WorkstationId]
								,[UserGroupId]
								,[UserId]
								,[FCalcDate]
								,[FRevenueDate]
								,[Quantity]
								,[UnitAmount]
								,[GrossAmount]
								,[NetAmount]
								,[Price]
								,[Percentage]
								,[RemaningValues]
								,[RevenueAmount]
								,[AccountingType]
								,[RRCalcTypeTrigger]
								,[RRPercentage]
								,[RRDays]
								,[AttributeIDS])
						select @SuspendCOAAccountId,
								@SuspendRRRId,
								@SuspendRRRCode,
								@SuspendRRCalcTypeWhere,
								@SuspendRRCalcTypeMethod,
								@SuspendCOAAccountConfigId,
								@SuspendCOAAccountTypeId,
								@SuspendCOAAccountCode,
								data_transaction.transactionid, 
								data_transaction.saleid,
								DATA_TransactionItem.saleitemid,
								DATA_SaleItem.Matrixcellid,
								CNF_MatrixCell.Code,
								CNF_MatrixCell.MatrixSheetid,
								data_transaction.Siteid,
								data_transaction.OperatingAreaId,
								data_transaction.Workstationid,
								data_transaction.UserGroupid,
								data_transaction.UserId,
								@BatchDate,
								CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
									 else data_transaction.TransactionDate
								end TransactionDate,
								Coalesce(DATA_TransactionItem.Quantity, 1),
								DATA_SaleItem.UnitPrice,
								case when isnull(DATA_TransactionItem.TotalAmount, 0) &lt;&gt; 0 then DATA_TransactionItem.TotalAmount
									when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
									else DATA_Sale.TotalAmount
								end,
								case when isnull((DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes)
									when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
									else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
								end as NetAmount,
								@SuspendPrice,
								@SuspendCOAAccount_Percentage,
								@SuspendRemainingValues,
								DATA_SaleItem.UnitRecharge * data_saleitem.Quantity,
								case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
										when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
										when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 1
										when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 2
										else @SuspendRRCOAAccountingType
								end Accountingtype,
								@SuspendRRCalcTypeTrigger,
								@SuspendPercentage,
								@SuspendDays,
								CNF_AttributeSet.Attributeids
	   
						from DATA_Sale
							inner join data_transaction			on data_transaction.TransactionId = DATA_Sale.PaidTransactionId
							left join DATA_TransactionItem		on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
							left join DATA_SaleItem			    on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
							left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
							left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

						where DATA_Sale.Paid = 1
							and data_transaction.transactiontype in (14, 39)
							and DATA_SaleItem.UnitRecharge &lt;&gt; 0
							and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
							   OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
							and data_transaction.transactionid in (select transactionid
																	from data_payment
																	where PaymentStatus = 1
																	and PaymentAmount &lt;&gt; 0
																)

					INSERT INTO [dbo].[RR_DATA_Revenue]
								([COAAccountId]
								,[RevenueRecognitionRuleId]
								,[RRCode]
								,[RRCalcTypeWhere]
								,[RRCalcTypeMethod]
								,[COAAccountConfigId]
								,[COAAccountType]
								,[COAAccountCode]
								,[TransactionId]
								,[SaleId]
								,[SaleItemId]
								,[MatrixCellId]
								,[MatrixCellCode]
								,[MatrixSheetID]
								,[SiteId]
								,[OperatingAreaId]
								,[WorkstationId]
								,[UserGroupId]
								,[UserId]
								,[FCalcDate]
								,[FRevenueDate]
								,[Quantity]
								,[UnitAmount]
								,[GrossAmount]
								,[NetAmount]
								,[Price]
								,[Percentage]
								,[RemaningValues]
								,[RevenueAmount]
								,[AccountingType]
								,[RRCalcTypeTrigger]
								,[RRPercentage]
								,[RRDays]
								,[AttributeIDS])
						select @SuspendCOAAccountId,
								@SuspendRRRId,
								@SuspendRRRCode,
								@SuspendRRCalcTypeWhere,
								@SuspendRRCalcTypeMethod,
								@SuspendCOAAccountConfigId,
								@SuspendCOAAccountTypeId,
								@SuspendCOAAccountCode,
								data_transaction.transactionid, 
								data_transaction.saleid,
								DATA_TransactionItem.saleitemid,
								DATA_SaleItem.Matrixcellid,
								CNF_MatrixCell.Code,
								CNF_MatrixCell.MatrixSheetid,
								data_transaction.Siteid,
								data_transaction.OperatingAreaId,
								data_transaction.Workstationid,
								data_transaction.UserGroupid,
								data_transaction.UserId,
								@BatchDate,
								CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
									 else data_transaction.TransactionDate
								end TransactionDate,
								Coalesce(DATA_TransactionItem.Quantity, 1),
								DATA_SaleItem.UnitPrice,
								case when isnull(DATA_TransactionItem.TotalAmount, 0) &lt;&gt; 0 then DATA_TransactionItem.TotalAmount
									when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
									else DATA_Sale.TotalAmount
								end,
								case when isnull((DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes)
									when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
									else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
								end as NetAmount,
								@SuspendPrice,
								@SuspendCOAAccount_Percentage,
								@SuspendRemainingValues,
								case    when (data_saleitem.ProductTaxType &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) 
												  and (isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0) 
													   and (((select discountamount from data_saleitemrule where saleitemid = DATA_SaleItem.saleitemid) &gt; 0) and (data_transaction.transactiontype in (7, 20, 22)))							
											then ((DATA_SaleItem.UnitRawPrice + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)

										when (data_saleitem.ProductTaxType &lt;&gt; 1) and (data_transaction.transactiontype in (18, 20, 22)) and (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitPrice  + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)
										when (data_saleitem.ProductTaxType = 1) and (data_transaction.transactiontype in (18, 20, 22)) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitPrice - DATA_SaleItem.unittaxes + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)

										when (data_saleitem.ProductTaxType &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice  + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)
										when (data_saleitem.ProductTaxType = 1) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice - DATA_SaleItem.unittaxes + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)

										when (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 and data_saleitem.unitRecharge = 0 then 0
										when (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 and data_saleitem.unitRecharge &lt;&gt; 0 then data_saleitem.unitRecharge
										when isnull((data_transaction.TotalAmount), 0) &lt;&gt; 0 then data_transaction.TotalAmount
										when isnull((DATA_Sale.TotalAmount), 0) &lt;&gt; 0 then DATA_Sale.TotalAmount
										else (data_transaction.Revenue)
								end,
								case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
										when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
										when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 1
										when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 2
										else @SuspendRRCOAAccountingType
								end Accountingtype,
								@SuspendRRCalcTypeTrigger,
								@SuspendPercentage,
								@SuspendDays,
								CNF_AttributeSet.Attributeids
	   
						from DATA_Sale
							inner join data_transaction			on data_transaction.TransactionId = ISNULL(data_sale.voidtransactionid, DATA_Sale.PaidTransactionId)
							left join DATA_TransactionItem		on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
							left join DATA_SaleItem			    on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
							left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
							left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

						where DATA_Sale.Paid = 1
							and data_transaction.transactiontype not in (6, 8, 10, 12, 14, 16, 42, 43, 31, 39, 48, 49, 52, 46, 47)
							and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
							   OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
							and data_transaction.transactionid in (select transactionid
																	from data_payment
																	where PaymentStatus = 1
																	and PaymentAmount &lt;&gt; 0
																)

						INSERT INTO [dbo].[RR_DATA_Revenue]
										([COAAccountId]
										,[RevenueRecognitionRuleId]
										,[RRCode]
										,[RRCalcTypeWhere]
										,[RRCalcTypeMethod]
										,[COAAccountConfigId]
										,[COAAccountType]
										,[COAAccountCode]
										,[TransactionId]
										,[SaleId]
										,[SiteId]
										,[OperatingAreaId]
										,[WorkstationId]
										,[UserGroupId]
										,[UserId]
										,[FCalcDate]
										,[FRevenueDate]
										,[Quantity]
										,[GrossAmount]
										,[NetAmount]
										,[Price]
										,[Percentage]
										,[RemaningValues]
										,[RevenueAmount]
										,[AccountingType]
										,[RRCalcTypeTrigger]
										,[RRPercentage]
										,[RRDays])
								select @SuspendCOAAccountId,
										@SuspendRRRId,
										@SuspendRRRCode,
										@SuspendRRCalcTypeWhere,
										@SuspendRRCalcTypeMethod,
										@SuspendCOAAccountConfigId,
										@SuspendCOAAccountTypeId,
										@SuspendCOAAccountCode,
										data_transaction.transactionid, 
										data_transaction.saleid,
										data_transaction.Siteid,
										data_transaction.OperatingAreaId,
										data_transaction.Workstationid,
										data_transaction.UserGroupid,
										data_transaction.UserId,
										@BatchDate,
										CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
											 else data_transaction.TransactionDate
										end TransactionDate,
										0 Quantity,
										data_transaction.revenue TotalAmount,
										data_transaction.revenue NetAmount,
										@SuspendPrice,
										@SuspendCOAAccount_Percentage,
										@SuspendRemainingValues,
										p.Amount,
										@SuspendRRCOAAccountingType,
										@SuspendRRCalcTypeTrigger,
										@SuspendPercentage,
										@SuspendDays
	   
						from DATA_Sale
							inner join data_transaction			on data_transaction.saleid = data_sale.saleid
							left  join  (select settletransactionid, sum(data_payment.paymentamount) as amount
											from data_paymentcredit
												INNER JOIN DATA_Payment						on data_payment.paymentid = data_paymentcredit.paymentid
												INNER JOIN DATA_Transaction					on data_transaction.transactionid = data_paymentcredit.SettleTransactionId
											where ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
												  OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
											group by settletransactionid)p					on p.SettleTransactionId = data_transaction.transactionid

						where DATA_Sale.Paid = 1
							and data_transaction.transactiontype in (6)
							and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
							   OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))


					INSERT INTO [dbo].[RR_DATA_Revenue]
								([COAAccountId]
								,[RevenueRecognitionRuleId]
								,[RRCode]
								,[RRCalcTypeWhere]
								,[RRCalcTypeMethod]
								,[COAAccountConfigId]
								,[COAAccountType]
								,[COAAccountCode]
								,[TransactionId]
								,[SaleId]
								,[SaleItemId]
								,[MatrixCellId]
								,[MatrixCellCode]
								,[MatrixSheetID]
								,[SiteId]
								,[OperatingAreaId]
								,[WorkstationId]
								,[UserGroupId]
								,[UserId]
								,[FCalcDate]
								,[FRevenueDate]
								,[Quantity]
								,[UnitAmount]
								,[GrossAmount]
								,[NetAmount]
								,[Price]
								,[Percentage]
								,[RemaningValues]
								,[RevenueAmount]
								,[AccountingType]
								,[RRCalcTypeTrigger]
								,[RRPercentage]
								,[RRDays]
								,[AttributeIDS])
						select @SuspendCOAAccountId,
								@SuspendRRRId,
								@SuspendRRRCode,
								@SuspendRRCalcTypeWhere,
								@SuspendRRCalcTypeMethod,
								@SuspendCOAAccountConfigId,
								@SuspendCOAAccountTypeId,
								@SuspendCOAAccountCode,
								data_transaction.transactionid, 
								data_transaction.saleid,
								DATA_SaleItem.saleitemid,
								DATA_SaleItem.Matrixcellid,
								CNF_MatrixCell.Code,
								CNF_MatrixCell.MatrixSheetid,
								data_transaction.Siteid,
								data_transaction.OperatingAreaId,
								data_transaction.Workstationid,
								data_transaction.UserGroupid,
								data_transaction.UserId,
								@BatchDate,
								CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
									 else data_transaction.TransactionDate
								end TransactionDate,
								Coalesce(DATA_SaleItem.Quantity, 1),
								DATA_SaleItem.UnitPrice,
								case when isnull(DATA_SaleItem.TotalAmount, 0) &lt;&gt; 0 then DATA_SaleItem.TotalAmount
									when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
									else DATA_Sale.TotalAmount
								end,
								case when isnull((DATA_SaleItem.TotalAmount - DATA_SaleItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_SaleItem.TotalAmount - DATA_SaleItem.TotalTaxes)
									when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
									else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
								end as NetAmount,
								@SuspendPrice,
								@SuspendCOAAccount_Percentage,
								@SuspendRemainingValues,
								case    when (data_saleitem.ProductTaxType &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) 
												  and (isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0) 
													   and (((select discountamount from data_saleitemrule where saleitemid = DATA_SaleItem.saleitemid) &gt; 0) and (data_transaction.transactiontype in (7, 20, 22)))							
											then ((DATA_SaleItem.UnitRawPrice + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)


										when (data_saleitem.ProductTaxType &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice  + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)
										when (data_saleitem.ProductTaxType = 1) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice - DATA_SaleItem.unittaxes + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)
										when (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 then 0
										when (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 and data_saleitem.unitRecharge &lt;&gt; 0 then data_saleitem.unitRecharge
										when isnull((data_transaction.TotalAmount), 0) &lt;&gt; 0 then data_transaction.TotalAmount
										when isnull((DATA_Sale.TotalAmount), 0) &lt;&gt; 0 then DATA_Sale.TotalAmount
										else (data_transaction.Revenue)
								end,
								case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
										when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
										when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 1
										when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 2
										else @SuspendRRCOAAccountingType
								end Accountingtype,
								@SuspendRRCalcTypeTrigger,
								@SuspendPercentage,
								@SuspendDays,
								CNF_AttributeSet.Attributeids
	   
						from DATA_Sale
							inner join data_transaction			on data_transaction.saleid = data_sale.saleid
							left join DATA_SaleItem			    on DATA_SaleItem.saleid = DATA_Transaction.saleid
							left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
							left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

						where DATA_Sale.Paid = 1
							and data_transaction.transactiontype in (46, 47)
							and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
							   OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
							and data_transaction.transactionid in (select transactionid
																	from data_payment
																	where PaymentStatus = 1
																	and PaymentAmount &lt;&gt; 0
																)


					INSERT INTO [dbo].[RR_DATA_Revenue]
								([COAAccountId]
								,[RevenueRecognitionRuleId]
								,[RRCode]
								,[RRCalcTypeWhere]
								,[RRCalcTypeMethod]
								,[COAAccountConfigId]
								,[COAAccountType]
								,[COAAccountCode]
								,[TransactionId]
								,[SaleId]
								,[SaleItemId]
								,[MatrixCellId]
								,[MatrixCellCode]
								,[MatrixSheetID]
								,[SiteId]
								,[OperatingAreaId]
								,[WorkstationId]
								,[UserGroupId]
								,[UserId]
								,[FCalcDate]
								,[FRevenueDate]
								,[Quantity]
								,[UnitAmount]
								,[GrossAmount]
								,[NetAmount]
								,[Price]
								,[Percentage]
								,[RemaningValues]
								,[RevenueAmount]
								,[AccountingType]
								,[RRCalcTypeTrigger]
								,[RRPercentage]
								,[RRDays]
								,[AttributeIDS])
						select @SuspendCOAAccountId,
								@SuspendRRRId,
								@SuspendRRRCode,
								@SuspendRRCalcTypeWhere,
								@SuspendRRCalcTypeMethod,
								@SuspendCOAAccountConfigId,
								@SuspendCOAAccountTypeId,
								@SuspendCOAAccountCode,
								data_transaction.transactionid, 
								data_transaction.saleid,
								DATA_TransactionItem.saleitemid,
								DATA_SaleItem.Matrixcellid,
								CNF_MatrixCell.Code,
								CNF_MatrixCell.MatrixSheetid,
								data_transaction.Siteid,
								data_transaction.OperatingAreaId,
								data_transaction.Workstationid,
								data_transaction.UserGroupid,
								data_transaction.UserId,
								@BatchDate,
								CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
									 else data_transaction.TransactionDate
								end TransactionDate,
								Coalesce(DATA_TransactionItem.Quantity, 1),
								DATA_SaleItem.UnitPrice,
								case when isnull(DATA_TransactionItem.TotalAmount, 0) &lt;&gt; 0 then DATA_TransactionItem.TotalAmount
									when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
									else DATA_Sale.TotalAmount
								end,
								case when isnull((DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes)
									when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
									else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
								end as NetAmount,
								@SuspendPrice,
								@SuspendCOAAccount_Percentage,
								@SuspendRemainingValues,
								DATA_SaleItem.Unitrecharge,
								case    when TransactionType in (5, 17, 8, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
										when TransactionType in (5, 17, 8, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
										when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 2
										when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 1
										else @SuspendRRCOAAccountingType
								end Accountingtype,
								@SuspendRRCalcTypeTrigger,
								@SuspendPercentage,
								@SuspendDays,
								CNF_AttributeSet.Attributeids
	   
						from DATA_Sale
							inner join data_transaction			on data_transaction.TransactionId = ISNULL(data_sale.voidtransactionid, DATA_Sale.PaidTransactionId)
							left join DATA_TransactionItem		on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
							left join DATA_SaleItem			    on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
							left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
							left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

						where DATA_Sale.Paid = 1
							and data_transaction.transactiontype in (10, 42, 43, 49)
							and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
							   OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
							and data_transaction.transactionid in (select transactionid
																	from data_payment
																	where PaymentStatus = 1
																	and PaymentAmount &lt;&gt; 0
																)
			
				INSERT INTO [dbo].[RR_DATA_Revenue]
								([COAAccountId]
								,[RevenueRecognitionRuleId]
								,[RRCode]
								,[RRCalcTypeWhere]
								,[RRCalcTypeMethod]
								,[COAAccountConfigId]
								,[COAAccountType]
								,[COAAccountCode]
								,[TransactionId]
								,[SaleId]
								,[SaleItemId]
								,[MatrixCellId]
								,[MatrixCellCode]
								,[MatrixSheetID]
								,[SiteId]
								,[OperatingAreaId]
								,[WorkstationId]
								,[UserGroupId]
								,[UserId]
								,[FCalcDate]
								,[FRevenueDate]
								,[Quantity]
								,[UnitAmount]
								,[GrossAmount]
								,[NetAmount]
								,[Price]
								,[Percentage]
								,[RemaningValues]
								,[RevenueAmount]
								,[AccountingType]
								,[RRCalcTypeTrigger]
								,[RRPercentage]
								,[RRDays]
								,[AttributeIDS])
						select @SuspendCOAAccountId,
								@SuspendRRRId,
								@SuspendRRRCode,
								@SuspendRRCalcTypeWhere,
								@SuspendRRCalcTypeMethod,
								@SuspendCOAAccountConfigId,
								@SuspendCOAAccountTypeId,
								@SuspendCOAAccountCode,
								data_transaction.transactionid, 
								data_transaction.saleid,
								DATA_TransactionItem.saleitemid,
								DATA_SaleItem.Matrixcellid,
								CNF_MatrixCell.Code,
								CNF_MatrixCell.MatrixSheetid,
								data_transaction.Siteid,
								data_transaction.OperatingAreaId,
								data_transaction.Workstationid,
								data_transaction.UserGroupid,
								data_transaction.UserId,
								@BatchDate,
								CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
									 else data_transaction.TransactionDate
								end TransactionDate,
								Coalesce(DATA_TransactionItem.Quantity, 1),
								DATA_SaleItem.UnitPrice,
								case when isnull(DATA_TransactionItem.TotalAmount, 0) &lt;&gt; 0 then DATA_TransactionItem.TotalAmount
									when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
									else DATA_Sale.TotalAmount
								end,
								case when isnull((DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes)
									when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
									else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
								end as NetAmount,
								@SuspendPrice,
								@SuspendCOAAccount_Percentage,
								@SuspendRemainingValues,
								ABS(DATA_SaleItem.Unitrecharge),
								case    when TransactionType in (5, 17, 8, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
										when TransactionType in (5, 17, 8, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
										when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 2
										when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 1
										else @SuspendRRCOAAccountingType
								end Accountingtype,
								@SuspendRRCalcTypeTrigger,
								@SuspendPercentage,
								@SuspendDays,
								CNF_AttributeSet.Attributeids
	   
						from DATA_Sale
							inner join data_transaction			on data_transaction.TransactionId = ISNULL(data_sale.voidtransactionid, DATA_Sale.PaidTransactionId)
							left join DATA_TransactionItem		on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
							left join DATA_SaleItem			    on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
							left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
							left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

						where DATA_Sale.Paid = 1
							and data_transaction.transactiontype in (31, 48, 52)
							and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
							   OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
							and data_transaction.transactionid in (select transactionid
																	from data_payment
																	where PaymentStatus = 1
																	and PaymentAmount &lt;&gt; 0
																   )


					INSERT INTO [dbo].[RR_DATA_Revenue]
										([COAAccountId]
										,[RevenueRecognitionRuleId]
										,[RRCode]
										,[RRCalcTypeWhere]
										,[RRCalcTypeMethod]
										,[COAAccountConfigId]
										,[COAAccountType]
										,[COAAccountCode]
										,[TransactionId]
										,[SaleId]
										,[SaleItemId]
										,[MatrixCellId]
										,[MatrixCellCode]
										,[MatrixSheetID]
										,[SiteId]
										,[OperatingAreaId]
										,[WorkstationId]
										,[UserGroupId]
										,[UserId]
										,[FCalcDate]
										,[FRevenueDate]
										,[Quantity]
										,[UnitAmount]
										,[GrossAmount]
										,[NetAmount]
										,[Price]
										,[Percentage]
										,[RemaningValues]
										,[RevenueAmount]
										,[AccountingType]
										,[RRCalcTypeTrigger]
										,[RRPercentage]
										,[RRDays]
										,[AttributeIDS])
								select @SuspendCOAAccountId,
										@SuspendRRRId,
										@SuspendRRRCode,
										@SuspendRRCalcTypeWhere,
										@SuspendRRCalcTypeMethod,
										@SuspendCOAAccountConfigId,
										@SuspendCOAAccountTypeId,
										@SuspendCOAAccountCode,
										data_transaction.transactionid, 
										data_transaction.saleid,
										DATA_TransactionItem.saleitemid,
										DATA_SaleItem.Matrixcellid,
										CNF_MatrixCell.Code,
										CNF_MatrixCell.MatrixSheetid,
										data_transaction.Siteid,
										data_transaction.OperatingAreaId,
										data_transaction.Workstationid,
										data_transaction.UserGroupid,
										data_transaction.UserId,
										@BatchDate,
										CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
											 else data_transaction.TransactionDate
										end TransactionDate,
										Coalesce(DATA_TransactionItem.Quantity, 1),
										DATA_SaleItem.UnitPrice,
										case when isnull(DATA_TransactionItem.TotalAmount, 0) &lt;&gt; 0 then DATA_TransactionItem.TotalAmount
											when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
											else DATA_Sale.TotalAmount
										end,
										case when isnull((DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes)
											when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
											else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
										end as NetAmount,
										@SuspendPrice,
										@SuspendCOAAccount_Percentage,
										@SuspendRemainingValues,
										case when (data_saleitem.ProductTaxType &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice + DATA_SaleItem.unittaxes) * DATA_SaleItem.Quantity)
											 when (data_saleitem.ProductTaxType = 1) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice) * DATA_SaleItem.Quantity)
											 when (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 then 0
											 when isnull((data_transaction.TotalAmount), 0) &lt;&gt; 0 then data_transaction.TotalAmount
											 when isnull((DATA_Sale.TotalAmount), 0) &lt;&gt; 0 then DATA_Sale.TotalAmount
											 else (data_transaction.Revenue)
										end,
										case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
												when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
												when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 2
												when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 1
												else @SuspendRRCOAAccountingType
										end Accountingtype,
										@SuspendRRCalcTypeTrigger,
										@SuspendPercentage,
										@SuspendDays,
										CNF_AttributeSet.Attributeids
	   
								from DATA_Sale
									inner join data_transaction			on data_transaction.Saleid = DATA_Sale.Saleid
									left join DATA_TransactionItem		on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
									left join DATA_SaleItem			    on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
									left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
									left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

								where data_transaction.transactiontype in (8)
									and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
										OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
									and data_transaction.transactionid in (select transactionid
																			from data_payment
																			where PaymentStatus = 1
																			and PaymentAmount &lt;&gt; 0
																		)

							INSERT INTO [dbo].[RR_DATA_Revenue]
										([COAAccountId]
										,[RevenueRecognitionRuleId]
										,[RRCode]
										,[RRCalcTypeWhere]
										,[RRCalcTypeMethod]
										,[COAAccountConfigId]
										,[COAAccountType]
										,[COAAccountCode]
										,[TransactionId]
										,[SaleId]
										,[SiteId]
										,[OperatingAreaId]
										,[WorkstationId]
										,[UserGroupId]
										,[UserId]
										,[FCalcDate]
										,[FRevenueDate]
										,[Quantity]
										,[GrossAmount]
										,[NetAmount]
										,[Price]
										,[Percentage]
										,[RemaningValues]
										,[RevenueAmount]
										,[AccountingType]
										,[RRCalcTypeTrigger]
										,[RRPercentage]
										,[RRDays])
								select @SuspendCOAAccountId,
										@SuspendRRRId,
										@SuspendRRRCode,
										@SuspendRRCalcTypeWhere,
										@SuspendRRCalcTypeMethod,
										@SuspendCOAAccountConfigId,
										@SuspendCOAAccountTypeId,
										@SuspendCOAAccountCode,
										data_transaction.transactionid, 
										data_transaction.saleid,
										data_transaction.Siteid,
										data_transaction.OperatingAreaId,
										data_transaction.Workstationid,
										data_transaction.UserGroupid,
										data_transaction.UserId,
										@BatchDate,
										CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
											 else data_transaction.TransactionDate
										end TransactionDate,
										0 Quantity,
										data_transaction.revenue TotalAmount,
										data_transaction.revenue NetAmount,
										@SuspendPrice,
										@SuspendCOAAccount_Percentage,
										@SuspendRemainingValues,
										data_transaction.revenue,
										@SuspendRRCOAAccountingType,
										@SuspendRRCalcTypeTrigger,
										@SuspendPercentage,
										@SuspendDays
	   
								from DATA_Sale
									inner join data_transaction			on data_transaction.saleid = DATA_Sale.saleid
								where data_transaction.transactiontype = 12
									and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
										OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
									and data_transaction.transactionid in (select transactionid
																			from data_payment
																			where PaymentStatus = 1
																			and PaymentAmount &lt;&gt; 0
																		)



								INSERT INTO [dbo].[RR_DATA_Revenue]
										([COAAccountId]
										,[RevenueRecognitionRuleId]
										,[RRCode]
										,[RRCalcTypeWhere]
										,[RRCalcTypeMethod]
										,[COAAccountConfigId]
										,[COAAccountType]
										,[COAAccountCode]
										,[TransactionId]
										,[SaleId]
										,[SaleItemId]
										,[MatrixCellId]
										,[MatrixCellCode]
										,[MatrixSheetID]
										,[SiteId]
										,[OperatingAreaId]
										,[WorkstationId]
										,[UserGroupId]
										,[UserId]
										,[FCalcDate]
										,[FRevenueDate]
										,[Quantity]
										,[UnitAmount]
										,[GrossAmount]
										,[NetAmount]
										,[Price]
										,[Percentage]
										,[RemaningValues]
										,[RevenueAmount]
										,[AccountingType]
										,[RRCalcTypeTrigger]
										,[RRPercentage]
										,[RRDays]
										,[AttributeIDS])
										select *
										from (
								select @SuspendCOAAccountId as COAAccountId,
										@SuspendRRRId as RevenueRecognitionRuleId,
										@SuspendRRRCode as RRCode,
										@SuspendRRCalcTypeWhere as RRCalcTypeWhere,
										@SuspendRRCalcTypeMethod as RRCalcTypeMethod,
										@SuspendCOAAccountConfigId as COAAccountConfigId,
										@SuspendCOAAccountTypeId as COAAccountType,
										@SuspendCOAAccountCode as COAAccountCode,
										data_transaction.transactionid, 
										data_transaction.saleid,
										DATA_SaleItem.saleitemid,
										DATA_SaleItem.Matrixcellid,
										CNF_MatrixCell.Code,
										CNF_MatrixCell.MatrixSheetid,
										data_transaction.Siteid,
										data_transaction.OperatingAreaId,
										data_transaction.Workstationid,
										data_transaction.UserGroupid,
										data_transaction.UserId,
										@BatchDate as calcdate,
										CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
												else data_transaction.TransactionDate
										end TransactionDate,
										Coalesce(DATA_SaleItem.Quantity, 1) as quantity,
										DATA_SaleItem.UnitPrice,
										case when isnull(DATA_SaleItem.TotalAmount, 0) &lt;&gt; 0 then DATA_SaleItem.TotalAmount
											when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
											else DATA_Sale.TotalAmount
										end as totalamount,
										case when isnull((DATA_SaleItem.TotalAmount - DATA_SaleItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_SaleItem.TotalAmount - DATA_SaleItem.TotalTaxes)
											when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
											else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
										end as NetAmount,
										@SuspendPrice as suspendprice,
										@SuspendCOAAccount_Percentage as percentage,
										@SuspendRemainingValues as remainingValues,
										case when (data_saleitem.ProductTaxType &lt;&gt; 1) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice) * DATA_SaleItem.Quantity)
											 when (data_saleitem.ProductTaxType = 1) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice - DATA_SaleItem.unittaxes) * DATA_SaleItem.Quantity)
											 when isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 then 0
											 when isnull((data_transaction.TotalAmount), 0) &lt;&gt; 0 then data_transaction.TotalAmount
											 when isnull((DATA_Sale.TotalAmount), 0) &lt;&gt; 0 then DATA_Sale.TotalAmount
											 else (data_transaction.Revenue)
										end as Revenueamount,
										case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
												when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
												when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 2
												when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 1
												else @SuspendRRCOAAccountingType
										end Accountingtype,
										@SuspendRRCalcTypeTrigger as rrTrigger,
										@SuspendPercentage as suspercentage,
										@SuspendDays as suspendday,
										CNF_AttributeSet.Attributeids
	   
								from DATA_Sale
									inner join data_transaction			on data_transaction.TransactionId = DATA_Sale.PaidTransactionId
									left join DATA_SaleItem			    on DATA_SaleItem.SAleid = data_transaction.SAleid
									left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
									left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

								where DATA_Sale.Paid = 1
									and data_transaction.transactiontype in (16)
									and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
									 OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
									and data_transaction.transactionid in (select transactionid
																			from data_payment
																			where PaymentStatus = 1
																			--and PaymentAmount &lt;&gt; 0
																		)
									and data_transaction.transactionid not in (select distinct transactionid
																				from rr_data_Revenue
																				where transactionid is not null)
									and data_saleitem.saleitemid not in (select distinct data_saleitem.saleitemid
																	from data_saleitem
																			inner join data_transactionitem   on data_transactionitem.saleitemid = data_saleitem.saleitemid
																			inner join data_transaction       on data_transaction.transactionid = data_transactionitem.transactionid
																	where data_transaction.transactiontype in (5)
																	)
									)p  where UnitPrice &lt;&gt; 0


								INSERT INTO [dbo].[RR_DATA_Revenue]
										([COAAccountId]
										,[RevenueRecognitionRuleId]
										,[RRCode]
										,[RRCalcTypeWhere]
										,[RRCalcTypeMethod]
										,[COAAccountConfigId]
										,[COAAccountType]
										,[COAAccountCode]
										,[TransactionId]
										,[SaleId]
										,[SaleItemId]
										,[MatrixCellId]
										,[MatrixCellCode]
										,[MatrixSheetID]
										,[SiteId]
										,[OperatingAreaId]
										,[WorkstationId]
										,[UserGroupId]
										,[UserId]
										,[FCalcDate]
										,[FRevenueDate]
										,[Quantity]
										,[UnitAmount]
										,[GrossAmount]
										,[NetAmount]
										,[Price]
										,[Percentage]
										,[RemaningValues]
										,[RevenueAmount]
										,[AccountingType]
										,[RRCalcTypeTrigger]
										,[RRPercentage]
										,[RRDays]
										,[AttributeIDS])
								select @SuspendCOAAccountId,
										@SuspendRRRId,
										@SuspendRRRCode,
										@SuspendRRCalcTypeWhere,
										@SuspendRRCalcTypeMethod,
										@SuspendCOAAccountConfigId,
										@SuspendCOAAccountTypeId,
										@SuspendCOAAccountCode,
										data_transaction.transactionid, 
										data_transaction.saleid,
										DATA_TransactionItem.saleitemid,
										DATA_SaleItem.Matrixcellid,
										CNF_MatrixCell.Code,
										CNF_MatrixCell.MatrixSheetid,
										data_transaction.Siteid,
										data_transaction.OperatingAreaId,
										data_transaction.Workstationid,
										data_transaction.UserGroupid,
										data_transaction.UserId,
										@BatchDate,
										CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
											 else data_transaction.TransactionDate
										end TransactionDate,
										Coalesce(DATA_TransactionItem.Quantity, 1),
										DATA_SaleItem.UnitPrice,
										case when isnull(DATA_TransactionItem.TotalAmount, 0) &lt;&gt; 0 then DATA_TransactionItem.TotalAmount
											when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
											else DATA_Sale.TotalAmount
										end,
										case when isnull((DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes)
											when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
											else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
										end as NetAmount,
										@SuspendPrice,
										@SuspendCOAAccount_Percentage,
										@SuspendRemainingValues,
										case when isnull((DATA_TransactionItem.UnitPrice *  DATA_TransactionItem.Quantity), 0) &lt;&gt; 0 then (DATA_TransactionItem.UnitPrice *  DATA_TransactionItem.Quantity)
											when isnull((data_transaction.TotalAmount), 0) &lt;&gt; 0 then data_transaction.TotalAmount
											when isnull((DATA_Sale.TotalAmount), 0) &lt;&gt; 0 then DATA_Sale.TotalAmount
											else (data_transaction.Revenue)
										end,
										case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
												when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
												when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 2
												when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 1
												else @SuspendRRCOAAccountingType
										end Accountingtype,
										@SuspendRRCalcTypeTrigger,
										@SuspendPercentage,
										@SuspendDays,
										CNF_AttributeSet.Attributeids
	   
								from DATA_Sale
									inner join data_transaction			on data_transaction.saleid = DATA_Sale.saleid
									inner join DATA_TransactionItem		on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
									left join DATA_SaleItem			    on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
									left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
									left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

								where DATA_Sale.Paid = 1
									and data_transaction.transactiontype in (5)
									and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
									 OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
					
									and data_transaction.transactionid in (select transactionid
																			from data_payment
																			where PaymentStatus = 1
																			and PaymentAmount &lt;&gt; 0
																		)
									and data_transaction.transactionid not in (select distinct transactionid
																				from rr_data_Revenue
																				where transactionid is not null)

				--PaymentMethod
								INSERT INTO [dbo].[RR_DATA_Revenue]
												([COAAccountId]
												,[RevenueRecognitionRuleId]
												,[RRCode]
												,[RRCalcTypeWhere]
												,[RRCalcTypeMethod]
												,[COAAccountConfigId]
												,[COAAccountType]
												,[COAAccountCode]
												,[TransactionId]
												,[SaleId]
												,[SiteId]
												,[OperatingAreaId]
												,[WorkstationId]
												,[UserGroupId]
												,[UserId]
												,[FCalcDate]
												,[FRevenueDate]
												,[Quantity]
												,[GrossAmount]
												,[NetAmount]
												,[Price]
												,[Percentage]
												,[RemaningValues]
												,[RevenueAmount]
												,[AccountingType]
												,[RRCalcTypeTrigger]
												,[RRPercentage]
												,[RRDays])
												select  coaaccountid,
														RRID,
														RRCode,
														TypeWhere,
														method,
														Configid,
														AccountType,
														AccountCode,
														transactionid, 
														saleid,
														Siteid,
														OperatingAreaId,
														WorkstationID,
														UserGroupid,
														UserId,
														BatchDate,
														TransactionDate,
														Qty,
														Gross,
														net,
														price,
														percentage,
														RemaningValue,
														sum(abs(RevenueAmount)),
														Accountingtype,
														TypeTrigger,
														PaymentPercentage,
														RRDays
												from (
												select  coaaccountid,
														RRID,
														RRCode,
														TypeWhere,
														method,
														Configid,
														AccountType,
														AccountCode,
														transactionid, 
														saleid,
														Siteid,
														OperatingAreaId,
														WorkstationID,
														UserGroupid,
														UserId,
														BatchDate,
														TransactionDate,
														Qty,
														Gross,
														net,
														price,
														percentage,
														RemaningValue,
														case when Rownumber = 1 then RevenueAmount + Change
															 else RevenueAmount
														 end RevenueAmount,
														Accountingtype,
														TypeTrigger,
														PaymentPercentage,
														RRDays
												from (
												select @PaymentCOAAccountId as coaaccountid,
														@PaymentRRRId as RRID,
														@PaymentRRRCode as RRCode,
														@PaymentRRCalcTypeWhere as TypeWhere,
														@PaymentRRCalcTypeMethod as method,
														@PaymentCOAAccountConfigId as Configid,
														@PaymentCOAAccountTypeId as AccountType,
														@PaymentCOAAccountCode as AccountCode,
														data_transaction.transactionid, 
														data_transaction.saleid,
														data_transaction.Siteid,
														data_transaction.OperatingAreaId,
														data_transaction.Workstationid,
														data_transaction.UserGroupid,
														data_transaction.UserId,
														@BatchDate as BatchDate,
														CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
															 else data_transaction.TransactionDate
														end TransactionDate,
														0 as Qty,
														0 as Gross,
														0 as net,
														0 as price,
														100 as percentage,
														0 as RemaningValue,
														(data_payment.PaymentAmount) as RevenueAmount,
														case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @PaymentRRCOAAccountingType = 1 then 2
																when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @PaymentRRCOAAccountingType = 2 then 1
																when TransactionType in (7) and (data_payment.PaymentAmount + data_Payment.PaymentFee) &lt;= 0  then 2
																when TransactionType in (7) and (data_payment.PaymentAmount + data_Payment.PaymentFee) &gt; 0  then 1
																else @PaymentRRCOAAccountingType
														end Accountingtype,
														data_transaction.Change,
														@PaymentRRCalcTypeTrigger as TypeTrigger,
														@PaymentPercentage as PaymentPercentage,
														@PaymentDays as RRDays,
														Row_Number ()  OVER (PARTITION BY data_transaction.transactionid order by data_transaction.transactionid)  as Rownumber
		  
												from DATA_Sale
															INNER join data_transaction			on ((data_transaction.TransactionId = Isnull(data_sale.voidtransactionid, DATA_Sale.PaidTransactionId)) or 
																								   (data_transaction.saleid = data_sale.saleid))
															INNER JOIN DATA_Payment				on data_payment.transactionid = data_transaction.transactionid
			
												where data_payment.PaymentStatus = 1
													and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
													 OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
											)p
											)r
											group by 	coaaccountid,
														RRID,
														RRCode,
														TypeWhere,
														method,
														Configid,
														AccountType,
														AccountCode,
														transactionid, 
														saleid,
														Siteid,
														OperatingAreaId,
														Workstationid,
														UserGroupid,
														UserId,
														BatchDate,
														TransactionDate,
														Qty,
														Gross,
														net,
														price,
														percentage,
														RemaningValue,
														Accountingtype,
														TypeTrigger,
														PaymentPercentage,
														RRDays
											Having sum(abs(RevenueAmount)) &lt;&gt; 0
						



				--Tax
									INSERT INTO [dbo].[RR_DATA_Revenue]
												([COAAccountId]
												,[RevenueRecognitionRuleId]
												,[RRCode]
												,[RRCalcTypeWhere]
												,[RRCalcTypeMethod]
												,[COAAccountConfigId]
												,[COAAccountType]
												,[COAAccountCode]
												,[TransactionId]
												,[SaleId]
												,[SiteId]
												,[OperatingAreaId]
												,[WorkstationId]
												,[UserGroupId]
												,[UserId]
												,[FCalcDate]
												,[FRevenueDate]
												,[Quantity]
												,[GrossAmount]
												,[NetAmount]
												,[Price]
												,[Percentage]
												,[RemaningValues]
												,[RevenueAmount]
												,[AccountingType]
												,[RRCalcTypeTrigger]
												,[RRPercentage]
												,[RRDays])

												select  @TaxCOAAccountId,
														@TaxRRRId,
														@TaxRRRCode,
														@TaxRRCalcTypeWhere,
														@TaxRRCalcTypeMethod,
														@TaxCOAAccountConfigId,
														@TaxCOAAccountTypeId,
														@TaxCOAAccountCode,
														data_transaction.transactionid, 
														data_transaction.saleid,
														data_transaction.Siteid,
														data_transaction.OperatingAreaId,
														data_transaction.Workstationid,
														data_transaction.UserGroupid,
														data_transaction.UserId,
														@BatchDate,
														CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
															 else data_transaction.TransactionDate
														end TransactionDate,
														0,
														0,
														0,
														0,
														100,
														0,
														ABS(sum(taxamount)) RevenueAmount,
														case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @TaxRRCOAAccountingType = 1 then 2
																when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @TaxRRCOAAccountingType = 2 then 1
																when TransactionType in (7) and sum(taxamount) &lt;= 0  then 1
																when TransactionType in (7) and sum(taxamount) &gt; 0  then 2
																else @TaxRRCOAAccountingType
														end Accountingtype,
														@TaxRRCalcTypeTrigger,
														@TaxPercentage,
														@TaxDays
		   
											from Data_Sale
												INNER JOIN DATA_Transaction						on data_transaction.Saleid = Data_Sale.Saleid
												INNER JOIN DATA_TransactionTax					on data_transactiontax.transactionid = data_transaction.transactionid
												INNER JOIN CNF_Tax								on cnf_tax.taxid = DATA_TransactionTax.taxid
												--INNER JOIN coa_cnf_account coa					on coa.coaaccountid = cnf_tax.coaaccountid


											where transactiontype NOT IN (33, 45, 46, 47)
											   and Data_Sale.paid = 1
												and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
												 OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
												  and data_transaction.transactionid in (select distinct transactionid
																						   from data_payment
																						   where data_payment.paymentstatus = 1
																						)
											group by 			data_transaction.transactionid, 
																data_transaction.saleid,
																data_transaction.Siteid,
																data_transaction.OperatingAreaId,
																data_transaction.Workstationid,
																data_transaction.UserGroupid,
																data_transaction.UserId,
																Data_Transaction.TransactionDate,
																TransactionType,
																fTransactionDate


				--Discount

										INSERT INTO [dbo].[RR_DATA_Revenue]
												([COAAccountId]
												,[RevenueRecognitionRuleId]
												,[RRCode]
												,[RRCalcTypeWhere]
												,[RRCalcTypeMethod]
												,[COAAccountConfigId]
												,[COAAccountType]
												,[COAAccountCode]
												,[TransactionId]
												,[SaleId]
												,[SiteId]
												,[OperatingAreaId]
												,[WorkstationId]
												,[UserGroupId]
												,[UserId]
												,[FCalcDate]
												,[FRevenueDate]
												,[Quantity]
												,[GrossAmount]
												,[NetAmount]
												,[Price]
												,[Percentage]
												,[RemaningValues]
												,[RevenueAmount]
												,[AccountingType]
												,[RRCalcTypeTrigger]
												,[RRPercentage]
												,[RRDays])

												select  @DiscountCOAAccountId,
														@DiscountRRRId,
														@DiscountRRRCode,
														@DiscountRRCalcTypeWhere,
														@DiscountRRCalcTypeMethod,
														@DiscountCOAAccountConfigId,
														@DiscountCOAAccountTypeId,
														@DiscountCOAAccountCode,
														data_transaction.transactionid, 
														data_transaction.saleid,
														data_transaction.Siteid,
														data_transaction.OperatingAreaId,
														data_transaction.Workstationid,
														data_transaction.UserGroupid,
														data_transaction.UserId,
														@BatchDate,
														CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
															 else data_transaction.TransactionDate
														end TransactionDate,
														0,
														0,
														0,
														0,
														100,
														0,
														ABS(p.GLAmount) RevenueAmount,
														case    when data_transaction.TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) then 2
																when data_transaction.TransactionType in (7) and (GLAmount) &lt;= 0  then 2
																when data_transaction.TransactionType in (7) and (GLAmount) &gt; 0  then 1
																else @DiscountRRCOAAccountingType
														end Accountingtype,

														@DiscountRRCalcTypeTrigger,
														@DiscountPercentage,
														@DiscountDays
											FROM
											(
												SELECT distinct DATA_SaleItem.Saleitemid,
																DATA_Sale.saleid AS SAleid,
      															DATA_Transaction.TransactionType,
      															( SELECT top 1 transactionid
																	FROM data_transaction		WITH (NOLOCK)
																   WHERE saleid = DATA_Sale.saleid
																	AND transactiontype in (14, 16)
																	AND paid = 1
																) AS tester,

																CASE WHEN DATA_Transaction.TransactionId IN (
																											  SELECT TR.TransactionID
																												FROM DATA_Transaction TR			WITH (NOLOCK)
																													LEFT JOIN DATA_Payment DP		WITH (NOLOCK) ON TR.TransactionId = DP.TransactionId
																											  WHERE TR.SaleId = DATA_Sale.SaleId
																												AND TR.Paid = 1
																												AND DP.PaymentStatus NOT IN (0, 2, 3)
																											)
      
																			THEN DATA_Transaction.Transactionid
																	 ELSE (
																			  SELECT MIN(TR.TransactionID)
																				FROM DATA_Transaction TR				WITH (NOLOCK)
																					LEFT JOIN DATA_Payment DP			WITH (NOLOCK) ON TR.TransactionId = DP.TransactionId
																			   WHERE TR.SaleId = DATA_Sale.saleid
																				 AND TR.TransactionType = 16
																				 AND TR.Paid = 1
																				 AND DP.PaymentStatus NOT IN (0, 2, 3)
																		  )
																END Transactionid, 
																 CASE WHEN CNF_Promotion.PromotionType = 1 AND CNF_PromotionItemRule.NewProduct = 1 THEN  (CNF_MatrixCell.Price - SUM(DATA_SaleItemRule.DiscountAmount))
																	  ELSE  CASE WHEN sum(1*data_saleItemRule.DiscountAmount) &lt; 0 AND transactiontype IN(20, 22, 30, 7, 5, 46, 47) AND
																																												(SELECT Count(*) 
																																												   FROM data_transaction WITH (NOLOCK)
																																												  WHERE saleid = data_sale.saleid
																																												 ) = 1 					  					  					  										  
																					  THEN Sum(1 * DATA_SaleItemRule.DiscountAmount)
																				 WHEN sum(1*data_saleItemRule.DiscountAmount) &lt; 0 THEN	Sum(-1 * DATA_SaleItemRule.DiscountAmount)
																				 WHEN sum(1*data_saleItemRule.DiscountAmount) &gt; 0 AND transactiontype IN(20, 22, 30, 7, 5, 46, 47) THEN Sum(-1 * DATA_SaleItemRule.DiscountAmount)		            	                  
																				 ELSE sum(1*Data_SaleItemRule.DiscountAmount)
																			END
																END AS GLAmount


												FROM dbo.DATA_SaleItemRule				WITH (NOLOCK)
													LEFT JOIN dbo.CNF_PromotionItemRule WITH (NOLOCK) ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
													LEFT JOIN dbo.CNF_PromotionItem		WITH (NOLOCK) ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
													LEFT JOIN dbo.CNF_Promotion			WITH (NOLOCK) ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId
													LEFT JOIN dbo.CNF_DmgCategory		WITH (NOLOCK) ON CNF_DmgCategory.DmgCategoryId = CNF_Promotion.DmgCategoryId
													LEFT JOIN dbo.DATA_SaleItem			WITH (NOLOCK) ON DATA_SaleItem.SaleItemId = DATA_SaleItemRule.SaleItemId
													LEFT JOIN dbo.DATA_Sale				WITH (NOLOCK) ON DATA_Sale.SaleID = DATA_SaleItem.SaleID
													LEFT JOIN DATA_TransactionItem		WITH (NOLOCK) ON DATA_TransactionItem.SaleItemId = DATA_SaleItem.SaleItemId 
													LEFT JOIN DATA_Transaction			WITH (NOLOCK) ON  DATA_Transaction.TransactionId = DATA_TransactionItem.TransactionId
													LEFT JOIN CNF_MatrixCell			WITH (NOLOCK) ON CNF_MatrixCell.MatrixCellId =  DATA_SaleItem.MatrixCellId

 
												WHERE DATA_Transaction.saleid in (
																					SELECT ff.saleid 
																					  FROM DATA_Transaction ff WITH (NOLOCK) 
																						LEFT JOIN Data_Payment WITH (NOLOCK) on (ff.Transactionid = Data_Payment.Transactionid) 
																					 WHERE  ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
																						OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
																					   AND DATA_PAyment.PaymentStatus NOT in (0,2,3) 
																					   AND (TransactionType not in (12)) 
																					   AND ff.PAid = 1
																				 )  

												 AND DATA_Sale.Paid = 1
												 and transactiontype NOT IN (33, 45, 46, 47)
												 AND ((DATA_SaleItem.quantity &gt; 0) OR ((DATA_SaleItem.quantity &lt; 0) AND (transactiontype IN (20, 22, 30, 7, 5, 46, 47))))

         
												group BY DATA_SaleItem.Saleitemid,
														 DATA_Sale.saleid,
														 Data_transaction.Paid,
														 Data_Transaction.Transactionid,
														 Data_Transaction.fTransactionDate,
														 Data_Saleitem.Matrixcellid,
														 CNF_DmgCategory.DmgCategoryCode,
														 PromotionType,
														 CNF_PromotionItemRule.NewProduct,
														 CNF_MatrixCell.Price,
														 transactiontype,
														 CNF_DmgCategory.Description
											)p
												LEFT JOIN data_transaction WITH (NOLOCK) on data_transaction.transactionid = p.transactionid

											WHERE ((p.TransactionType &lt;&gt; 5) or (Tester is not null))
											  AND data_transaction.transactionid is not null


					
						--End Move Transactions to Suspend Account

						exec otn_sp_RR_RevenueData_OnDepositTrigger @BatchDate, @RRTransDateType

						exec otn_sp_RR_RevenueData_OnSaleTrigger @BatchDate, @RRTransDateType
		
						exec otn_sp_RR_RevenueData_OnMoneyCardLoad @BatchDate, @RRTransDateType

						exec otn_sp_RR_RevenueData_OnMoneyCardCashOut @BatchDate, @RRTransDateType

						exec otn_sp_RR_RevenueData_OnExternalMoneyCardCashOut @BatchDate, @RRTransDateType

						exec otn_sp_RR_RevenueData_OnExternalMoneyCardLoad @BatchDate, @RRTransDateType

						exec otn_sp_RR_RevenueData_OnCreditWriteoff @BatchDate, @RRTransDateType

						exec otn_sp_RR_RevenueData_OnMoneyRefundTrigger @BatchDate, @RRTransDateType

						exec otn_sp_RR_RevenueData_OnAdvancedPaymentTrigger @BatchDate, @RRTransDateType
		
						--exec otn_sp_RR_RevenueData_OnFlexContractPayment @BatchDate, @RRTransDateType

						--exec otn_sp_RR_RevenueData_OnFlexContractCancelled @BatchDate, @RRTransDateType

						exec otn_sp_RR_RevenueData_OnCreditSettlementTrigger @BatchDate, @RRTransDateType
		
						exec otn_sp_RR_RevenueData_SettleUpSuspendAccount @BatchDate, @RRTransDateType


						exec otn_sp_RR_RevenueData_OnTicketUsageTrigger @BatchDate, @RRTransDateType

						exec otn_sp_RR_RevenueData_OnEventTrigger @BatchDate, @RRTransDateType

						exec otn_sp_RR_RevenueData_OnTimePeriodTrigger @BatchDate, @RRTransDateType

						exec otn_sp_RR_RevenueData_OnTicketExpiredTrigger @BatchDate, @RRTransDateType
		

	FETCH NEXT FROM date_Cursor INTO
		@BatchDate

end

End
</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>smcdonald</ADDEDBY>
			<SQLVERSION>2313</SQLVERSION>
			<RMTRACKLINK>67297</RMTRACKLINK>
			<REASON>Add two new tables for the Travel Matrix functionality</REASON>
			<TABLENAMES>CNF_TravelMatrix=TravelMatrixId
CNF_TravelTime=TravelTimeId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS ( SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND  TABLE_NAME = 'CNF_TravelMatrix' )

BEGIN
  Create table [CNF_TravelMatrix]
  (
	[TravelMatrixId] Integer Identity(1,1) NOT NULL,
	[TravelMatrixAK] Varchar(32) NOT NULL, UNIQUE ([TravelMatrixAK]),
	[Code] Nvarchar(10) NULL,
	[Description] Ntext NULL,
	[Name] Nvarchar(50) NULL,
	[Enabled] Smallint Default 1 NULL,
  Primary Key ([TravelMatrixId])
  ) 
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS ( SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND  TABLE_NAME = 'CNF_TravelTime' )

BEGIN
  Create table [CNF_TravelTime]
  (
	[TravelTimeId] Integer Identity(1,1) NOT NULL,
	[TravelMatrixId] Integer NOT NULL,
	[FromGateId] Integer NOT NULL,
	[ToGateId] Integer NOT NULL,
	[TravelTime] Smallint NULL,
  Primary Key ([TravelTimeId],[TravelMatrixId])
  ) 
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_TravelTime'
	          AND CONSTRAINT_NAME = N'fk_CNF_TravelTime_FromGateId')          
BEGIN
  ALTER TABLE CNF_TravelTime WITH CHECK
  ADD CONSTRAINT [fk_CNF_TravelTime_FromGateId] FOREIGN KEY([FromGateId])
  REFERENCES [ADM_Gate] ([GateId])
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_TravelTime'
	          AND CONSTRAINT_NAME = N'fk_CNF_TravelTime_ToGateId')          
BEGIN
  ALTER TABLE CNF_TravelTime WITH CHECK
  ADD CONSTRAINT [fk_CNF_TravelTime_ToGateId] FOREIGN KEY([ToGateId])
  REFERENCES [ADM_Gate] ([GateId])
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>jlaguardia</ADDEDBY>
			<SQLVERSION>2312</SQLVERSION>
			<RMTRACKLINK>70911</RMTRACKLINK>
			<REASON>Droppped and re-added DATA_PaymentHotel</REASON>
			<TABLENAMES>DATA_PaymentHotel=PaymentHotelId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS ( SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND  TABLE_NAME = 'DATA_PaymentHotel' )

BEGIN
  drop table DATA_PaymentHotel
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS ( SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND  TABLE_NAME = 'DATA_PaymentHotel' )

BEGIN
Create table DATA_PaymentHotel
(
	[PaymentHotelId] Integer Identity(1,1) NOT NULL,
	[PaymentId] Integer NOT NULL,
	[RawRequest] Varchar(1000) NULL,
	[RawAnswer] Varchar(1000) NULL,
	[HotelTransactionId] Integer NULL,
	[SequenceNumber] Integer NULL,
	[ResponseStatus] Ntext NULL,
	[ResponseText] Ntext NULL,
	[RoomNumber] Varchar(1000) NULL,
	[GuestLastName] Varchar(1000) NULL,
	[HotelReservationId] Varchar(1000) NULL,
	[PaymentStatus] Smallint NULL,
Primary Key ([PaymentHotelId])
) 
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'DATA_PaymentHotel'
	          AND CONSTRAINT_NAME = N'fk_DATA_PaymentHotel_PaymentId')          
BEGIN
  ALTER TABLE DATA_PaymentHotel WITH CHECK
  ADD CONSTRAINT [fk_DATA_PaymentHotel_PaymentId] FOREIGN KEY([PaymentId])
  REFERENCES [DATA_Payment] ([PaymentId])
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>mkimball</ADDEDBY>
			<SQLVERSION>2311</SQLVERSION>
			<RMTRACKLINK>70363</RMTRACKLINK>
			<REASON>add ResourceAK to RES_CNF_Resource</REASON>
			<TABLENAMES>RES_CNF_Resource=ResourceId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'ResourceAK' AND
                Object_ID  = Object_ID(N'RES_CNF_Resource'))
BEGIN
  ALTER TABLE RES_CNF_Resource ADD ResourceAK Nvarchar(32) NOT NULL DEFAULT SUBSTRING(CONVERT(VARCHAR(36), NEWID()), 1, 32)
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>kdixon</ADDEDBY>
			<SQLVERSION>2310</SQLVERSION>
			<RMTRACKLINK>71376</RMTRACKLINK>
			<REASON>Chart of Accounts-Phase 2 - Sprint 3</REASON>
			<TABLENAMES>CNF_PaymentMethod=PaymentMethodID</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'FixedVoucherCOAAccountId' AND
                Object_ID  = Object_ID(N'CNF_PaymentMethod'))
BEGIN
	Alter Table CNF_PaymentMethod
	Add FixedVoucherCOAAccountId Integer NULL
END
</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>jlaguardia</ADDEDBY>
			<SQLVERSION>2309</SQLVERSION>
			<RMTRACKLINK>70348</RMTRACKLINK>
			<REASON>Change name of EventTemplateNotifcation driver to BOSNotification</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>update sh set Configuration = null from CNF_Scheduler sh
inner join CNF_Driver dr on dr.DriverId = sh.DriverId
where dr.DriverAk = 'TDrvJobEventTemplateNotification'</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_Driver set DriverAk = 'TDrvJobBOSNotification', Description = 'BOS Notifications'
where DriverAk = 'TDrvJobEventTemplateNotification'</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>jlaguardia</ADDEDBY>
			<SQLVERSION>2308</SQLVERSION>
			<RMTRACKLINK>70348</RMTRACKLINK>
			<REASON>Added column to CNF_Notification
  +NotificationType smallint notnull default 1
Added column to ADM_AccessConfiguration
 +AllowNotification smallint null
</REASON>
			<TABLENAMES>CNF_Notification=NotificationId
ADM_AccessConfiguration=AccessConfigurationId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'NotificationType' AND
                Object_ID  = Object_ID(N'CNF_Notification'))
BEGIN
  alter table CNF_Notification 
  add NotificationType smallint not null default 1
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'AllowNotification' AND
                Object_ID  = Object_ID(N'ADM_AccessConfiguration'))
BEGIN
  alter table ADM_AccessConfiguration 
  add AllowNotification smallint null
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>kdixon</ADDEDBY>
			<SQLVERSION>2307</SQLVERSION>
			<RMTRACKLINK>71176</RMTRACKLINK>
			<REASON>COA2   Sprint 2</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_RR_RevenueData_OnCreditSettlementTrigger]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_RR_RevenueData_OnCreditSettlementTrigger
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE Procedure dbo.otn_sp_RR_RevenueData_OnCreditSettlementTrigger
	@BatchDate Date,
	@RRTransDateType Integer
AS 
BEGIN


	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer
	Declare @OnCreditSettlementTrigger Integer = 8

	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1

	BEGIN
		--Normal Transaction No Remaining Values
			INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[Saleitemid]
				   ,[MatrixCellid]
				   ,[MatrixCellCode]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				   ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])
				   select *
				   from (
					select distinct p.COAAccountId, 
								p.RevenueRecognitionRuleId,
								p.code,		   
								p.RRCalcTypeWhere,
								p.RRCalcTypeMethod,	   
								p.COAAccountConfigId,
								p.COAAccountTypeId,
								p.AccountCode,
								RR_DATA_REVENUE.Transactionid as Transactionid,
								RR_DATA_REVENUE.saleid as Saleid,
								RR_DATA_REVENUE.SaleitemID as SaleitemID,
								RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								RR_DATA_REVENUE.MatrixcellCode as MatrixCode,
								RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								RR_DATA_REVENUE.Siteid as SiteID,
								RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								RR_DATA_REVENUE.Workstationid as Workstationid,
								RR_DATA_REVENUE.UserGroupid as UserGroupID,
								RR_DATA_REVENUE.UserId as userID,
								@BatchDate as BatchDate,
								case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
								     else DATA_Transaction.transactiondate
								  end as TransDate,
								RR_DATA_REVENUE.Quantity as Quantity,
								RR_DATA_REVENUE.GrossAmount as GrossAmount,
								RR_DATA_REVENUE.NetAmount as NetAmount,
								p.Price as ConfigPrice,
								p.Percentage as ConfigPercentage,
								p.RemainingValues,
								(CASE WHEN p.coaaccountid not in (@ACCPaymentMethod, @TaxAccountID, @DiscountAccountID) then   --Accounts not Tax not PaymentMethods 
									Case when p.Price &gt; 0 then (p.Price * RR_DATA_REVENUE.Quantity) 
											else (ISNULL((((ABS(RR_DATA_REVENUE.RevenueAmount)) - ISNULL((select (ABS((sum(TaxAmount) * RR_DATA_REVENUE.Quantity)))
																									from data_saleitemTax
																									where saleitemid = RR_DATA_REVENUE.SaleitemID), 0)) * p.Percentage/100), 0))
									end 																		                                                                                                                                                                                              
								end)  as RevenueAmount,
								 p.Accountingtype,
									p.RRCalcTypeTrigger,
									p.rrPercentage,
									p.Days						
						
						
							from RR_DATA_REVENUE
								INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
								INNER JOIN (select '1' as PCOAAccountid, 
												   coa_cnf_accountConfig.Siteid, 
												   RR_CNF_RevenueRecognitionRule.Enabled, 
												   RR_CNF_RevenueRecognitionRule.FromDate, 
												   RR_CNF_RevenueRecognitionRule.ToDate,
												   COA_CNF_AccountConfig.RemainingValues,
												   coa_cnf_account.coaaccountid,
												   COA_CNF_AccountConfig.Price,
												   COA_CNF_AccountConfig.Percentage,
												   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
												   RR_CNF_RevenueRecognitionRule.code,		   
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
												   COA_CNF_AccountConfig.COAAccountConfigId,
												   coa_cnf_account.COAAccountTypeId,
												   coa_cnf_account.Code as accountcode,
												   coa_cnf_accountconfig.Accountingtype,
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
												   RR_CNF_RevenueRecognitionRule.Percentage rrPercentage,
												   RR_CNF_RevenueRecognitionRule.Days	

												from RR_CNF_RevenueRecognitionRule	
												INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
												INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid and coa_cnf_account.Enabled = 1
												INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
											where  RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @OnCreditSettlementTrigger
											and RR_CNF_RevenueRecognitionRule.Enabled = 1
											and coa_cnf_account.coaaccountid not in (@ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)) p				on p.PCOAAccountid = rr_data_revenue.coaaccountid 

							where transactiontype in (6)												 
								and p.Enabled = 1
								and ((p.Siteid = RR_DATA_REVENUE.Siteid) or (p.Siteid is null))
								and @BatchDate between p.FromDate and p.ToDate
								and p.RemainingValues &lt;&gt; 1
								and RR_DATA_REVENUE.fcalcdate = @BatchDate
					)r 
					where r.revenueAmount &lt;&gt; 0


				--Normal Transaction with Remaining Values
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[Saleitemid]
				   ,[MatrixCellid]
				   ,[MatrixCellCode]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])
				   select *
				   from (
					select distinct p.COAAccountId, 
								p.RevenueRecognitionRuleId,
								p.code,		   
								p.RRCalcTypeWhere,
								p.RRCalcTypeMethod,	   
								p.COAAccountConfigId,
								p.COAAccountTypeId,
								p.AccountCode,
								RR_DATA_REVENUE.Transactionid as Transactionid,
								RR_DATA_REVENUE.saleid as Saleid,
								RR_DATA_REVENUE.SaleitemID as SaleitemID,
								RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								RR_DATA_REVENUE.MatrixcellCode as MatrixCode,
								RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								RR_DATA_REVENUE.Siteid as SiteID,
								RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								RR_DATA_REVENUE.Workstationid as Workstationid,
								RR_DATA_REVENUE.UserGroupid as UserGroupID,
								RR_DATA_REVENUE.UserId as userID,
								@BatchDate as BatchDate,
								case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
								     else DATA_Transaction.transactiondate
								  end as TransDate,
								RR_DATA_REVENUE.Quantity as Quantity,
								RR_DATA_REVENUE.GrossAmount as GrossAmount,
								RR_DATA_REVENUE.NetAmount as NetAmount,
								p.Price as ConfigPrice,
								p.Percentage as ConfigPercentage,
								p.RemainingValues,
								CASE WHEN p.coaaccountid not in (@ACCPaymentMethod, @TaxAccountID, @DiscountAccountID) then																																													 
							    ABS(ABS(RR_DATA_REVENUE.RevenueAmount) -					 
								ISNULL((select ABS(sum(RevenueAmount))
										from RR_DATA_Revenue rrd
									    where rrd.RevenueRecognitionRuleId = p.RevenueRecognitionRuleId
										and rrd.RevenueRecognitionRuleId not in (@SuspendID, @ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)
										and rrd.transactionid = RR_DATA_REVENUE.transactionid
								), 0)) 
								else 0
								end RevenueAmount,
								p.Accountingtype,
									p.RRCalcTypeTrigger,
									p.rrPercentage,
									p.Days						
						
						
							from RR_DATA_REVENUE
								INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
								INNER JOIN (select '1' as PCOAAccountid, 
												   coa_cnf_accountConfig.Siteid, 
												   RR_CNF_RevenueRecognitionRule.Enabled, 
												   RR_CNF_RevenueRecognitionRule.FromDate, 
												   RR_CNF_RevenueRecognitionRule.ToDate,
												   COA_CNF_AccountConfig.RemainingValues,
												   coa_cnf_account.coaaccountid,
												   COA_CNF_AccountConfig.Price,
												   COA_CNF_AccountConfig.Percentage,
												   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
												   RR_CNF_RevenueRecognitionRule.code,		   
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
												   COA_CNF_AccountConfig.COAAccountConfigId,
												   coa_cnf_account.COAAccountTypeId,
												   coa_cnf_account.Code as accountcode,
												   coa_cnf_accountconfig.Accountingtype,
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
												   RR_CNF_RevenueRecognitionRule.Percentage rrPercentage,
												   RR_CNF_RevenueRecognitionRule.Days	

												from RR_CNF_RevenueRecognitionRule	
												INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
												INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid and coa_cnf_account.Enabled = 1
												INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
											where  RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @OnCreditSettlementTrigger
											and RR_CNF_RevenueRecognitionRule.Enabled = 1
											and coa_cnf_account.coaaccountid not in (@ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)) p				on p.PCOAAccountid = rr_data_revenue.coaaccountid 

							where transactiontype in (6)																				 
								and p.Enabled = 1
								and ((p.Siteid = RR_DATA_REVENUE.Siteid) or (p.Siteid is null))
								and @BatchDate between p.FromDate and p.ToDate
								and p.RemainingValues = 1
								and RR_DATA_REVENUE.fcalcdate = @BatchDate		
					)r 
					where r.revenueAmount &lt;&gt; 0

	end

END
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_RR_RevenueData_SettleUpSuspendAccount]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_RR_RevenueData_SettleUpSuspendAccount
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE Procedure dbo.otn_sp_RR_RevenueData_SettleUpSuspendAccount
	@BatchDate Date,
	@RRTransDateType Integer
AS 
BEGIN
	Declare @SuspendRRRId Integer
	Declare @SuspendCOAAccountId Integer
	Declare @SuspendRRRCode varchar(10)
	Declare @SuspendRRCalcTypeTrigger Integer
	Declare @SuspendRRCalcTypeWhere Integer
	Declare @SuspendRRCalcTypeMethod Integer
	Declare @SuspendCOAAccountConfigId Integer
	Declare @SuspendCOAAccountTypeId Integer
	Declare @SuspendCOAAccountCode varchar(10)
	Declare @SuspendPercentage float
	Declare @SuspendDays Integer
	Declare @SuspendPrice float
	Declare @SuspendCOAAccount_Percentage Float
	Declare @SuspendRemainingValues Integer
	Declare @SuspendRRCOAAccountingType Integer

	Declare @TransactionID Integer
	Declare @TransactionType Integer
	Declare @FCalcDate date
	Declare @UsageID Integer
	Declare @TicketID Integer
	Declare @UsagePrice float
	Declare @AmountLeft float

	Declare @saleid Integer
	Declare @Siteid Integer
	Declare @OperatingAreaId Integer
	Declare @Workstationid Integer
	Declare @UserGroupid Integer
	Declare @UserId Integer
	Declare @Quantity Integer
	Declare @GrossAmount Float
	Declare @NetAmount Float
	Declare @RevenueAmount Float
	Declare @PaymentMethod Integer
	Declare @PaymentAmount Float
	Declare @TransDate Date
	Declare @Matrixcell Integer
	Declare @MatrixcellCode varchar(10)
	Declare @MatrixSheetId Integer 
	Declare @SaleitemID Integer
	Declare @PaymentDriver Integer

	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer
	Declare @UsageTrigger Integer = 2
	Declare @DepositTrigger Integer = 5
	Declare @MoneyRefund Integer = 6
	Declare @OnSaleTrigger Integer = 1
	Declare @OnAdvancePaymentTrigger Integer = 7
	Declare @SuspendRule Integer
	Declare @StartTime DateTime

	Set @StartTime = Getdate();
	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @SuspendRule = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleid
	from coa_cnf_account
		INNER JOIN COA_CNF_AccountType				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
		INNER JOIN COA_CNF_AccountConfig			on COA_CNF_AccountConfig.COAAccountId = coa_cnf_account.COAAccountId
		INNER JOIN RR_CNF_RevenueRecognitionRule	on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId
	where coa_cnf_account.COAAccountID = @SuspendID

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1

	select @SuspendRRRId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
		   @SuspendRRRCode = RR_CNF_RevenueRecognitionRule.code,
		   @SuspendRRCalcTypeTrigger = RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
		   @SuspendRRCalcTypeWhere = RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
		   @SuspendRRCalcTypeMethod = RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
		   @SuspendCOAAccountConfigId = COA_CNF_AccountConfig.COAAccountConfigId,
		   @SuspendCOAAccountTypeId = COA_CNF_AccountType.COAAccountTypeId,
		   @SuspendCOAAccountId = coa_cnf_account.COAAccountId,
		   @SuspendPercentage = RR_CNF_RevenueRecognitionRule.Percentage,
		   @SuspendDays = RR_CNF_RevenueRecognitionRule.Days,
		   @SuspendPrice = COA_CNF_AccountConfig.Price,
		   @SuspendCOAAccount_Percentage = COA_CNF_AccountConfig.Percentage,
		   @SuspendRemainingValues = COA_CNF_AccountConfig.RemainingValues,
		   @SuspendCOAAccountCode = coa_cnf_account.Code,
		   @SuspendRRCOAAccountingType = COA_CNF_AccountConfig.AccountingType

	from coa_cnf_account
		INNER JOIN COA_CNF_AccountType				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
		INNER JOIN COA_CNF_AccountConfig			on COA_CNF_AccountConfig.COAAccountId = coa_cnf_account.COAAccountId
		INNER JOIN RR_CNF_RevenueRecognitionRule	on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId
	where coa_cnf_account.COAAccountID = @SuspendID
	  and RR_CNF_RevenueRecognitionRule.enabled = 1
	  and COA_CNF_AccountConfig.enabled = 1


	update rr_data_revenue
	   set revenueamount = abs(revenueamount)		   
	 where FCalcDate = @BatchDate
	   and coaaccountid = @SuspendID

	BEGIN
		
			INSERT INTO [dbo].[RR_DATA_Revenue]
					   ([COAAccountId]
					   ,[RevenueRecognitionRuleId]
					   ,[RRCode]
					   ,[RRCalcTypeWhere]
					   ,[RRCalcTypeMethod]
					   ,[COAAccountConfigId]
					   ,[COAAccountType]
					   ,[COAAccountCode]
					   ,[TransactionId]
					   ,[SaleId]
					   ,[SiteId]
					   ,[OperatingAreaId]
					   ,[WorkstationId]
					   ,[UserGroupId]
					   ,[UserId]
					   ,[FCalcDate]
					   ,[FRevenueDate]
					   ,[Quantity]
					   ,[GrossAmount]
					   ,[NetAmount]
					   ,[Price]
					   ,[Percentage]
					   ,[RemaningValues]
					   ,[RevenueAmount]
					   ,[AccountingType]
					   ,[RRCalcTypeTrigger]
					   ,[RRPercentage]
					   ,[RRDays]
					   ,[AttributeIDs])
				select SuspendCOAAccountId,
					   SuspendRRRId,
					   SuspendRRRCode,
					   SuspendRRCalcTypeWhere,
					   SuspendRRCalcTypeMethod,
					   SuspendCOAAccountConfigId,
					   SuspendCOAAccountTypeId,
					   SuspendCOAAccountCode,
					   Transactionid,
					   saleid,
					   Siteid,
					   OperatingAreaId,
					   Workstationid,
					   UserGroupid,
					   UserId,
					   BatchDate,
					   TransDate,
					   0,
					   GrossAmount,
					   NetAmount,
					   SuspendPrice,
					   percentage,
					   RemainingValues,
					   sum(ABS(RevenueAmount)),
					   case when accountingtype = 1 then 2
					        else 1
						end Accountingtype,
					   rrtrigger,
					   percentage2,
					   rrdays,
					   AttributeIDs
				from (
				select distinct @SuspendCOAAccountId SuspendCOAAccountId,
					   @SuspendRRRId SuspendRRRId,
					   @SuspendRRRCode SuspendRRRCode,
					   @SuspendRRCalcTypeWhere SuspendRRCalcTypeWhere,
					   @SuspendRRCalcTypeMethod SuspendRRCalcTypeMethod,
					   @SuspendCOAAccountConfigId SuspendCOAAccountConfigId,
					   @SuspendCOAAccountTypeId SuspendCOAAccountTypeId,
					   @SuspendCOAAccountCode SuspendCOAAccountCode,
					   RR_DATA_Revenue.Transactionid Transactionid,
					   RR_DATA_Revenue.saleid saleid,
					   RR_DATA_Revenue.SaleItemid saleitemid,
					   RR_DATA_Revenue.Matrixcellid Matrixcell,
					   RR_DATA_Revenue.MatrixcellCode MatrixcellCode,
					   RR_DATA_Revenue.MatrixSheetId MatrixSheetId,
					   RR_DATA_Revenue.Siteid Siteid,
					   RR_DATA_Revenue.OperatingAreaId OperatingAreaId,
					   RR_DATA_Revenue.Workstationid Workstationid,
					   @UserGroupid UserGroupid,
					   RR_DATA_Revenue.UserId UserId,
					   @BatchDate BatchDate,
						case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
							else DATA_Transaction.transactiondate
						end as TransDate,
					   0 GrossAmount,
					   0 NetAmount,
					   @SuspendPrice SuspendPrice,
					   @SuspendCOAAccount_Percentage percentage,
					   @SuspendRemainingValues RemainingValues,
					   case when RR_DATA_Revenue.RRCalcTypeTrigger = 5 and data_transaction.transactiontype &lt;&gt; 12 then 0
					        else RevenueAmount
						end RevenueAmount, 
					   ISNULL((select top 1 AccountingType 
								  from rr_data_revenue tt
								  where tt.COAAccountId = @SuspendID
									and tt.transactionid = rr_data_revenue.transactionid
									and tt.saleitemid = rr_data_revenue.saleitemid),
								(select top 1 AccountingType 
								  from rr_data_revenue tt
								  where tt.COAAccountId = @SuspendID
									and tt.transactionid = rr_data_revenue.transactionid)
								)	 as Accountingtype,
					   @SuspendRRCalcTypeTrigger rrtrigger,
					   @SuspendPercentage percentage2,
					   @SuspendDays rrdays,
					   RR_DATA_Revenue.AttributeIDs
	  
				from RR_DATA_Revenue
						INNER JOIN data_transaction					on data_transaction.transactionid = rr_data_revenue.transactionid
						LEFT JOIN DATA_SaleItem					on data_saleitem.saleid = data_transaction.saleid
				   where TransactionType in (5, 6, 7, 8, 9, 10, 12, 13, 14, 18, 20, 22, 16, 30, 31, 34, 42, 43, 48, 49, 52) 
				     and rr_data_revenue.fcalcdate = @BatchDate
					 and rr_data_revenue.RevenueRecognitionRuleId &lt;&gt; @SuspendRRRId
					 and rr_data_revenue.coaaccountid not in (@SuspendID, @ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)
				)p	
				
				group by   SuspendCOAAccountId,
						   SuspendRRRId,
						   SuspendRRRCode,
						   SuspendRRCalcTypeWhere,
						   SuspendRRCalcTypeMethod,
						   SuspendCOAAccountConfigId,
						   SuspendCOAAccountTypeId,
						   SuspendCOAAccountCode,
						   Transactionid,
						   saleid,
						   Siteid,
						   OperatingAreaId,
						   Workstationid,
						   UserGroupid,
						   UserId,
						   BatchDate,
						   TransDate,
						   GrossAmount,
						   NetAmount,
						   SuspendPrice,
						   percentage,
						   RemainingValues,
						   accountingtype,
						   rrtrigger,
						   percentage2,
					       rrdays,
						   AttributeIDs									  																			
	end
END
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_RR_RevenueData_batchJob]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_RR_RevenueData_batchJob
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE Procedure dbo.otn_sp_RR_RevenueData_batchJob	 
	@BatchDate Date
AS 
BEGIN
	Declare @RRTransDateType Integer


	Declare @SuspendRRRId Integer
	Declare @SuspendCOAAccountId Integer
	Declare @SuspendRRRCode varchar(10)
	Declare @SuspendRRCalcTypeTrigger Integer
	Declare @SuspendRRCalcTypeWhere Integer
	Declare @SuspendRRCalcTypeMethod Integer
	Declare @SuspendCOAAccountConfigId Integer
	Declare @SuspendCOAAccountTypeId Integer
	Declare @SuspendCOAAccountCode varchar(10)
	Declare @SuspendPercentage float
	Declare @SuspendDays Integer
	Declare @SuspendPrice float
	Declare @SuspendCOAAccount_Percentage Float
	Declare @SuspendRemainingValues Integer
	Declare @SuspendRRCOAAccountingType Integer
	Declare @SuspendAccountingType Integer

	Declare @PaymentRRRId Integer
	Declare @PaymentCOAAccountId Integer
	Declare @PaymentRRRCode varchar(10)
	Declare @PaymentRRCalcTypeTrigger Integer
	Declare @PaymentRRCalcTypeWhere Integer
	Declare @PaymentRRCalcTypeMethod Integer
	Declare @PaymentCOAAccountConfigId Integer
	Declare @PaymentCOAAccountTypeId Integer
	Declare @PaymentCOAAccountCode varchar(10)
	Declare @PaymentPercentage float
	Declare @PaymentDays Integer
	Declare @PaymentPrice float
	Declare @PaymentCOAAccount_Percentage Float
	Declare @PaymentRemainingValues Integer
	Declare @PaymentRRCOAAccountingType Integer
	Declare @PaymentAccountingType Integer


	Declare @TaxRRRId Integer
	Declare @TaxCOAAccountId Integer
	Declare @TaxRRRCode varchar(10)
	Declare @TaxRRCalcTypeTrigger Integer
	Declare @TaxRRCalcTypeWhere Integer
	Declare @TaxRRCalcTypeMethod Integer
	Declare @TaxCOAAccountConfigId Integer
	Declare @TaxCOAAccountTypeId Integer
	Declare @TaxCOAAccountCode varchar(10)
	Declare @TaxPercentage float
	Declare @TaxDays Integer
	Declare @TaxPrice float
	Declare @TaxCOAAccount_Percentage Float
	Declare @TaxRemainingValues Integer
	Declare @TaxRRCOAAccountingType Integer
	Declare @TaxAccountingType Integer


	Declare @DiscountRRRId Integer
	Declare @DiscountCOAAccountId Integer
	Declare @DiscountRRRCode varchar(10)
	Declare @DiscountRRCalcTypeTrigger Integer
	Declare @DiscountRRCalcTypeWhere Integer
	Declare @DiscountRRCalcTypeMethod Integer
	Declare @DiscountCOAAccountConfigId Integer
	Declare @DiscountCOAAccountTypeId Integer
	Declare @DiscountCOAAccountCode varchar(10)
	Declare @DiscountPercentage float
	Declare @DiscountDays Integer
	Declare @DiscountPrice float
	Declare @DiscountCOAAccount_Percentage Float
	Declare @DiscountRemainingValues Integer
	Declare @DiscountRRCOAAccountingType Integer
	Declare @DiscountAccountingType Integer

	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer

	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1

	delete from rr_data_revenue
	where fcalcdate = @BatchDate 


	select @RRTransDateType = RRTransDateType
      from cnf_system

--Begin Move Transactions to Suspend Account
	select TOP 1 @SuspendRRRId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
			@SuspendRRRCode = RR_CNF_RevenueRecognitionRule.code,
			@SuspendRRCalcTypeTrigger = RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
			@SuspendRRCalcTypeWhere = RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
			@SuspendRRCalcTypeMethod = RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
			@SuspendCOAAccountConfigId = COA_CNF_AccountConfig.COAAccountConfigId,
			@SuspendCOAAccountTypeId = COA_CNF_AccountType.COAAccountTypeId,
			@SuspendCOAAccountId = coa_cnf_account.COAAccountId,
			@SuspendPercentage = RR_CNF_RevenueRecognitionRule.Percentage,
			@SuspendDays = RR_CNF_RevenueRecognitionRule.Days,
			@SuspendPrice = COA_CNF_AccountConfig.Price,
			@SuspendCOAAccount_Percentage = COA_CNF_AccountConfig.Percentage,
			@SuspendRemainingValues = COA_CNF_AccountConfig.RemainingValues,
			@SuspendCOAAccountCode = coa_cnf_account.Code,
			@SuspendRRCOAAccountingType = COA_CNF_AccountConfig.AccountingType
	from coa_cnf_account
		INNER JOIN COA_CNF_AccountType				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
		INNER JOIN COA_CNF_AccountConfig			on COA_CNF_AccountConfig.COAAccountId = coa_cnf_account.COAAccountId
		INNER JOIN RR_CNF_RevenueRecognitionRule	on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId
	where coa_cnf_account.COAAccountID = @SuspendID
	 order by RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId

	select TOP 1 @PaymentRRRId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
			@PaymentRRRCode = RR_CNF_RevenueRecognitionRule.code,
			@PaymentRRCalcTypeTrigger = RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
			@PaymentRRCalcTypeWhere = RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
			@PaymentRRCalcTypeMethod = RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
			@PaymentCOAAccountConfigId = COA_CNF_AccountConfig.COAAccountConfigId,
			@PaymentCOAAccountTypeId = COA_CNF_AccountType.COAAccountTypeId,
			@PaymentCOAAccountId = coa_cnf_account.COAAccountId,
			@PaymentPercentage = RR_CNF_RevenueRecognitionRule.Percentage,
			@PaymentDays = RR_CNF_RevenueRecognitionRule.Days,
			@PaymentPrice = COA_CNF_AccountConfig.Price,
			@PaymentCOAAccount_Percentage = COA_CNF_AccountConfig.Percentage,
			@PaymentRemainingValues = COA_CNF_AccountConfig.RemainingValues,
			@PaymentCOAAccountCode = coa_cnf_account.Code,
			@PaymentRRCOAAccountingType = COA_CNF_AccountConfig.AccountingType
	from coa_cnf_account
		INNER JOIN COA_CNF_AccountType				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
		INNER JOIN COA_CNF_AccountConfig			on COA_CNF_AccountConfig.COAAccountId = coa_cnf_account.COAAccountId
		INNER JOIN RR_CNF_RevenueRecognitionRule	on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId
	where coa_cnf_account.COAAccountID = @ACCPaymentMethod
	 order by RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId

	select TOP 1 @TaxRRRId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
			@TaxRRRCode = RR_CNF_RevenueRecognitionRule.code,
			@TaxRRCalcTypeTrigger = RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
			@TaxRRCalcTypeWhere = RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
			@TaxRRCalcTypeMethod = RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
			@TaxCOAAccountConfigId = COA_CNF_AccountConfig.COAAccountConfigId,
			@TaxCOAAccountTypeId = COA_CNF_AccountType.COAAccountTypeId,
			@TaxCOAAccountId = coa_cnf_account.COAAccountId,
			@TaxPercentage = RR_CNF_RevenueRecognitionRule.Percentage,
			@TaxDays = RR_CNF_RevenueRecognitionRule.Days,
			@TaxPrice = COA_CNF_AccountConfig.Price,
			@TaxCOAAccount_Percentage = COA_CNF_AccountConfig.Percentage,
			@TaxRemainingValues = COA_CNF_AccountConfig.RemainingValues,
			@TaxCOAAccountCode = coa_cnf_account.Code,
			@TaxRRCOAAccountingType = COA_CNF_AccountConfig.AccountingType
	from coa_cnf_account
		INNER JOIN COA_CNF_AccountType				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
		INNER JOIN COA_CNF_AccountConfig			on COA_CNF_AccountConfig.COAAccountId = coa_cnf_account.COAAccountId
		INNER JOIN RR_CNF_RevenueRecognitionRule	on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId
	where coa_cnf_account.COAAccountID = @TaxAccountID
	 order by RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId

	select TOP 1 @DiscountRRRId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
			@DiscountRRRCode = RR_CNF_RevenueRecognitionRule.code,
			@DiscountRRCalcTypeTrigger = RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
			@DiscountRRCalcTypeWhere = RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
			@DiscountRRCalcTypeMethod = RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
			@DiscountCOAAccountConfigId = COA_CNF_AccountConfig.COAAccountConfigId,
			@DiscountCOAAccountTypeId = COA_CNF_AccountType.COAAccountTypeId,
			@DiscountCOAAccountId = coa_cnf_account.COAAccountId,
			@DiscountPercentage = RR_CNF_RevenueRecognitionRule.Percentage,
			@DiscountDays = RR_CNF_RevenueRecognitionRule.Days,
			@DiscountPrice = COA_CNF_AccountConfig.Price,
			@DiscountCOAAccount_Percentage = COA_CNF_AccountConfig.Percentage,
			@DiscountRemainingValues = COA_CNF_AccountConfig.RemainingValues,
			@DiscountCOAAccountCode = coa_cnf_account.Code,
			@DiscountRRCOAAccountingType = COA_CNF_AccountConfig.AccountingType
	from coa_cnf_account
		INNER JOIN COA_CNF_AccountType				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
		INNER JOIN COA_CNF_AccountConfig			on COA_CNF_AccountConfig.COAAccountId = coa_cnf_account.COAAccountId
		INNER JOIN RR_CNF_RevenueRecognitionRule	on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId
	where coa_cnf_account.COAAccountID = @DiscountAccountID
	 order by RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId

INSERT INTO [dbo].[RR_DATA_Revenue]
				([COAAccountId]
				,[RevenueRecognitionRuleId]
				,[RRCode]
				,[RRCalcTypeWhere]
				,[RRCalcTypeMethod]
				,[COAAccountConfigId]
				,[COAAccountType]
				,[COAAccountCode]
				,[TransactionId]
				,[SaleId]
				,[SaleItemId]
				,[MatrixCellId]
				,[MatrixCellCode]
				,[MatrixSheetID]
				,[SiteId]
				,[OperatingAreaId]
				,[WorkstationId]
				,[UserGroupId]
				,[UserId]
				,[FCalcDate]
				,[FRevenueDate]
				,[Quantity]
				,[UnitAmount]
				,[GrossAmount]
				,[NetAmount]
				,[Price]
				,[Percentage]
				,[RemaningValues]
				,[RevenueAmount]
				,[AccountingType]
				,[RRCalcTypeTrigger]
				,[RRPercentage]
				,[RRDays]
				,[AttributeIDS])
		select @SuspendCOAAccountId,
				@SuspendRRRId,
				@SuspendRRRCode,
				@SuspendRRCalcTypeWhere,
				@SuspendRRCalcTypeMethod,
				@SuspendCOAAccountConfigId,
				@SuspendCOAAccountTypeId,
				@SuspendCOAAccountCode,
				data_transaction.transactionid, 
				data_transaction.saleid,
				DATA_TransactionItem.saleitemid,
				DATA_SaleItem.Matrixcellid,
				CNF_MatrixCell.Code,
				CNF_MatrixCell.MatrixSheetid,
				data_transaction.Siteid,
				data_transaction.OperatingAreaId,
				data_transaction.Workstationid,
				data_transaction.UserGroupid,
				data_transaction.UserId,
				@BatchDate,
				CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
				     else data_transaction.TransactionDate
				end TransactionDate,
				Coalesce(DATA_TransactionItem.Quantity, 1),
				DATA_SaleItem.UnitPrice,
				case when isnull(DATA_TransactionItem.TotalAmount, 0) &lt;&gt; 0 then DATA_TransactionItem.TotalAmount
					when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
					else DATA_Sale.TotalAmount
				end,
				case when isnull((DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes)
					when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
					else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
				end as NetAmount,
				@SuspendPrice,
				@SuspendCOAAccount_Percentage,
				@SuspendRemainingValues,
				case    when (data_saleitem.ProductTaxType &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice ) * DATA_SaleItem.Quantity)
						when (data_saleitem.ProductTaxType = 1) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice - DATA_SaleItem.unittaxes) * DATA_SaleItem.Quantity)
						when (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 then 0				
						when isnull((data_transaction.TotalAmount), 0) &lt;&gt; 0 then data_transaction.TotalAmount
						when isnull((DATA_Sale.TotalAmount), 0) &lt;&gt; 0 then DATA_Sale.TotalAmount
						else (data_transaction.Revenue)
				end,
				case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
						when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
						when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 1
						when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 2
						else @SuspendRRCOAAccountingType
				end Accountingtype,
				@SuspendRRCalcTypeTrigger,
				@SuspendPercentage,
				@SuspendDays,
				CNF_AttributeSet.Attributeids
	   
		from DATA_Sale
			inner join data_transaction			on data_transaction.TransactionId = DATA_Sale.PaidTransactionId
			left join DATA_TransactionItem		on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
			left join DATA_SaleItem			    on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
			left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
			left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

		where DATA_Sale.Paid = 1
			and data_transaction.transactiontype in (14)
			and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
			   OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
			and data_transaction.transactionid in (select transactionid
													from data_payment
													where PaymentStatus = 1
													and PaymentAmount &lt;&gt; 0
												)

INSERT INTO [dbo].[RR_DATA_Revenue]
				([COAAccountId]
				,[RevenueRecognitionRuleId]
				,[RRCode]
				,[RRCalcTypeWhere]
				,[RRCalcTypeMethod]
				,[COAAccountConfigId]
				,[COAAccountType]
				,[COAAccountCode]
				,[TransactionId]
				,[SaleId]
				,[SaleItemId]
				,[MatrixCellId]
				,[MatrixCellCode]
				,[MatrixSheetID]
				,[SiteId]
				,[OperatingAreaId]
				,[WorkstationId]
				,[UserGroupId]
				,[UserId]
				,[FCalcDate]
				,[FRevenueDate]
				,[Quantity]
				,[UnitAmount]
				,[GrossAmount]
				,[NetAmount]
				,[Price]
				,[Percentage]
				,[RemaningValues]
				,[RevenueAmount]
				,[AccountingType]
				,[RRCalcTypeTrigger]
				,[RRPercentage]
				,[RRDays]
				,[AttributeIDS])
		select @SuspendCOAAccountId,
				@SuspendRRRId,
				@SuspendRRRCode,
				@SuspendRRCalcTypeWhere,
				@SuspendRRCalcTypeMethod,
				@SuspendCOAAccountConfigId,
				@SuspendCOAAccountTypeId,
				@SuspendCOAAccountCode,
				data_transaction.transactionid, 
				data_transaction.saleid,
				DATA_TransactionItem.saleitemid,
				DATA_SaleItem.Matrixcellid,
				CNF_MatrixCell.Code,
				CNF_MatrixCell.MatrixSheetid,
				data_transaction.Siteid,
				data_transaction.OperatingAreaId,
				data_transaction.Workstationid,
				data_transaction.UserGroupid,
				data_transaction.UserId,
				@BatchDate,
				CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
				     else data_transaction.TransactionDate
				end TransactionDate,
				Coalesce(DATA_TransactionItem.Quantity, 1),
				DATA_SaleItem.UnitPrice,
				case when isnull(DATA_TransactionItem.TotalAmount, 0) &lt;&gt; 0 then DATA_TransactionItem.TotalAmount
					when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
					else DATA_Sale.TotalAmount
				end,
				case when isnull((DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes)
					when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
					else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
				end as NetAmount,
				@SuspendPrice,
				@SuspendCOAAccount_Percentage,
				@SuspendRemainingValues,
				DATA_SaleItem.UnitRecharge * data_saleitem.Quantity,
				case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
						when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
						when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 1
						when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 2
						else @SuspendRRCOAAccountingType
				end Accountingtype,
				@SuspendRRCalcTypeTrigger,
				@SuspendPercentage,
				@SuspendDays,
				CNF_AttributeSet.Attributeids
	   
		from DATA_Sale
			inner join data_transaction			on data_transaction.TransactionId = DATA_Sale.PaidTransactionId
			left join DATA_TransactionItem		on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
			left join DATA_SaleItem			    on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
			left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
			left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

		where DATA_Sale.Paid = 1
			and data_transaction.transactiontype in (14, 39)
			and DATA_SaleItem.UnitRecharge &lt;&gt; 0
			and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
			   OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
			and data_transaction.transactionid in (select transactionid
													from data_payment
													where PaymentStatus = 1
													and PaymentAmount &lt;&gt; 0
												)

	INSERT INTO [dbo].[RR_DATA_Revenue]
				([COAAccountId]
				,[RevenueRecognitionRuleId]
				,[RRCode]
				,[RRCalcTypeWhere]
				,[RRCalcTypeMethod]
				,[COAAccountConfigId]
				,[COAAccountType]
				,[COAAccountCode]
				,[TransactionId]
				,[SaleId]
				,[SaleItemId]
				,[MatrixCellId]
				,[MatrixCellCode]
				,[MatrixSheetID]
				,[SiteId]
				,[OperatingAreaId]
				,[WorkstationId]
				,[UserGroupId]
				,[UserId]
				,[FCalcDate]
				,[FRevenueDate]
				,[Quantity]
				,[UnitAmount]
				,[GrossAmount]
				,[NetAmount]
				,[Price]
				,[Percentage]
				,[RemaningValues]
				,[RevenueAmount]
				,[AccountingType]
				,[RRCalcTypeTrigger]
				,[RRPercentage]
				,[RRDays]
				,[AttributeIDS])
		select @SuspendCOAAccountId,
				@SuspendRRRId,
				@SuspendRRRCode,
				@SuspendRRCalcTypeWhere,
				@SuspendRRCalcTypeMethod,
				@SuspendCOAAccountConfigId,
				@SuspendCOAAccountTypeId,
				@SuspendCOAAccountCode,
				data_transaction.transactionid, 
				data_transaction.saleid,
				DATA_TransactionItem.saleitemid,
				DATA_SaleItem.Matrixcellid,
				CNF_MatrixCell.Code,
				CNF_MatrixCell.MatrixSheetid,
				data_transaction.Siteid,
				data_transaction.OperatingAreaId,
				data_transaction.Workstationid,
				data_transaction.UserGroupid,
				data_transaction.UserId,
				@BatchDate,
				CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
				     else data_transaction.TransactionDate
				end TransactionDate,
				Coalesce(DATA_TransactionItem.Quantity, 1),
				DATA_SaleItem.UnitPrice,
				case when isnull(DATA_TransactionItem.TotalAmount, 0) &lt;&gt; 0 then DATA_TransactionItem.TotalAmount
					when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
					else DATA_Sale.TotalAmount
				end,
				case when isnull((DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes)
					when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
					else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
				end as NetAmount,
				@SuspendPrice,
				@SuspendCOAAccount_Percentage,
				@SuspendRemainingValues,
				case    when (data_saleitem.ProductTaxType &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) 
				                  and (isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0) 
								       and (((select discountamount from data_saleitemrule where saleitemid = DATA_SaleItem.saleitemid) &gt; 0) and (data_transaction.transactiontype in (7, 20, 22)))							
                            then ((DATA_SaleItem.UnitRawPrice + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)

				        when (data_saleitem.ProductTaxType &lt;&gt; 1) and (data_transaction.transactiontype in (18, 20, 22)) and (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitPrice  + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)
						when (data_saleitem.ProductTaxType = 1) and (data_transaction.transactiontype in (18, 20, 22)) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitPrice - DATA_SaleItem.unittaxes + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)

				        when (data_saleitem.ProductTaxType &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice  + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)
						when (data_saleitem.ProductTaxType = 1) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice - DATA_SaleItem.unittaxes + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)

						when (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 and data_saleitem.unitRecharge = 0 then 0
						when (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 and data_saleitem.unitRecharge &lt;&gt; 0 then data_saleitem.unitRecharge
						when isnull((data_transaction.TotalAmount), 0) &lt;&gt; 0 then data_transaction.TotalAmount
						when isnull((DATA_Sale.TotalAmount), 0) &lt;&gt; 0 then DATA_Sale.TotalAmount
						else (data_transaction.Revenue)
				end,
				case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
						when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
						when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 1
						when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 2
						else @SuspendRRCOAAccountingType
				end Accountingtype,
				@SuspendRRCalcTypeTrigger,
				@SuspendPercentage,
				@SuspendDays,
				CNF_AttributeSet.Attributeids
	   
		from DATA_Sale
			inner join data_transaction			on data_transaction.TransactionId = ISNULL(data_sale.voidtransactionid, DATA_Sale.PaidTransactionId)
			left join DATA_TransactionItem		on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
			left join DATA_SaleItem			    on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
			left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
			left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

		where DATA_Sale.Paid = 1
			and data_transaction.transactiontype not in (6, 8, 10, 12, 14, 16, 42, 43, 31, 39, 48, 49, 52, 46, 47)
			and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
			   OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
			and data_transaction.transactionid in (select transactionid
													from data_payment
													where PaymentStatus = 1
													and PaymentAmount &lt;&gt; 0
												)

		INSERT INTO [dbo].[RR_DATA_Revenue]
						([COAAccountId]
						,[RevenueRecognitionRuleId]
						,[RRCode]
						,[RRCalcTypeWhere]
						,[RRCalcTypeMethod]
						,[COAAccountConfigId]
						,[COAAccountType]
						,[COAAccountCode]
						,[TransactionId]
						,[SaleId]
						,[SiteId]
						,[OperatingAreaId]
						,[WorkstationId]
						,[UserGroupId]
						,[UserId]
						,[FCalcDate]
						,[FRevenueDate]
						,[Quantity]
						,[GrossAmount]
						,[NetAmount]
						,[Price]
						,[Percentage]
						,[RemaningValues]
						,[RevenueAmount]
						,[AccountingType]
						,[RRCalcTypeTrigger]
						,[RRPercentage]
						,[RRDays])
				select @SuspendCOAAccountId,
						@SuspendRRRId,
						@SuspendRRRCode,
						@SuspendRRCalcTypeWhere,
						@SuspendRRCalcTypeMethod,
						@SuspendCOAAccountConfigId,
						@SuspendCOAAccountTypeId,
						@SuspendCOAAccountCode,
						data_transaction.transactionid, 
						data_transaction.saleid,
						data_transaction.Siteid,
						data_transaction.OperatingAreaId,
						data_transaction.Workstationid,
						data_transaction.UserGroupid,
						data_transaction.UserId,
						@BatchDate,
						CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
							 else data_transaction.TransactionDate
						end TransactionDate,
						0 Quantity,
						data_transaction.revenue TotalAmount,
						data_transaction.revenue NetAmount,
						@SuspendPrice,
						@SuspendCOAAccount_Percentage,
						@SuspendRemainingValues,
						p.Amount,
						@SuspendRRCOAAccountingType,
						@SuspendRRCalcTypeTrigger,
						@SuspendPercentage,
						@SuspendDays
	   
		from DATA_Sale
			inner join data_transaction			on data_transaction.saleid = data_sale.saleid
			left  join  (select settletransactionid, sum(data_payment.paymentamount) as amount
							from data_paymentcredit
								INNER JOIN DATA_Payment						on data_payment.paymentid = data_paymentcredit.paymentid
								INNER JOIN DATA_Transaction					on data_transaction.transactionid = data_paymentcredit.SettleTransactionId
							where ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
								  OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
							group by settletransactionid)p					on p.SettleTransactionId = data_transaction.transactionid

		where DATA_Sale.Paid = 1
			and data_transaction.transactiontype in (6)
			and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
			   OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))


	INSERT INTO [dbo].[RR_DATA_Revenue]
				([COAAccountId]
				,[RevenueRecognitionRuleId]
				,[RRCode]
				,[RRCalcTypeWhere]
				,[RRCalcTypeMethod]
				,[COAAccountConfigId]
				,[COAAccountType]
				,[COAAccountCode]
				,[TransactionId]
				,[SaleId]
				,[SaleItemId]
				,[MatrixCellId]
				,[MatrixCellCode]
				,[MatrixSheetID]
				,[SiteId]
				,[OperatingAreaId]
				,[WorkstationId]
				,[UserGroupId]
				,[UserId]
				,[FCalcDate]
				,[FRevenueDate]
				,[Quantity]
				,[UnitAmount]
				,[GrossAmount]
				,[NetAmount]
				,[Price]
				,[Percentage]
				,[RemaningValues]
				,[RevenueAmount]
				,[AccountingType]
				,[RRCalcTypeTrigger]
				,[RRPercentage]
				,[RRDays]
				,[AttributeIDS])
		select @SuspendCOAAccountId,
				@SuspendRRRId,
				@SuspendRRRCode,
				@SuspendRRCalcTypeWhere,
				@SuspendRRCalcTypeMethod,
				@SuspendCOAAccountConfigId,
				@SuspendCOAAccountTypeId,
				@SuspendCOAAccountCode,
				data_transaction.transactionid, 
				data_transaction.saleid,
				DATA_SaleItem.saleitemid,
				DATA_SaleItem.Matrixcellid,
				CNF_MatrixCell.Code,
				CNF_MatrixCell.MatrixSheetid,
				data_transaction.Siteid,
				data_transaction.OperatingAreaId,
				data_transaction.Workstationid,
				data_transaction.UserGroupid,
				data_transaction.UserId,
				@BatchDate,
				CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
				     else data_transaction.TransactionDate
				end TransactionDate,
				Coalesce(DATA_SaleItem.Quantity, 1),
				DATA_SaleItem.UnitPrice,
				case when isnull(DATA_SaleItem.TotalAmount, 0) &lt;&gt; 0 then DATA_SaleItem.TotalAmount
					when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
					else DATA_Sale.TotalAmount
				end,
				case when isnull((DATA_SaleItem.TotalAmount - DATA_SaleItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_SaleItem.TotalAmount - DATA_SaleItem.TotalTaxes)
					when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
					else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
				end as NetAmount,
				@SuspendPrice,
				@SuspendCOAAccount_Percentage,
				@SuspendRemainingValues,
				case    when (data_saleitem.ProductTaxType &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) 
				                  and (isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0) 
								       and (((select discountamount from data_saleitemrule where saleitemid = DATA_SaleItem.saleitemid) &gt; 0) and (data_transaction.transactiontype in (7, 20, 22)))							
                            then ((DATA_SaleItem.UnitRawPrice + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)


				        when (data_saleitem.ProductTaxType &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice  + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)
						when (data_saleitem.ProductTaxType = 1) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice - DATA_SaleItem.unittaxes + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)
						when (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 then 0
						when (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 and data_saleitem.unitRecharge &lt;&gt; 0 then data_saleitem.unitRecharge
						when isnull((data_transaction.TotalAmount), 0) &lt;&gt; 0 then data_transaction.TotalAmount
						when isnull((DATA_Sale.TotalAmount), 0) &lt;&gt; 0 then DATA_Sale.TotalAmount
						else (data_transaction.Revenue)
				end,
				case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
						when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
						when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 1
						when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 2
						else @SuspendRRCOAAccountingType
				end Accountingtype,
				@SuspendRRCalcTypeTrigger,
				@SuspendPercentage,
				@SuspendDays,
				CNF_AttributeSet.Attributeids
	   
		from DATA_Sale
			inner join data_transaction			on data_transaction.saleid = data_sale.saleid
			left join DATA_SaleItem			    on DATA_SaleItem.saleid = DATA_Transaction.saleid
			left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
			left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

		where DATA_Sale.Paid = 1
			and data_transaction.transactiontype in (46, 47)
			and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
			   OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
			and data_transaction.transactionid in (select transactionid
													from data_payment
													where PaymentStatus = 1
													and PaymentAmount &lt;&gt; 0
												)


	INSERT INTO [dbo].[RR_DATA_Revenue]
				([COAAccountId]
				,[RevenueRecognitionRuleId]
				,[RRCode]
				,[RRCalcTypeWhere]
				,[RRCalcTypeMethod]
				,[COAAccountConfigId]
				,[COAAccountType]
				,[COAAccountCode]
				,[TransactionId]
				,[SaleId]
				,[SaleItemId]
				,[MatrixCellId]
				,[MatrixCellCode]
				,[MatrixSheetID]
				,[SiteId]
				,[OperatingAreaId]
				,[WorkstationId]
				,[UserGroupId]
				,[UserId]
				,[FCalcDate]
				,[FRevenueDate]
				,[Quantity]
				,[UnitAmount]
				,[GrossAmount]
				,[NetAmount]
				,[Price]
				,[Percentage]
				,[RemaningValues]
				,[RevenueAmount]
				,[AccountingType]
				,[RRCalcTypeTrigger]
				,[RRPercentage]
				,[RRDays]
				,[AttributeIDS])
		select @SuspendCOAAccountId,
				@SuspendRRRId,
				@SuspendRRRCode,
				@SuspendRRCalcTypeWhere,
				@SuspendRRCalcTypeMethod,
				@SuspendCOAAccountConfigId,
				@SuspendCOAAccountTypeId,
				@SuspendCOAAccountCode,
				data_transaction.transactionid, 
				data_transaction.saleid,
				DATA_TransactionItem.saleitemid,
				DATA_SaleItem.Matrixcellid,
				CNF_MatrixCell.Code,
				CNF_MatrixCell.MatrixSheetid,
				data_transaction.Siteid,
				data_transaction.OperatingAreaId,
				data_transaction.Workstationid,
				data_transaction.UserGroupid,
				data_transaction.UserId,
				@BatchDate,
				CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
				     else data_transaction.TransactionDate
				end TransactionDate,
				Coalesce(DATA_TransactionItem.Quantity, 1),
				DATA_SaleItem.UnitPrice,
				case when isnull(DATA_TransactionItem.TotalAmount, 0) &lt;&gt; 0 then DATA_TransactionItem.TotalAmount
					when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
					else DATA_Sale.TotalAmount
				end,
				case when isnull((DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes)
					when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
					else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
				end as NetAmount,
				@SuspendPrice,
				@SuspendCOAAccount_Percentage,
				@SuspendRemainingValues,
				DATA_SaleItem.Unitrecharge,
				case    when TransactionType in (5, 17, 8, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
						when TransactionType in (5, 17, 8, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
						when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 2
						when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 1
						else @SuspendRRCOAAccountingType
				end Accountingtype,
				@SuspendRRCalcTypeTrigger,
				@SuspendPercentage,
				@SuspendDays,
				CNF_AttributeSet.Attributeids
	   
		from DATA_Sale
			inner join data_transaction			on data_transaction.TransactionId = ISNULL(data_sale.voidtransactionid, DATA_Sale.PaidTransactionId)
			left join DATA_TransactionItem		on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
			left join DATA_SaleItem			    on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
			left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
			left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

		where DATA_Sale.Paid = 1
			and data_transaction.transactiontype in (10, 42, 43, 49)
			and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
			   OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
			and data_transaction.transactionid in (select transactionid
													from data_payment
													where PaymentStatus = 1
													and PaymentAmount &lt;&gt; 0
												)
			
INSERT INTO [dbo].[RR_DATA_Revenue]
				([COAAccountId]
				,[RevenueRecognitionRuleId]
				,[RRCode]
				,[RRCalcTypeWhere]
				,[RRCalcTypeMethod]
				,[COAAccountConfigId]
				,[COAAccountType]
				,[COAAccountCode]
				,[TransactionId]
				,[SaleId]
				,[SaleItemId]
				,[MatrixCellId]
				,[MatrixCellCode]
				,[MatrixSheetID]
				,[SiteId]
				,[OperatingAreaId]
				,[WorkstationId]
				,[UserGroupId]
				,[UserId]
				,[FCalcDate]
				,[FRevenueDate]
				,[Quantity]
				,[UnitAmount]
				,[GrossAmount]
				,[NetAmount]
				,[Price]
				,[Percentage]
				,[RemaningValues]
				,[RevenueAmount]
				,[AccountingType]
				,[RRCalcTypeTrigger]
				,[RRPercentage]
				,[RRDays]
				,[AttributeIDS])
		select @SuspendCOAAccountId,
				@SuspendRRRId,
				@SuspendRRRCode,
				@SuspendRRCalcTypeWhere,
				@SuspendRRCalcTypeMethod,
				@SuspendCOAAccountConfigId,
				@SuspendCOAAccountTypeId,
				@SuspendCOAAccountCode,
				data_transaction.transactionid, 
				data_transaction.saleid,
				DATA_TransactionItem.saleitemid,
				DATA_SaleItem.Matrixcellid,
				CNF_MatrixCell.Code,
				CNF_MatrixCell.MatrixSheetid,
				data_transaction.Siteid,
				data_transaction.OperatingAreaId,
				data_transaction.Workstationid,
				data_transaction.UserGroupid,
				data_transaction.UserId,
				@BatchDate,
				CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
				     else data_transaction.TransactionDate
				end TransactionDate,
				Coalesce(DATA_TransactionItem.Quantity, 1),
				DATA_SaleItem.UnitPrice,
				case when isnull(DATA_TransactionItem.TotalAmount, 0) &lt;&gt; 0 then DATA_TransactionItem.TotalAmount
					when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
					else DATA_Sale.TotalAmount
				end,
				case when isnull((DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes)
					when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
					else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
				end as NetAmount,
				@SuspendPrice,
				@SuspendCOAAccount_Percentage,
				@SuspendRemainingValues,
				ABS(DATA_SaleItem.Unitrecharge),
				case    when TransactionType in (5, 17, 8, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
						when TransactionType in (5, 17, 8, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
						when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 2
						when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 1
						else @SuspendRRCOAAccountingType
				end Accountingtype,
				@SuspendRRCalcTypeTrigger,
				@SuspendPercentage,
				@SuspendDays,
				CNF_AttributeSet.Attributeids
	   
		from DATA_Sale
			inner join data_transaction			on data_transaction.TransactionId = ISNULL(data_sale.voidtransactionid, DATA_Sale.PaidTransactionId)
			left join DATA_TransactionItem		on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
			left join DATA_SaleItem			    on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
			left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
			left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

		where DATA_Sale.Paid = 1
			and data_transaction.transactiontype in (31, 48, 52)
			and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
			   OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
			and data_transaction.transactionid in (select transactionid
													from data_payment
													where PaymentStatus = 1
													and PaymentAmount &lt;&gt; 0
												   )


	INSERT INTO [dbo].[RR_DATA_Revenue]
						([COAAccountId]
						,[RevenueRecognitionRuleId]
						,[RRCode]
						,[RRCalcTypeWhere]
						,[RRCalcTypeMethod]
						,[COAAccountConfigId]
						,[COAAccountType]
						,[COAAccountCode]
						,[TransactionId]
						,[SaleId]
						,[SaleItemId]
						,[MatrixCellId]
						,[MatrixCellCode]
						,[MatrixSheetID]
						,[SiteId]
						,[OperatingAreaId]
						,[WorkstationId]
						,[UserGroupId]
						,[UserId]
						,[FCalcDate]
						,[FRevenueDate]
						,[Quantity]
						,[UnitAmount]
						,[GrossAmount]
						,[NetAmount]
						,[Price]
						,[Percentage]
						,[RemaningValues]
						,[RevenueAmount]
						,[AccountingType]
						,[RRCalcTypeTrigger]
						,[RRPercentage]
						,[RRDays]
						,[AttributeIDS])
				select @SuspendCOAAccountId,
						@SuspendRRRId,
						@SuspendRRRCode,
						@SuspendRRCalcTypeWhere,
						@SuspendRRCalcTypeMethod,
						@SuspendCOAAccountConfigId,
						@SuspendCOAAccountTypeId,
						@SuspendCOAAccountCode,
						data_transaction.transactionid, 
						data_transaction.saleid,
						DATA_TransactionItem.saleitemid,
						DATA_SaleItem.Matrixcellid,
						CNF_MatrixCell.Code,
						CNF_MatrixCell.MatrixSheetid,
						data_transaction.Siteid,
						data_transaction.OperatingAreaId,
						data_transaction.Workstationid,
						data_transaction.UserGroupid,
						data_transaction.UserId,
						@BatchDate,
						CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
							 else data_transaction.TransactionDate
						end TransactionDate,
						Coalesce(DATA_TransactionItem.Quantity, 1),
						DATA_SaleItem.UnitPrice,
						case when isnull(DATA_TransactionItem.TotalAmount, 0) &lt;&gt; 0 then DATA_TransactionItem.TotalAmount
							when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
							else DATA_Sale.TotalAmount
						end,
						case when isnull((DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes)
							when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
							else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
						end as NetAmount,
						@SuspendPrice,
						@SuspendCOAAccount_Percentage,
						@SuspendRemainingValues,
						case when (data_saleitem.ProductTaxType &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice + DATA_SaleItem.unittaxes) * DATA_SaleItem.Quantity)
						     when (data_saleitem.ProductTaxType = 1) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice) * DATA_SaleItem.Quantity)
						     when (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 then 0
							 when isnull((data_transaction.TotalAmount), 0) &lt;&gt; 0 then data_transaction.TotalAmount
							 when isnull((DATA_Sale.TotalAmount), 0) &lt;&gt; 0 then DATA_Sale.TotalAmount
							 else (data_transaction.Revenue)
						end,
						case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
								when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
								when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 2
								when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 1
								else @SuspendRRCOAAccountingType
						end Accountingtype,
						@SuspendRRCalcTypeTrigger,
						@SuspendPercentage,
						@SuspendDays,
						CNF_AttributeSet.Attributeids
	   
				from DATA_Sale
					inner join data_transaction			on data_transaction.Saleid = DATA_Sale.Saleid
					left join DATA_TransactionItem		on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
					left join DATA_SaleItem			    on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
					left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
					left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

				where data_transaction.transactiontype in (8)
					and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
						OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
					and data_transaction.transactionid in (select transactionid
															from data_payment
															where PaymentStatus = 1
															and PaymentAmount &lt;&gt; 0
														)

			INSERT INTO [dbo].[RR_DATA_Revenue]
						([COAAccountId]
						,[RevenueRecognitionRuleId]
						,[RRCode]
						,[RRCalcTypeWhere]
						,[RRCalcTypeMethod]
						,[COAAccountConfigId]
						,[COAAccountType]
						,[COAAccountCode]
						,[TransactionId]
						,[SaleId]
						,[SiteId]
						,[OperatingAreaId]
						,[WorkstationId]
						,[UserGroupId]
						,[UserId]
						,[FCalcDate]
						,[FRevenueDate]
						,[Quantity]
						,[GrossAmount]
						,[NetAmount]
						,[Price]
						,[Percentage]
						,[RemaningValues]
						,[RevenueAmount]
						,[AccountingType]
						,[RRCalcTypeTrigger]
						,[RRPercentage]
						,[RRDays])
				select @SuspendCOAAccountId,
						@SuspendRRRId,
						@SuspendRRRCode,
						@SuspendRRCalcTypeWhere,
						@SuspendRRCalcTypeMethod,
						@SuspendCOAAccountConfigId,
						@SuspendCOAAccountTypeId,
						@SuspendCOAAccountCode,
						data_transaction.transactionid, 
						data_transaction.saleid,
						data_transaction.Siteid,
						data_transaction.OperatingAreaId,
						data_transaction.Workstationid,
						data_transaction.UserGroupid,
						data_transaction.UserId,
						@BatchDate,
						CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
							 else data_transaction.TransactionDate
						end TransactionDate,
						0 Quantity,
						data_transaction.revenue TotalAmount,
						data_transaction.revenue NetAmount,
						@SuspendPrice,
						@SuspendCOAAccount_Percentage,
						@SuspendRemainingValues,
						data_transaction.revenue,
						@SuspendRRCOAAccountingType,
						@SuspendRRCalcTypeTrigger,
						@SuspendPercentage,
						@SuspendDays
	   
				from DATA_Sale
					inner join data_transaction			on data_transaction.saleid = DATA_Sale.saleid
				where data_transaction.transactiontype = 12
					and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
						OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
					and data_transaction.transactionid in (select transactionid
															from data_payment
															where PaymentStatus = 1
															and PaymentAmount &lt;&gt; 0
														)



				INSERT INTO [dbo].[RR_DATA_Revenue]
						([COAAccountId]
						,[RevenueRecognitionRuleId]
						,[RRCode]
						,[RRCalcTypeWhere]
						,[RRCalcTypeMethod]
						,[COAAccountConfigId]
						,[COAAccountType]
						,[COAAccountCode]
						,[TransactionId]
						,[SaleId]
						,[SaleItemId]
						,[MatrixCellId]
						,[MatrixCellCode]
						,[MatrixSheetID]
						,[SiteId]
						,[OperatingAreaId]
						,[WorkstationId]
						,[UserGroupId]
						,[UserId]
						,[FCalcDate]
						,[FRevenueDate]
						,[Quantity]
						,[UnitAmount]
						,[GrossAmount]
						,[NetAmount]
						,[Price]
						,[Percentage]
						,[RemaningValues]
						,[RevenueAmount]
						,[AccountingType]
						,[RRCalcTypeTrigger]
						,[RRPercentage]
						,[RRDays]
						,[AttributeIDS])
						select *
						from (
				select @SuspendCOAAccountId as COAAccountId,
						@SuspendRRRId as RevenueRecognitionRuleId,
						@SuspendRRRCode as RRCode,
						@SuspendRRCalcTypeWhere as RRCalcTypeWhere,
						@SuspendRRCalcTypeMethod as RRCalcTypeMethod,
						@SuspendCOAAccountConfigId as COAAccountConfigId,
						@SuspendCOAAccountTypeId as COAAccountType,
						@SuspendCOAAccountCode as COAAccountCode,
						data_transaction.transactionid, 
						data_transaction.saleid,
						DATA_SaleItem.saleitemid,
						DATA_SaleItem.Matrixcellid,
						CNF_MatrixCell.Code,
						CNF_MatrixCell.MatrixSheetid,
						data_transaction.Siteid,
						data_transaction.OperatingAreaId,
						data_transaction.Workstationid,
						data_transaction.UserGroupid,
						data_transaction.UserId,
						@BatchDate as calcdate,
						CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
								else data_transaction.TransactionDate
						end TransactionDate,
						Coalesce(DATA_SaleItem.Quantity, 1) as quantity,
						DATA_SaleItem.UnitPrice,
						case when isnull(DATA_SaleItem.TotalAmount, 0) &lt;&gt; 0 then DATA_SaleItem.TotalAmount
							when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
							else DATA_Sale.TotalAmount
						end as totalamount,
						case when isnull((DATA_SaleItem.TotalAmount - DATA_SaleItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_SaleItem.TotalAmount - DATA_SaleItem.TotalTaxes)
							when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
							else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
						end as NetAmount,
						@SuspendPrice as suspendprice,
						@SuspendCOAAccount_Percentage as percentage,
						@SuspendRemainingValues as remainingValues,
						case when (data_saleitem.ProductTaxType &lt;&gt; 1) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice) * DATA_SaleItem.Quantity)
						     when (data_saleitem.ProductTaxType = 1) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice - DATA_SaleItem.unittaxes) * DATA_SaleItem.Quantity)
						     when isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 then 0
							 when isnull((data_transaction.TotalAmount), 0) &lt;&gt; 0 then data_transaction.TotalAmount
							 when isnull((DATA_Sale.TotalAmount), 0) &lt;&gt; 0 then DATA_Sale.TotalAmount
							 else (data_transaction.Revenue)
						end as Revenueamount,
						case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
								when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
								when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 2
								when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 1
								else @SuspendRRCOAAccountingType
						end Accountingtype,
						@SuspendRRCalcTypeTrigger as rrTrigger,
						@SuspendPercentage as suspercentage,
						@SuspendDays as suspendday,
						CNF_AttributeSet.Attributeids
	   
				from DATA_Sale
					inner join data_transaction			on data_transaction.TransactionId = DATA_Sale.PaidTransactionId
					left join DATA_SaleItem			    on DATA_SaleItem.SAleid = data_transaction.SAleid
					left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
					left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

				where DATA_Sale.Paid = 1
					and data_transaction.transactiontype in (16)
					and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
					 OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
					and data_transaction.transactionid in (select transactionid
															from data_payment
															where PaymentStatus = 1
															--and PaymentAmount &lt;&gt; 0
														)
					and data_transaction.transactionid not in (select distinct transactionid
																from rr_data_Revenue
																where transactionid is not null)
					and data_saleitem.saleitemid not in (select distinct data_saleitem.saleitemid
													from data_saleitem
															inner join data_transactionitem   on data_transactionitem.saleitemid = data_saleitem.saleitemid
															inner join data_transaction       on data_transaction.transactionid = data_transactionitem.transactionid
													where data_transaction.transactiontype in (5)
													)
					)p  where UnitPrice &lt;&gt; 0


				INSERT INTO [dbo].[RR_DATA_Revenue]
						([COAAccountId]
						,[RevenueRecognitionRuleId]
						,[RRCode]
						,[RRCalcTypeWhere]
						,[RRCalcTypeMethod]
						,[COAAccountConfigId]
						,[COAAccountType]
						,[COAAccountCode]
						,[TransactionId]
						,[SaleId]
						,[SaleItemId]
						,[MatrixCellId]
						,[MatrixCellCode]
						,[MatrixSheetID]
						,[SiteId]
						,[OperatingAreaId]
						,[WorkstationId]
						,[UserGroupId]
						,[UserId]
						,[FCalcDate]
						,[FRevenueDate]
						,[Quantity]
						,[UnitAmount]
						,[GrossAmount]
						,[NetAmount]
						,[Price]
						,[Percentage]
						,[RemaningValues]
						,[RevenueAmount]
						,[AccountingType]
						,[RRCalcTypeTrigger]
						,[RRPercentage]
						,[RRDays]
						,[AttributeIDS])
				select @SuspendCOAAccountId,
						@SuspendRRRId,
						@SuspendRRRCode,
						@SuspendRRCalcTypeWhere,
						@SuspendRRCalcTypeMethod,
						@SuspendCOAAccountConfigId,
						@SuspendCOAAccountTypeId,
						@SuspendCOAAccountCode,
						data_transaction.transactionid, 
						data_transaction.saleid,
						DATA_TransactionItem.saleitemid,
						DATA_SaleItem.Matrixcellid,
						CNF_MatrixCell.Code,
						CNF_MatrixCell.MatrixSheetid,
						data_transaction.Siteid,
						data_transaction.OperatingAreaId,
						data_transaction.Workstationid,
						data_transaction.UserGroupid,
						data_transaction.UserId,
						@BatchDate,
						CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
							 else data_transaction.TransactionDate
						end TransactionDate,
						Coalesce(DATA_TransactionItem.Quantity, 1),
						DATA_SaleItem.UnitPrice,
						case when isnull(DATA_TransactionItem.TotalAmount, 0) &lt;&gt; 0 then DATA_TransactionItem.TotalAmount
							when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
							else DATA_Sale.TotalAmount
						end,
						case when isnull((DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes)
							when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
							else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
						end as NetAmount,
						@SuspendPrice,
						@SuspendCOAAccount_Percentage,
						@SuspendRemainingValues,
						case when isnull((DATA_TransactionItem.UnitPrice *  DATA_TransactionItem.Quantity), 0) &lt;&gt; 0 then (DATA_TransactionItem.UnitPrice *  DATA_TransactionItem.Quantity)
							when isnull((data_transaction.TotalAmount), 0) &lt;&gt; 0 then data_transaction.TotalAmount
							when isnull((DATA_Sale.TotalAmount), 0) &lt;&gt; 0 then DATA_Sale.TotalAmount
							else (data_transaction.Revenue)
						end,
						case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
								when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
								when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 2
								when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 1
								else @SuspendRRCOAAccountingType
						end Accountingtype,
						@SuspendRRCalcTypeTrigger,
						@SuspendPercentage,
						@SuspendDays,
						CNF_AttributeSet.Attributeids
	   
				from DATA_Sale
					inner join data_transaction			on data_transaction.saleid = DATA_Sale.saleid
					inner join DATA_TransactionItem		on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
					left join DATA_SaleItem			    on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
					left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
					left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

				where DATA_Sale.Paid = 1
					and data_transaction.transactiontype in (5)
					and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
					 OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
					
					and data_transaction.transactionid in (select transactionid
															from data_payment
															where PaymentStatus = 1
															and PaymentAmount &lt;&gt; 0
														)
					and data_transaction.transactionid not in (select distinct transactionid
																from rr_data_Revenue
																where transactionid is not null)

--PaymentMethod
				INSERT INTO [dbo].[RR_DATA_Revenue]
								([COAAccountId]
								,[RevenueRecognitionRuleId]
								,[RRCode]
								,[RRCalcTypeWhere]
								,[RRCalcTypeMethod]
								,[COAAccountConfigId]
								,[COAAccountType]
								,[COAAccountCode]
								,[TransactionId]
								,[SaleId]
								,[SiteId]
								,[OperatingAreaId]
								,[WorkstationId]
								,[UserGroupId]
								,[UserId]
								,[FCalcDate]
								,[FRevenueDate]
								,[Quantity]
								,[GrossAmount]
								,[NetAmount]
								,[Price]
								,[Percentage]
								,[RemaningValues]
								,[RevenueAmount]
								,[AccountingType]
								,[RRCalcTypeTrigger]
								,[RRPercentage]
								,[RRDays])
								select  coaaccountid,
										RRID,
										RRCode,
										TypeWhere,
										method,
										Configid,
										AccountType,
										AccountCode,
										transactionid, 
										saleid,
										Siteid,
										OperatingAreaId,
										WorkstationID,
										UserGroupid,
										UserId,
										BatchDate,
										TransactionDate,
										Qty,
										Gross,
										net,
										price,
										percentage,
										RemaningValue,
										sum(abs(RevenueAmount)),
										Accountingtype,
										TypeTrigger,
										PaymentPercentage,
										RRDays
								from (
								select  coaaccountid,
										RRID,
										RRCode,
										TypeWhere,
										method,
										Configid,
										AccountType,
										AccountCode,
										transactionid, 
										saleid,
										Siteid,
										OperatingAreaId,
										WorkstationID,
										UserGroupid,
										UserId,
										BatchDate,
										TransactionDate,
										Qty,
										Gross,
										net,
										price,
										percentage,
										RemaningValue,
										case when Rownumber = 1 then RevenueAmount + Change
										     else RevenueAmount
										 end RevenueAmount,
										Accountingtype,
										TypeTrigger,
										PaymentPercentage,
										RRDays
								from (
								select @PaymentCOAAccountId as coaaccountid,
										@PaymentRRRId as RRID,
										@PaymentRRRCode as RRCode,
										@PaymentRRCalcTypeWhere as TypeWhere,
										@PaymentRRCalcTypeMethod as method,
										@PaymentCOAAccountConfigId as Configid,
										@PaymentCOAAccountTypeId as AccountType,
										@PaymentCOAAccountCode as AccountCode,
										data_transaction.transactionid, 
										data_transaction.saleid,
										data_transaction.Siteid,
										data_transaction.OperatingAreaId,
										data_transaction.Workstationid,
										data_transaction.UserGroupid,
										data_transaction.UserId,
										@BatchDate as BatchDate,
										CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
											 else data_transaction.TransactionDate
										end TransactionDate,
										0 as Qty,
										0 as Gross,
										0 as net,
										0 as price,
										100 as percentage,
										0 as RemaningValue,
										(data_payment.PaymentAmount) as RevenueAmount,
										case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @PaymentRRCOAAccountingType = 1 then 2
												when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @PaymentRRCOAAccountingType = 2 then 1
												when TransactionType in (7) and (data_payment.PaymentAmount + data_Payment.PaymentFee) &lt;= 0  then 2
												when TransactionType in (7) and (data_payment.PaymentAmount + data_Payment.PaymentFee) &gt; 0  then 1
												else @PaymentRRCOAAccountingType
									    end Accountingtype,
										data_transaction.Change,
										@PaymentRRCalcTypeTrigger as TypeTrigger,
										@PaymentPercentage as PaymentPercentage,
										@PaymentDays as RRDays,
										Row_Number ()  OVER (PARTITION BY data_transaction.transactionid order by data_transaction.transactionid)  as Rownumber
		  
								from DATA_Sale
											INNER join data_transaction			on ((data_transaction.TransactionId = Isnull(data_sale.voidtransactionid, DATA_Sale.PaidTransactionId)) or 
											                                       (data_transaction.saleid = data_sale.saleid))
											INNER JOIN DATA_Payment				on data_payment.transactionid = data_transaction.transactionid
			
								where data_payment.PaymentStatus = 1
									and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
									 OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
							)p
							)r
							group by 	coaaccountid,
										RRID,
										RRCode,
										TypeWhere,
										method,
										Configid,
										AccountType,
										AccountCode,
										transactionid, 
										saleid,
										Siteid,
										OperatingAreaId,
										Workstationid,
										UserGroupid,
										UserId,
										BatchDate,
										TransactionDate,
										Qty,
										Gross,
										net,
										price,
										percentage,
										RemaningValue,
										Accountingtype,
										TypeTrigger,
										PaymentPercentage,
										RRDays
							Having sum(abs(RevenueAmount)) &lt;&gt; 0
						



--Tax
					INSERT INTO [dbo].[RR_DATA_Revenue]
								([COAAccountId]
								,[RevenueRecognitionRuleId]
								,[RRCode]
								,[RRCalcTypeWhere]
								,[RRCalcTypeMethod]
								,[COAAccountConfigId]
								,[COAAccountType]
								,[COAAccountCode]
								,[TransactionId]
								,[SaleId]
								,[SiteId]
								,[OperatingAreaId]
								,[WorkstationId]
								,[UserGroupId]
								,[UserId]
								,[FCalcDate]
								,[FRevenueDate]
								,[Quantity]
								,[GrossAmount]
								,[NetAmount]
								,[Price]
								,[Percentage]
								,[RemaningValues]
								,[RevenueAmount]
								,[AccountingType]
								,[RRCalcTypeTrigger]
								,[RRPercentage]
								,[RRDays])

								select  @TaxCOAAccountId,
										@TaxRRRId,
										@TaxRRRCode,
										@TaxRRCalcTypeWhere,
										@TaxRRCalcTypeMethod,
										@TaxCOAAccountConfigId,
										@TaxCOAAccountTypeId,
										@TaxCOAAccountCode,
										data_transaction.transactionid, 
										data_transaction.saleid,
										data_transaction.Siteid,
										data_transaction.OperatingAreaId,
										data_transaction.Workstationid,
										data_transaction.UserGroupid,
										data_transaction.UserId,
										@BatchDate,
										CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
											 else data_transaction.TransactionDate
										end TransactionDate,
										0,
										0,
										0,
										0,
										100,
										0,
										ABS(sum(taxamount)) RevenueAmount,
										case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @TaxRRCOAAccountingType = 1 then 2
												when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @TaxRRCOAAccountingType = 2 then 1
											    when TransactionType in (7) and sum(taxamount) &lt;= 0  then 1
												when TransactionType in (7) and sum(taxamount) &gt; 0  then 2
												else @TaxRRCOAAccountingType
									    end Accountingtype,
										@TaxRRCalcTypeTrigger,
										@TaxPercentage,
										@TaxDays
		   
							from Data_Sale
								INNER JOIN DATA_Transaction						on data_transaction.Saleid = Data_Sale.Saleid
								INNER JOIN DATA_TransactionTax					on data_transactiontax.transactionid = data_transaction.transactionid
								INNER JOIN CNF_Tax								on cnf_tax.taxid = DATA_TransactionTax.taxid
								--INNER JOIN coa_cnf_account coa					on coa.coaaccountid = cnf_tax.coaaccountid


							where transactiontype NOT IN (33, 45, 46, 47)
							   and Data_Sale.paid = 1
								and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
								 OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
								  and data_transaction.transactionid in (select distinct transactionid
								                                           from data_payment
																		   where data_payment.paymentstatus = 1
																		)
							group by 			data_transaction.transactionid, 
												data_transaction.saleid,
												data_transaction.Siteid,
												data_transaction.OperatingAreaId,
												data_transaction.Workstationid,
												data_transaction.UserGroupid,
												data_transaction.UserId,
												Data_Transaction.TransactionDate,
												TransactionType,
												fTransactionDate


--Discount

						INSERT INTO [dbo].[RR_DATA_Revenue]
								([COAAccountId]
								,[RevenueRecognitionRuleId]
								,[RRCode]
								,[RRCalcTypeWhere]
								,[RRCalcTypeMethod]
								,[COAAccountConfigId]
								,[COAAccountType]
								,[COAAccountCode]
								,[TransactionId]
								,[SaleId]
								,[SiteId]
								,[OperatingAreaId]
								,[WorkstationId]
								,[UserGroupId]
								,[UserId]
								,[FCalcDate]
								,[FRevenueDate]
								,[Quantity]
								,[GrossAmount]
								,[NetAmount]
								,[Price]
								,[Percentage]
								,[RemaningValues]
								,[RevenueAmount]
								,[AccountingType]
								,[RRCalcTypeTrigger]
								,[RRPercentage]
								,[RRDays])

								select  @DiscountCOAAccountId,
										@DiscountRRRId,
										@DiscountRRRCode,
										@DiscountRRCalcTypeWhere,
										@DiscountRRCalcTypeMethod,
										@DiscountCOAAccountConfigId,
										@DiscountCOAAccountTypeId,
										@DiscountCOAAccountCode,
										data_transaction.transactionid, 
										data_transaction.saleid,
										data_transaction.Siteid,
										data_transaction.OperatingAreaId,
										data_transaction.Workstationid,
										data_transaction.UserGroupid,
										data_transaction.UserId,
										@BatchDate,
										CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
											 else data_transaction.TransactionDate
										end TransactionDate,
										0,
										0,
										0,
										0,
										100,
										0,
										ABS(p.GLAmount) RevenueAmount,
										case    when data_transaction.TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) then 2
											    when data_transaction.TransactionType in (7) and (GLAmount) &lt;= 0  then 2
												when data_transaction.TransactionType in (7) and (GLAmount) &gt; 0  then 1
												else @DiscountRRCOAAccountingType
									    end Accountingtype,

										@DiscountRRCalcTypeTrigger,
										@DiscountPercentage,
										@DiscountDays
							FROM
							(
								SELECT distinct DATA_SaleItem.Saleitemid,
												DATA_Sale.saleid AS SAleid,
      											DATA_Transaction.TransactionType,
      											( SELECT top 1 transactionid
													FROM data_transaction		WITH (NOLOCK)
												   WHERE saleid = DATA_Sale.saleid
													AND transactiontype in (14, 16)
													AND paid = 1
												) AS tester,

												CASE WHEN DATA_Transaction.TransactionId IN (
																							  SELECT TR.TransactionID
																								FROM DATA_Transaction TR			WITH (NOLOCK)
																									LEFT JOIN DATA_Payment DP		WITH (NOLOCK) ON TR.TransactionId = DP.TransactionId
																							  WHERE TR.SaleId = DATA_Sale.SaleId
																								AND TR.Paid = 1
																								AND DP.PaymentStatus NOT IN (0, 2, 3)
																							)
      
															THEN DATA_Transaction.Transactionid
													 ELSE (
															  SELECT MIN(TR.TransactionID)
																FROM DATA_Transaction TR				WITH (NOLOCK)
																	LEFT JOIN DATA_Payment DP			WITH (NOLOCK) ON TR.TransactionId = DP.TransactionId
															   WHERE TR.SaleId = DATA_Sale.saleid
																 AND TR.TransactionType = 16
																 AND TR.Paid = 1
																 AND DP.PaymentStatus NOT IN (0, 2, 3)
														  )
												END Transactionid, 
												 CASE WHEN CNF_Promotion.PromotionType = 1 AND CNF_PromotionItemRule.NewProduct = 1 THEN  (CNF_MatrixCell.Price - SUM(DATA_SaleItemRule.DiscountAmount))
													  ELSE  CASE WHEN sum(1*data_saleItemRule.DiscountAmount) &lt; 0 AND transactiontype IN(20, 22, 30, 7, 5, 46, 47) AND
																																								(SELECT Count(*) 
																																								   FROM data_transaction WITH (NOLOCK)
																																								  WHERE saleid = data_sale.saleid
																																								 ) = 1 					  					  					  										  
																	  THEN Sum(1 * DATA_SaleItemRule.DiscountAmount)
																 WHEN sum(1*data_saleItemRule.DiscountAmount) &lt; 0 THEN	Sum(-1 * DATA_SaleItemRule.DiscountAmount)
																 WHEN sum(1*data_saleItemRule.DiscountAmount) &gt; 0 AND transactiontype IN(20, 22, 30, 7, 5, 46, 47) THEN Sum(-1 * DATA_SaleItemRule.DiscountAmount)		            	                  
																 ELSE sum(1*Data_SaleItemRule.DiscountAmount)
															END
												END AS GLAmount


								FROM dbo.DATA_SaleItemRule				WITH (NOLOCK)
									LEFT JOIN dbo.CNF_PromotionItemRule WITH (NOLOCK) ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
									LEFT JOIN dbo.CNF_PromotionItem		WITH (NOLOCK) ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
									LEFT JOIN dbo.CNF_Promotion			WITH (NOLOCK) ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId
									LEFT JOIN dbo.CNF_DmgCategory		WITH (NOLOCK) ON CNF_DmgCategory.DmgCategoryId = CNF_Promotion.DmgCategoryId
									LEFT JOIN dbo.DATA_SaleItem			WITH (NOLOCK) ON DATA_SaleItem.SaleItemId = DATA_SaleItemRule.SaleItemId
									LEFT JOIN dbo.DATA_Sale				WITH (NOLOCK) ON DATA_Sale.SaleID = DATA_SaleItem.SaleID
									LEFT JOIN DATA_TransactionItem		WITH (NOLOCK) ON DATA_TransactionItem.SaleItemId = DATA_SaleItem.SaleItemId 
									LEFT JOIN DATA_Transaction			WITH (NOLOCK) ON  DATA_Transaction.TransactionId = DATA_TransactionItem.TransactionId
									LEFT JOIN CNF_MatrixCell			WITH (NOLOCK) ON CNF_MatrixCell.MatrixCellId =  DATA_SaleItem.MatrixCellId

 
								WHERE DATA_Transaction.saleid in (
																	SELECT ff.saleid 
																	  FROM DATA_Transaction ff WITH (NOLOCK) 
																		LEFT JOIN Data_Payment WITH (NOLOCK) on (ff.Transactionid = Data_Payment.Transactionid) 
																	 WHERE  ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
																		OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
																	   AND DATA_PAyment.PaymentStatus NOT in (0,2,3) 
																	   AND (TransactionType not in (12)) 
																	   AND ff.PAid = 1
																 )  

								 AND DATA_Sale.Paid = 1
								 and transactiontype NOT IN (33, 45, 46, 47)
								 AND ((DATA_SaleItem.quantity &gt; 0) OR ((DATA_SaleItem.quantity &lt; 0) AND (transactiontype IN (20, 22, 30, 7, 5, 46, 47))))

         
								group BY DATA_SaleItem.Saleitemid,
										 DATA_Sale.saleid,
										 Data_transaction.Paid,
										 Data_Transaction.Transactionid,
										 Data_Transaction.fTransactionDate,
										 Data_Saleitem.Matrixcellid,
										 CNF_DmgCategory.DmgCategoryCode,
										 PromotionType,
										 CNF_PromotionItemRule.NewProduct,
										 CNF_MatrixCell.Price,
										 transactiontype,
										 CNF_DmgCategory.Description
							)p
								LEFT JOIN data_transaction WITH (NOLOCK) on data_transaction.transactionid = p.transactionid

							WHERE ((p.TransactionType &lt;&gt; 5) or (Tester is not null))
							  AND data_transaction.transactionid is not null


					
		--End Move Transactions to Suspend Account

		exec otn_sp_RR_RevenueData_OnDepositTrigger @BatchDate, @RRTransDateType

		exec otn_sp_RR_RevenueData_OnSaleTrigger @BatchDate, @RRTransDateType
		
		exec otn_sp_RR_RevenueData_OnMoneyCardLoad @BatchDate, @RRTransDateType

		exec otn_sp_RR_RevenueData_OnMoneyCardCashOut @BatchDate, @RRTransDateType

		exec otn_sp_RR_RevenueData_OnExternalMoneyCardCashOut @BatchDate, @RRTransDateType

		exec otn_sp_RR_RevenueData_OnExternalMoneyCardLoad @BatchDate, @RRTransDateType

	    exec otn_sp_RR_RevenueData_OnCreditWriteoff @BatchDate, @RRTransDateType

		exec otn_sp_RR_RevenueData_OnMoneyRefundTrigger @BatchDate, @RRTransDateType

		exec otn_sp_RR_RevenueData_OnAdvancedPaymentTrigger @BatchDate, @RRTransDateType
		
		--exec otn_sp_RR_RevenueData_OnFlexContractPayment @BatchDate, @RRTransDateType

		--exec otn_sp_RR_RevenueData_OnFlexContractCancelled @BatchDate, @RRTransDateType

		exec otn_sp_RR_RevenueData_OnCreditSettlementTrigger @BatchDate, @RRTransDateType
		
		exec otn_sp_RR_RevenueData_SettleUpSuspendAccount @BatchDate, @RRTransDateType


	    exec otn_sp_RR_RevenueData_OnTicketUsageTrigger @BatchDate, @RRTransDateType

		exec otn_sp_RR_RevenueData_OnEventTrigger @BatchDate, @RRTransDateType

		exec otn_sp_RR_RevenueData_OnTimePeriodTrigger @BatchDate, @RRTransDateType

		exec otn_sp_RR_RevenueData_OnTicketExpiredTrigger @BatchDate, @RRTransDateType
		

End
</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>marioarosio</ADDEDBY>
			<SQLVERSION>2306</SQLVERSION>
			<RMTRACKLINK>68300</RMTRACKLINK>
			<REASON>Updating Sale Restriction tables</REASON>
			<TABLENAMES>CNF_SaleRestrictionValidity=SaleRestrictionValidityId
CNF_SaleLimitRestriction=SaleLimitRestrictionId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'MaxAllowed' AND
                Object_ID  = Object_ID(N'CNF_SaleRestrictionValidity'))
BEGIN
  exec sp_rename 'CNF_SaleRestrictionValidity.MaxAllowed', 'MaxAllowedPerPeriod', 'COLUMN'
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'MaxAllowed' AND
                Object_ID  = Object_ID(N'CNF_SaleLimitRestriction'))
BEGIN
  exec sp_rename 'CNF_SaleLimitRestriction.MaxAllowed', 'MaxAllowedPerPeriod', 'COLUMN'
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>andreadavanzo</ADDEDBY>
			<SQLVERSION>2305</SQLVERSION>
			<RMTRACKLINK>70318</RMTRACKLINK>
			<REASON>Adding index to the DATA_TicketStatus
[0] Index TicketId - Active
[1] Rebuild index</REASON>
			<TABLENAMES>DATA_TicketStatus=TicketStatusID</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * 
               FROM sys.indexes  
               WHERE name='IDX_DATA_TicketStatus_TicketId_Active' AND object_id = OBJECT_ID('DATA_TicketStatus'))
BEGIN
   CREATE NONCLUSTERED INDEX [IDX_DATA_TicketStatus_TicketId_Active]
   ON [DATA_TicketStatus] ([TicketId],[Active])
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * 
           FROM sys.indexes  
           WHERE name='IDX_DATA_TicketStatus_TicketId_Active' AND object_id = OBJECT_ID('DATA_TicketStatus'))
BEGIN
   ALTER INDEX IDX_DATA_TicketStatus_TicketId_Active ON DATA_TicketStatus REBUILD
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>kdixon</ADDEDBY>
			<SQLVERSION>2304</SQLVERSION>
			<RMTRACKLINK>71078</RMTRACKLINK>
			<REASON>Check in of Sprint 1 of COA2</REASON>
			<TABLENAMES>rr_data_revenue=RevenueRecognitionDataId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS(SELECT 1 FROM sys.columns 
          WHERE Name = N'AttributeIDs'
          AND Object_ID = Object_ID(N'rr_data_revenue'))
BEGIN

	ALTER Table rr_data_revenue
	ADD AttributeIDs [varchar](4000)

END
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_RR_RevenueData_batchJob]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_RR_RevenueData_batchJob
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_RR_RevenueData_PaymentMethodTaxDiscounts2]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_RR_RevenueData_PaymentMethodTaxDiscounts2
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE Procedure dbo.otn_sp_RR_RevenueData_PaymentMethodTaxDiscounts2
	@BatchDate Date,
	@Transactions varchar(500),
	@Trigger int,
	@RRTransDateType Integer
AS 
BEGIN
	 
	Create Table #TransactionIDs(
	TransactionId Int NOT NULL)

	DECLARE @DelimPosition INT

    SET @DelimPosition = CHARINDEX(',', @Transactions)

    WHILE @DelimPosition &gt; 0
    BEGIN
        INSERT INTO #TransactionIDs(TransactionId)
            VALUES(CAST(RTRIM(LEFT(@Transactions, @DelimPosition - 1)) AS INT))
        SET @Transactions = right(@Transactions, len(@Transactions) - @DelimPosition)

        SET @DelimPosition = CHARINDEX(',', @Transactions)
    END


	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer

	Declare @OnCreditWriteoff Integer = 9
	Declare @StartTime DateTime

	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1
	

		--Normal Sale Split out the Payments to Smaller Subset.
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays]
				   ,[attributeids])				    
						select distinct COA.COAAccountId, 
								p.RevenueRecognitionRuleId,
								p.code,		   
								p.RRCalcTypeWhere,
								p.RRCalcTypeMethod,	   
								p.COAAccountConfigId,
								p.COAAccountTypeId,
								COA.Code,
								RR_DATA_REVENUE.Transactionid as Transactionid,
								RR_DATA_REVENUE.saleid as Saleid,
								RR_DATA_REVENUE.Siteid as SiteID,
								RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								RR_DATA_REVENUE.Workstationid as Workstationid,
								RR_DATA_REVENUE.UserGroupid as UserGroupID,
								RR_DATA_REVENUE.UserId as userID,
								@BatchDate as BatchDate,
							   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
									else DATA_Transaction.transactiondate
							   end as TransDate,
								0 as Quantity,
								0 as GrossAmount,
								0 as NetAmount,
								0 as ConfigPrice,
								100 as ConfigPercentage,
								0 RemainingValues,	
								ABS ((data_payment.PaymentAmount + data_payment.PaymentFee) - 
							   (case when data_payment.paymentid = (select top 1 paymentid
																	from data_payment
																	where transactionid = RR_DATA_REVENUE.Transactionid
																		and data_payment.paymentamount &gt; (select sum(Change) *-1
																									from data_transaction
																									where data_transaction.transactionid = RR_DATA_REVENUE.Transactionid))
									then (select sum(Change) *-1
																									from data_transaction
																									where data_transaction.transactionid = RR_DATA_REVENUE.Transactionid)
									else 0
								end ))
								as RevenueAmount,
							--	p.Accountingtype,		
								case    when DATA_Transaction.TransactionType in (5, 8, 17, 18, 20, 22, 30) and p.Accountingtype = 1 then 2
										when DATA_Transaction.TransactionType in (5, 8, 17, 18, 20, 22, 30) and p.Accountingtype = 2 then 1
										when DATA_Transaction.TransactionType in (7) and (RR_DATA_REVENUE.revenueAmount) &lt;= 0  then 1
										when DATA_Transaction.TransactionType in (7) and (RR_DATA_REVENUE.revenueAmount) &gt; 0  then 2
										else p.Accountingtype
								end Accountingtype,
							   p.RRCalcTypeTrigger,
							   p.RRPercentage,
							   p.Days,
							   RR_DATA_REVENUE.attributeids

					from RR_DATA_REVENUE
									INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
									INNER JOIN (select '1' as PCOAAccountid, 
													   coa_cnf_accountConfig.Siteid, 
													   RR_CNF_RevenueRecognitionRule.Enabled, 
													   RR_CNF_RevenueRecognitionRule.FromDate, 
													   RR_CNF_RevenueRecognitionRule.ToDate,
													   COA_CNF_AccountConfig.RemainingValues,
													   coa_cnf_account.coaaccountid,
													   COA_CNF_AccountConfig.Price,
													   COA_CNF_AccountConfig.Percentage,
													   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
													   RR_CNF_RevenueRecognitionRule.code,		   
													   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
													   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
													   COA_CNF_AccountConfig.COAAccountConfigId,
													   coa_cnf_account.COAAccountTypeId,
													   coa_cnf_account.Code as accountcode,
													   coa_cnf_accountconfig.Accountingtype,
													   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
													   RR_CNF_RevenueRecognitionRule.Percentage rrPercentage,
													   RR_CNF_RevenueRecognitionRule.Days	

													from RR_CNF_RevenueRecognitionRule	
													INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
													INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid and coa_cnf_account.Enabled = 1
													INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
												where  RR_CNF_RevenueRecognitionRule.Enabled = 1
												and coa_cnf_account.coaaccountid in (@ACCPaymentMethod)) p				on p.PCOAAccountid = rr_data_revenue.coaaccountid 
							INNER JOIN data_payment							on data_payment.transactionid = rr_data_revenue.transactionid
							left  JOIN DATA_PaymentCard						on data_paymentcard.paymentid = data_payment.PaymentId
							left JOIN CNF_PaymentCard						on cnf_paymentcard.paymentcardid = data_paymentcard.paymentcardid
							INNER JOIN CNF_PaymentMethod					on CNF_PaymentMethod.PaymentMethodId = data_payment.PaymentMethodId
							INNER JOIN COA_CNF_Account COA					on COA.COAAccountid = ISNULL(cnf_paymentcard.coaaccountid, CNF_PaymentMethod.COAAccountid)


						where data_payment.paymentstatus = 1
						and DATA_Transaction.TransactionType in (select transactionid
																from #TransactionIDs)
						and RR_DATA_REVENUE.fcalcdate = @BatchDate
						and @BatchDate between p.FromDate and p.ToDate
						AND data_payment.Transactionid not in (select distinct transactionid
													from rr_Data_Revenue
													where coaaccountid in (select distinct coaaccountid
																				from cnf_paymentmethod CP
																				where coaaccountid is not null
																				union all
																				select distinct coaaccountid
																				from cnf_paymentcard pc
																				where coaaccountid is not null
																			)
													)
						AND data_payment.Transactionid in (select distinct transactionid
													from rr_Data_Revenue
													where coaaccountid in (@ACCPaymentMethod)
													)
						 AND RR_DATA_REVENUE.coaaccountid not in (@ACCPaymentMethod)


		----Normal Sale Split out the Payments to Payment Fees
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays]
				   ,[attributeids])				    
				select distinct COA.COAAccountId, 
						   p.RevenueRecognitionRuleId,
						   p.RRCode,		   
						   p.RRCalcTypeWhere,
						   p.RRCalcTypeMethod,	   
						   p.COAAccountConfigId,
						   COA.COAAccountTypeId,
						   COA.Code,
						   RR_DATA_REVENUE.Transactionid as Transactionid,
						   RR_DATA_REVENUE.saleid as Saleid,
						   RR_DATA_REVENUE.Siteid as SiteID,
						   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
						   RR_DATA_REVENUE.Workstationid as Workstationid,
						   RR_DATA_REVENUE.UserGroupid as UserGroupID,
						   RR_DATA_REVENUE.UserId as userID,
						   @BatchDate,
						   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
							    else DATA_Transaction.transactiondate
						   end as TransDate,
						   0,
						   0,
						   0,
						   0,
						   100,
						   0,  	
						   data_payment.paymentfee as RevenueAmount,
						   case when data_payment.paymentfee &gt;= 0 then 2
						        else 1
							end accountingtype,		
						   p.RRCalcTypeTrigger,
						   p.RRPercentage,
						   p.RRDays,
						   RR_DATA_REVENUE.AttributeIDs

						from RR_DATA_REVENUE
						inner join rr_cnf_Product						ON ((RR_DATA_REVENUE.MATRIXCELLID = rr_cnf_Product.MATRIXCELLID) 
                                            or (RR_DATA_REVENUE.MatrixSheetId = rr_cnf_Product.MatrixSheetId)
											or (rr_cnf_product.Attributeid in (select top 1 Attributeid
																				from rr_cnf_product
																				where Attributeid in (select Value
																										from dbo.split((select rr.Attributeids
																														from rr_data_revenue rr
																														where rr.revenuerecognitiondataid = RR_DATA_REVENUE.revenuerecognitiondataid), '.')
																										)
																			)
												))
											and rr_cnf_Product.Enabled = 1
						inner join RR_CNF_RevenueRecognitionRule		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_cnf_Product.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  
						INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
						INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
						INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 
						INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
						INNER JOIN data_payment							on data_payment.transactionid = rr_data_revenue.transactionid
						left  JOIN DATA_PaymentCard						on data_paymentcard.paymentid = data_payment.PaymentId
						left JOIN CNF_PaymentCard						on cnf_paymentcard.paymentcardid = data_paymentcard.paymentcardid
						INNER JOIN CNF_PaymentMethod					on CNF_PaymentMethod.PaymentMethodId = data_payment.PaymentMethodId
						INNER JOIN COA_CNF_Account COA					on COA.COAAccountid = CNF_PaymentMethod.FeeCOAAccountId

						INNER JOIN (select transactionid, RevenueRecognitionRuleId, RR_DATA_Revenue.RRCode, RRCalcTypeWhere, 
											RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount,  Accountingtype
											from RR_DATA_Revenue
											INNER JOIN COA_CNF_Account		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
											where COA_CNF_Account.coaAccountID = @ACCPaymentMethod
										)p    on p.transactionid = 	data_payment.transactionid

					where data_payment.paymentstatus = 1
					and DATA_Transaction.TransactionType in (select transactionid
																from #TransactionIDs)
					and data_payment.paymentfee &lt;&gt; 0
					and RR_DATA_REVENUE.fcalcdate = @BatchDate
					and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
					AND data_payment.Transactionid not in (select distinct transactionid
												from rr_Data_Revenue
												where coaaccountid in (select distinct FeeCOAAccountId
																			from cnf_paymentmethod CP
																		)
												)
					AND data_payment.Transactionid in (select distinct transactionid
												from rr_Data_Revenue
												where coaaccountid in (@ACCPaymentMethod)
												)


							


		--	--Normal Transactions Reverse out of PaymentMethods
			INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays]
				   ,[AttributeIDs])				    					
				   select COAAccountId, 
						   Max(RevenueRecognitionRuleId),
						   Max(RRCode),		   
						   RRCalcTypeWhere,
						   RRCalcTypeMethod,	   
						   Max(COAAccountConfigId),
						   COAAccountTypeId,
						   COAAccountCode,
						   Transactionid,
						   saleid,
						   Siteid,
						   OperatingAreaId,
						   Workstationid,
						   UserGroupid,
						   UserId,
						   batchdate,
						   TransDate,
						   0,
						   0,
						   0,						
						   0,
						   0,
						   0,
						   ABS(sum(RevenueAmount)) as RevenueAmount,
				           case when accountingtype = 1 then 2
					        else 1
						   end Accountingtype,		
						   RRCalcTypeTrigger,
						   RRPercentage,
						   RRDays,
						   AttributeIDs
						   from (
							select distinct 
								       p.COAAccountId, 
									   p.RevenueRecognitionRuleId,
									   p.RRCode,		   
									   p.RRCalcTypeWhere,
									   p.RRCalcTypeMethod,	   
									   p.COAAccountConfigId,
									  p.COAAccountTypeId,
									   p.COAAccountCode,
									   rr_data_Revenue.Transactionid Transactionid,
									   rr_data_Revenue.saleid saleid,
									   rr_data_Revenue.Siteid siteid,
									   rr_data_Revenue.OperatingAreaId OperatingAreaid,
									   rr_data_Revenue.Workstationid workstationid,
									   rr_data_Revenue.UserGroupid usergroupid,
									   rr_data_Revenue.UserId userid,
									   @BatchDate batchdate,
									   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
											else DATA_Transaction.transactiondate
									   end as TransDate,
									   rr_data_Revenue.RevenueAmount *-1  as RevenueAmount,
								       p.Accountingtype,
									   transactiontype,		
									   p.RRCalcTypeTrigger,
									   p.RRPercentage,
									   p.RRDays,
									   rr_data_Revenue.AttributeIDs
							FROM rr_data_Revenue   				        WITH (NOLOCK)
								   INNER JOIN (select saleid, transactionid, RevenueRecognitionRuleId, RR_DATA_Revenue.RRCode, RRCalcTypeWhere, Saleitemid, RR_DATA_Revenue.COAAccountId, 
													   RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount, COA_CNF_Account.COAAccountTypeId,  Accountingtype,
													   RR_DATA_Revenue.COAAccountCode
													  from RR_DATA_Revenue
														INNER JOIN COA_CNF_Account		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
													 where COA_CNF_Account.coaAccountID = @ACCPaymentMethod
													   --and rr_data_revenue.RRCalcTypeTrigger = @Trigger
													)p								ON p.transactionid = 	rr_data_Revenue.transactionid
									INNER JOIN DATA_Transaction			on data_transaction.transactionid = rr_data_revenue.transactionid
							where RR_DATA_REVENUE.fcalcdate = @BatchDate
							  and DATA_Transaction.TransactionType in (select transactionid
																from #TransactionIDs)
							  and rr_data_Revenue.coaaccountid in (select distinct coaaccountid
																	 from cnf_paymentmethod
																	 where coaaccountid is not null
																	union all
																   select distinct coaaccountid
																	 from cnf_paymentcard
																	 where coaaccountid is not null
																  )
						)r	
							group by	 COAAccountId, 		   
									   RRCalcTypeWhere,
									   RRCalcTypeMethod,	   
									   COAAccountTypeId,
									   COAAccountCode,
									   Transactionid,
									   saleid,
									   Siteid,
									   OperatingAreaId,
									   Workstationid,
									   UserGroupid,
									   UserId,
									   batchdate,
									   TransDate,					
									   Accountingtype,		
									   RRCalcTypeTrigger,
									   RRPercentage,
									   RRDays, 
									   TransactionType, 
									   AttributeIDs


----Normal Sale Split out the Payments to Payment Fees
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays]
				   ,[AttributeIDs])				    
				select distinct COA.COAAccountId, 
						   p.RevenueRecognitionRuleId,
						   p.RRCode,		   
						   p.RRCalcTypeWhere,
						   p.RRCalcTypeMethod,	   
						   p.COAAccountConfigId,
						   COA.COAAccountTypeId,
						   COA.Code,
						   RR_DATA_REVENUE.Transactionid as Transactionid,
						   RR_DATA_REVENUE.saleid as Saleid,
						   RR_DATA_REVENUE.Siteid as SiteID,
						   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
						   RR_DATA_REVENUE.Workstationid as Workstationid,
						   RR_DATA_REVENUE.UserGroupid as UserGroupID,
						   RR_DATA_REVENUE.UserId as userID,
						   @BatchDate,
						   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
							    else DATA_Transaction.transactiondate
						   end as TransDate,
						   0,
						   0,
						   0,
						   0,
						   100,
						   0,  	
						  ABS(data_ledger.entryAmount) as RevenueAmount,
							case when data_ledger.entryAmount &gt;= 0 then 1
								else 2
							end accountingtype,		
							p.RRCalcTypeTrigger,
							p.RRPercentage,
							p.RRDays,
							RR_DATA_Revenue.AttributeIDs

						from RR_DATA_REVENUE
						inner join rr_cnf_Product						ON ((RR_DATA_REVENUE.MATRIXCELLID = rr_cnf_Product.MATRIXCELLID) 
                                            or (RR_DATA_REVENUE.MatrixSheetId = rr_cnf_Product.MatrixSheetId)
											or (rr_cnf_product.Attributeid in (select top 1 Attributeid
																				from rr_cnf_product
																				where Attributeid in (select Value
																										from dbo.split((select rr.Attributeids
																														from rr_data_revenue rr
																														where rr.revenuerecognitiondataid = RR_DATA_REVENUE.revenuerecognitiondataid), '.')
																										)
																			)
												))
											and rr_cnf_Product.Enabled = 1
						inner join RR_CNF_RevenueRecognitionRule		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_cnf_Product.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  

						INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
						INNER JOIN data_payment							on data_payment.transactionid = rr_data_revenue.transactionid
						left  JOIN DATA_PaymentCard						on data_paymentcard.paymentid = data_payment.PaymentId
						left JOIN CNF_PaymentCard						on cnf_paymentcard.paymentcardid = data_paymentcard.paymentcardid
						INNER JOIN CNF_PaymentMethod					on CNF_PaymentMethod.PaymentMethodId = data_payment.PaymentMethodId
						INNER JOIN COA_CNF_Account COA					on COA.COAAccountid = CNF_PaymentMethod.returnedcheckcoaaccountid
						INNER JOIN data_ledger							ON data_ledger.transactionid = data_transaction.transactionid
						INNER JOIN cnf_ledgeraccount					ON cnf_ledgeraccount.LedgerAccountId = data_ledger.ledgeraccountid
												INNER JOIN (select transactionid, RevenueRecognitionRuleId, RR_DATA_Revenue.RRCode, RRCalcTypeWhere, 
																	RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount,  Accountingtype
																	from RR_DATA_Revenue
																	INNER JOIN COA_CNF_Account		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
																	where COA_CNF_Account.coaAccountID = @ACCPaymentMethod
																)p    on p.transactionid = 	data_payment.transactionid


						where data_payment.paymentstatus = 1
							and DATA_Transaction.TransactionType in (select transactionid
																from #TransactionIDs)
							and DATA_Transaction.tip &lt;&gt; 0
							and RR_DATA_REVENUE.fcalcdate = @BatchDate
							and systemaccounttable = 119
							and systemaccountid = 15
							and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
							
																			
		End
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_RR_RevenueData_PaymentMethodTaxDiscounts]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_RR_RevenueData_PaymentMethodTaxDiscounts
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE Procedure dbo.otn_sp_RR_RevenueData_PaymentMethodTaxDiscounts
	@BatchDate Date,
	@Transactions varchar(500),
	@Trigger int,
	@RRTransDateType integer
AS 
BEGIN
	 
	Create Table #TransactionIDs(
	TransactionId Int NOT NULL)

	DECLARE @DelimPosition INT

    SET @DelimPosition = CHARINDEX(',', @Transactions)

    WHILE @DelimPosition &gt; 0
    BEGIN
        INSERT INTO #TransactionIDs(TransactionId)
            VALUES(CAST(RTRIM(LEFT(@Transactions, @DelimPosition - 1)) AS INT))
        SET @Transactions = right(@Transactions, len(@Transactions) - @DelimPosition)

        SET @DelimPosition = CHARINDEX(',', @Transactions)
    END

	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer

	Declare @OnCreditWriteoff Integer = 9
	Declare @StartTime DateTime

	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1
	

		--	--	--Normal Sale Split out the Payments to Smaller Subset.
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])				    
						select distinct COA.COAAccountId, 
						   p.RevenueRecognitionRuleId,
						   p.RRCode,		   
						   p.RRCalcTypeWhere,
						   p.RRCalcTypeMethod,	   
						   p.COAAccountConfigId,
						   COA.COAAccountTypeId,
						   COA.Code,
						   RR_DATA_REVENUE.Transactionid as Transactionid,
						   RR_DATA_REVENUE.saleid as Saleid,
						   RR_DATA_REVENUE.Siteid as SiteID,
						   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
						   RR_DATA_REVENUE.Workstationid as Workstationid,
						   RR_DATA_REVENUE.UserGroupid as UserGroupID,
						   RR_DATA_REVENUE.UserId as userID,
						   @BatchDate,
						   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
							    else DATA_Transaction.transactiondate
						   end as TransDate,
						   0,
						   0,
						   0,
						   0,
						   100,
						   0, 	
						   ABS ((data_payment.PaymentAmount) -
						   (case when data_payment.paymentid = (select top 1 paymentid
																from data_payment
																where transactionid = RR_DATA_REVENUE.Transactionid
																	and data_payment.paymentamount &gt; (select sum(Change) *-1
																								from data_transaction
																								where data_transaction.transactionid = RR_DATA_REVENUE.Transactionid))
								then (select sum(Change) *-1
																								from data_transaction
																								where data_transaction.transactionid = RR_DATA_REVENUE.Transactionid)
								else 0
							end ))
							as RevenueAmount,
							p.Accountingtype,		
						    p.RRCalcTypeTrigger,
						    p.RRPercentage,
						    p.RRDays

						from RR_DATA_REVENUE
						inner join rr_cnf_Product						ON ((RR_DATA_REVENUE.MATRIXCELLID = rr_cnf_Product.MATRIXCELLID) 
                                                      or (RR_DATA_REVENUE.MatrixSheetId = rr_cnf_Product.MatrixSheetId)
													  or (rr_cnf_product.Attributeid in (select top 1 Attributeid
																							from rr_cnf_product
																							where Attributeid in (select Value
																													from dbo.split((select rr.Attributeids
																																	from rr_data_revenue rr
																																	where rr.revenuerecognitiondataid = RR_DATA_REVENUE.revenuerecognitiondataid), '.')
																												   )
																					    )
															))
													  and rr_cnf_Product.Enabled = 1
						inner join RR_CNF_RevenueRecognitionRule		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_cnf_Product.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  
						INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
						INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
						INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 
						INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
						INNER JOIN data_payment							on data_payment.transactionid = rr_data_revenue.transactionid
						left  JOIN DATA_PaymentCard						on data_paymentcard.paymentid = data_payment.PaymentId
						left JOIN CNF_PaymentCard						on cnf_paymentcard.paymentcardid = data_paymentcard.paymentcardid
						INNER JOIN CNF_PaymentMethod					on CNF_PaymentMethod.PaymentMethodId = data_payment.PaymentMethodId
						INNER JOIN COA_CNF_Account COA					on COA.COAAccountid = ISNULL(cnf_paymentcard.coaaccountid, CNF_PaymentMethod.COAAccountid)

						INNER JOIN (select transactionid, RevenueRecognitionRuleId, RR_DATA_Revenue.RRCode, RRCalcTypeWhere, 
											RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount,  Accountingtype
											from RR_DATA_Revenue
											INNER JOIN COA_CNF_Account		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
											where COA_CNF_Account.coaAccountID = @ACCPaymentMethod
											--and RR_DATA_Revenue.RRCalcTypeTrigger = @Trigger
											and RR_DATA_REVENUE.fcalcdate = @BatchDate
										)p    on p.transactionid = 	data_payment.transactionid

					where data_payment.paymentstatus = 1
					and DATA_Transaction.TransactionType in (select transactionid
																from #TransactionIDs)
					and RR_DATA_REVENUE.fcalcdate = @BatchDate
					and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
					AND data_payment.Transactionid not in (select distinct transactionid
												from rr_Data_Revenue
												where coaaccountid in (select distinct coaaccountid
																			from cnf_paymentmethod CP
																			where coaaccountid is not null
																			union all
																			select distinct coaaccountid
																			from cnf_paymentcard pc
																			where coaaccountid is not null
																		)
												)
					AND data_payment.Transactionid in (select distinct transactionid
												from rr_Data_Revenue
												where coaaccountid in (@ACCPaymentMethod)
												)
					 AND RR_DATA_REVENUE.coaaccountid not in (@ACCPaymentMethod)


		----Normal Sale Split out the Payments to Payment Fees
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])				    
				select distinct COA.COAAccountId, 
						   p.RevenueRecognitionRuleId,
						   p.RRCode,		   
						   p.RRCalcTypeWhere,
						   p.RRCalcTypeMethod,	   
						   p.COAAccountConfigId,
						   COA.COAAccountTypeId,
						   COA.Code,
						   RR_DATA_REVENUE.Transactionid as Transactionid,
						   RR_DATA_REVENUE.saleid as Saleid,
						   RR_DATA_REVENUE.Siteid as SiteID,
						   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
						   RR_DATA_REVENUE.Workstationid as Workstationid,
						   RR_DATA_REVENUE.UserGroupid as UserGroupID,
						   RR_DATA_REVENUE.UserId as userID,
						   @BatchDate,
						   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
							    else DATA_Transaction.transactiondate
						   end as TransDate,
						   0,
						   0,
						   0,
						   0,
						   100,
						   0,  	
						   data_payment.paymentfee as RevenueAmount,
						   case when data_payment.paymentfee &gt;= 0 then 2
						        else 1
							end accountingtype,		
						   p.RRCalcTypeTrigger,
						   p.RRPercentage,
						   p.RRDays

						from RR_DATA_REVENUE
						inner join rr_cnf_Product						ON ((RR_DATA_REVENUE.MATRIXCELLID = rr_cnf_Product.MATRIXCELLID) 
                                                      or (RR_DATA_REVENUE.MatrixSheetId = rr_cnf_Product.MatrixSheetId)
													  or (rr_cnf_product.Attributeid in (select top 1 Attributeid
																							from rr_cnf_product
																							where Attributeid in (select Value
																													from dbo.split((select rr.Attributeids
																																	from rr_data_revenue rr
																																	where rr.revenuerecognitiondataid = RR_DATA_REVENUE.revenuerecognitiondataid), '.')
																												   )
																					    )
															))
													  and rr_cnf_Product.Enabled = 1
						inner join RR_CNF_RevenueRecognitionRule		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_cnf_Product.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  
						INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
						INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
						INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 
						INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
						INNER JOIN data_payment							on data_payment.transactionid = rr_data_revenue.transactionid
						left  JOIN DATA_PaymentCard						on data_paymentcard.paymentid = data_payment.PaymentId
						left JOIN CNF_PaymentCard						on cnf_paymentcard.paymentcardid = data_paymentcard.paymentcardid
						INNER JOIN CNF_PaymentMethod					on CNF_PaymentMethod.PaymentMethodId = data_payment.PaymentMethodId
						INNER JOIN COA_CNF_Account COA					on COA.COAAccountid = CNF_PaymentMethod.FeeCOAAccountId

						INNER JOIN (select transactionid, RevenueRecognitionRuleId, RR_DATA_Revenue.RRCode, RRCalcTypeWhere, 
											RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount,  Accountingtype
											from RR_DATA_Revenue
											INNER JOIN COA_CNF_Account		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
											where COA_CNF_Account.coaAccountID = @ACCPaymentMethod
										)p    on p.transactionid = 	data_payment.transactionid

					where data_payment.paymentstatus = 1
					and DATA_Transaction.TransactionType in (select transactionid
																from #TransactionIDs)
					and data_payment.paymentfee &lt;&gt; 0
					and RR_DATA_REVENUE.fcalcdate = @BatchDate
					and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
					AND data_payment.Transactionid not in (select distinct transactionid
												from rr_Data_Revenue
												where coaaccountid in (select distinct FeeCOAAccountId
																			from cnf_paymentmethod CP
																		)
												)
					AND data_payment.Transactionid in (select distinct transactionid
												from rr_Data_Revenue
												where coaaccountid in (@ACCPaymentMethod)
												)


		--	--Normal Transactions Reverse out of PaymentMethods
			INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])				    					
					select COAAccountId, 
						   Max(RevenueRecognitionRuleId),
						   Max(RRCode),		   
						   RRCalcTypeWhere,
						   RRCalcTypeMethod,	   
						   Max(COAAccountConfigId),
						   COAAccountTypeId,
						   COAAccountCode,
						   Transactionid,
						   saleid,
						   Siteid,
						   OperatingAreaId,
						   Workstationid,
						   UserGroupid,
						   UserId,
						   batchdate,
						   TransDate,
						   0,
						   0,
						   0,						
						   0,
						   0,
						   0,
						   ABS(sum(RevenueAmount)) as RevenueAmount,
						   case when accountingtype = 1 then 2
								else 1
							end Accountingtype,		
						   RRCalcTypeTrigger,
						   RRPercentage,
						   RRDays
						   from (
			select distinct rr_data_Revenue.coaaccountid as rrcoaaccountid,
								       p.COAAccountId, 
									   p.RevenueRecognitionRuleId,
									   p.RRCode,		   
									   p.RRCalcTypeWhere,
									   p.RRCalcTypeMethod,	   
									   p.COAAccountConfigId,
									   p.COAAccountTypeId,
									   p.COAAccountCode,
									   rr_data_Revenue.Transactionid Transactionid,
									   rr_data_Revenue.saleid saleid,
									   rr_data_Revenue.Siteid siteid,
									   rr_data_Revenue.OperatingAreaId OperatingAreaid,
									   rr_data_Revenue.Workstationid workstationid,
									   rr_data_Revenue.UserGroupid usergroupid,
									   rr_data_Revenue.UserId userid,
									   @BatchDate batchdate,
									   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
											else DATA_Transaction.transactiondate
									   end as TransDate,
									   rr_data_Revenue.RevenueAmount  as RevenueAmount,
								       p.Accountingtype,
									   transactiontype,		
									   p.RRCalcTypeTrigger,
									   p.RRPercentage,
									   p.RRDays

							FROM rr_data_Revenue   				        WITH (NOLOCK)
								   INNER JOIN (select saleid, transactionid, RevenueRecognitionRuleId, RR_DATA_Revenue.RRCode, RRCalcTypeWhere, Saleitemid, RR_DATA_Revenue.COAAccountId, 
													   RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount, COA_CNF_Account.COAAccountTypeId,  Accountingtype,
													   RR_DATA_Revenue.COAAccountCode
													  from RR_DATA_Revenue
														INNER JOIN COA_CNF_Account		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
													 where COA_CNF_Account.coaAccountID = @ACCPaymentMethod
													-- and rr_data_Revenue.RRCalcTypeTrigger = @Trigger
													)p								ON p.transactionid = 	rr_data_Revenue.transactionid
									INNER JOIN DATA_Transaction			on data_transaction.transactionid = rr_data_revenue.transactionid
							where RR_DATA_REVENUE.fcalcdate = @BatchDate
							  
							  and DATA_Transaction.TransactionType in (select transactionid
																from #TransactionIDs)
							  and rr_data_Revenue.coaaccountid in (select distinct coaaccountid
																	 from cnf_paymentmethod
																	 where coaaccountid is not null
																	union all
																   select distinct coaaccountid
																	 from cnf_paymentcard
																	 where coaaccountid is not null

																  )
						)r	
							group by	 COAAccountId, 		   
									   RRCalcTypeWhere,
									   RRCalcTypeMethod,	   
									   COAAccountTypeId,
									   COAAccountCode,
									   Transactionid,
									   saleid,
									   Siteid,
									   OperatingAreaId,
									   Workstationid,
									   UserGroupid,
									   UserId,
									   batchdate,
									   TransDate,					
									   Accountingtype,		
									   RRCalcTypeTrigger,
									   RRPercentage,
									   RRDays, 
									   TransactionType
							

----Normal Sale Split out the Payments to returned Checks
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])				    
				select distinct COA.COAAccountId, 
						   p.RevenueRecognitionRuleId,
						   p.RRCode,		   
						   p.RRCalcTypeWhere,
						   p.RRCalcTypeMethod,	   
						   p.COAAccountConfigId,
						   COA.COAAccountTypeId,
						   COA.Code,
						   RR_DATA_REVENUE.Transactionid as Transactionid,
						   RR_DATA_REVENUE.saleid as Saleid,
						   RR_DATA_REVENUE.Siteid as SiteID,
						   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
						   RR_DATA_REVENUE.Workstationid as Workstationid,
						   RR_DATA_REVENUE.UserGroupid as UserGroupID,
						   RR_DATA_REVENUE.UserId as userID,
						   @BatchDate,
						   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
							    else DATA_Transaction.transactiondate
						   end as TransDate,
						   0,
						   0,
						   0,
						   0,
						   100,
						   0,  	
						  ABS(data_ledger.entryAmount) as RevenueAmount,
							case when data_ledger.entryAmount &gt;= 0 then 1
								else 2
							end accountingtype,		
							p.RRCalcTypeTrigger,
							p.RRPercentage,
							p.RRDays

						from RR_DATA_REVENUE
						inner join rr_cnf_Product						ON ((RR_DATA_REVENUE.MATRIXCELLID = rr_cnf_Product.MATRIXCELLID) 
                                            or (RR_DATA_REVENUE.MatrixSheetId = rr_cnf_Product.MatrixSheetId)
											or (rr_cnf_product.Attributeid in (select top 1 Attributeid
																				from rr_cnf_product
																				where Attributeid in (select Value
																										from dbo.split((select rr.Attributeids
																														from rr_data_revenue rr
																														where rr.revenuerecognitiondataid = RR_DATA_REVENUE.revenuerecognitiondataid), '.')
																										)
																			)
												))
											and rr_cnf_Product.Enabled = 1
						inner join RR_CNF_RevenueRecognitionRule		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_cnf_Product.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  

						INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
						INNER JOIN data_payment							on data_payment.transactionid = rr_data_revenue.transactionid
						left  JOIN DATA_PaymentCard						on data_paymentcard.paymentid = data_payment.PaymentId
						left JOIN CNF_PaymentCard						on cnf_paymentcard.paymentcardid = data_paymentcard.paymentcardid
						INNER JOIN CNF_PaymentMethod					on CNF_PaymentMethod.PaymentMethodId = data_payment.PaymentMethodId
						INNER JOIN COA_CNF_Account COA					on COA.COAAccountid = CNF_PaymentMethod.returnedcheckcoaaccountid
						INNER JOIN data_ledger							ON data_ledger.transactionid = data_transaction.transactionid
						INNER JOIN cnf_ledgeraccount					ON cnf_ledgeraccount.LedgerAccountId = data_ledger.ledgeraccountid
												INNER JOIN (select transactionid, RevenueRecognitionRuleId, RR_DATA_Revenue.RRCode, RRCalcTypeWhere, 
																	RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount,  Accountingtype
																	from RR_DATA_Revenue
																	INNER JOIN COA_CNF_Account		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
																	where COA_CNF_Account.coaAccountID = @ACCPaymentMethod
																)p    on p.transactionid = 	data_payment.transactionid


						where data_payment.paymentstatus = 1
							and DATA_Transaction.TransactionType in (select transactionid
																from #TransactionIDs)
							and DATA_Transaction.tip &lt;&gt; 0
							and RR_DATA_REVENUE.fcalcdate = @BatchDate
							and systemaccounttable = 119
							and systemaccountid = 15
							and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate

				--Normal Transaction break out Tax
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])				    
						  select COAAccountId, 
						   MIN(p.RevenueRecognitionRuleId),
						   MIN(p.RRCode),		   
						   RRCalcTypeWhere,
						   RRCalcTypeMethod,	   
						   COAAccountConfigId,
						   COAAccountTypeId,
						   COACODE,
						   Transactionid,
						   saleid,
						   Siteid,
						   OperatingAreaId,
						   Workstationid,
						   UserGroupid,
						   UserId,
						   batchdate,
						   TransDate,
						   0,
						   0,
						   0,						
						   price,
						   percentage,
						   test,
						   ABS(sum(RevenueAmount)) as RevenueAmount,
				           case when TransactionType in (5, 17, 18, 20, 22, 30) and sum(RevenueAmount) &lt;= 0  then 1
						        when TransactionType in (5, 17, 18, 20, 22, 30) and sum(RevenueAmount) &lt;= 0  then 2
								when TransactionType in (7) and sum(RevenueAmount) &lt;= 0  then 1
								when TransactionType in (7) and sum(RevenueAmount) &gt; 0  then 2
								else Accountingtype
							end Accountingtype,		
						   RRCalcTypeTrigger,
						   RRPercentage,
						   RRDays
						   
						   from (
						  select distinct COA.COAAccountId, 
						   min(p.RevenueRecognitionRuleId) RevenueRecognitionRuleId,
						   min(p.rrcode) rrcode,		   
						   RR_DATA_REVENUE.RRCalcTypeWhere,
						   RR_DATA_REVENUE.RRCalcTypeMethod,	   
						   RR_DATA_REVENUE.COAAccountConfigId,
						   COA.COAAccountTypeId,
						   COA.Code COACODE,
						   RR_DATA_REVENUE.Transactionid as Transactionid,
						   RR_DATA_REVENUE.saleid as Saleid,
						   RR_DATA_REVENUE.Siteid as SiteID,
						   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
						   RR_DATA_REVENUE.Workstationid as Workstationid,
						   RR_DATA_REVENUE.UserGroupid as UserGroupID,
						   RR_DATA_REVENUE.UserId as userID,
						   @BatchDate as batchdate,
						   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
							    else DATA_Transaction.transactiondate
						   end as TransDate,
						   0 as Quantity,
						   0 as GrossAmount,
						   0 as NetAmount,
						   0 as price,
						   100 as percentage,
						   0 as test, 	
						   taxamount RevenueAmount,
						   Transactiontype,
							p.Accountingtype,					   		
						   RR_DATA_REVENUE.RRCalcTypeTrigger,
						   RR_DATA_REVENUE.RRPercentage,
						   RR_DATA_REVENUE.RRDays

					from RR_DATA_REVENUE
						inner join rr_cnf_Product						ON ((RR_DATA_REVENUE.MATRIXCELLID = rr_cnf_Product.MATRIXCELLID) 
                                            or (RR_DATA_REVENUE.MatrixSheetId = rr_cnf_Product.MatrixSheetId)
											or (rr_cnf_product.Attributeid in (select top 1 Attributeid
																				from rr_cnf_product
																				where Attributeid in (select Value
																										from dbo.split((select rr.Attributeids
																														from rr_data_revenue rr
																														where rr.revenuerecognitiondataid = RR_DATA_REVENUE.revenuerecognitiondataid), '.')
																										)
																			)
												))
											and rr_cnf_Product.Enabled = 1
						inner join RR_CNF_RevenueRecognitionRule		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_cnf_Product.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  
						INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
						INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
						INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 
						INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
						INNER JOIN DATA_TransactionTax					on data_transactiontax.transactionid = data_transaction.transactionid
						INNER JOIN CNF_Tax								on cnf_tax.taxid = DATA_TransactionTax.taxid
						INNER JOIN coa_cnf_account coa					on coa.coaaccountid = cnf_tax.coaaccountid
							INNER JOIN (select saleid, transactionid, RevenueRecognitionRuleId, RR_DATA_Revenue.RRCode, RRCalcTypeWhere, Saleitemid, RR_DATA_Revenue.coaaccountid,
												RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount,  Accountingtype
												from RR_DATA_Revenue
												INNER JOIN COA_CNF_Account		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
												where COA_CNF_Account.coaAccountID = @TaxAccountID
												--and rr_data_Revenue.RRCalcTypeTrigger = @Trigger
												and RR_DATA_REVENUE.fcalcdate = @BatchDate
											)p    on p.transactionid = 	data_transactiontax.transactionid
					where RR_DATA_REVENUE.coaaccountid = 1
					and RR_DATA_REVENUE.fcalcdate = @BatchDate
					and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @Trigger
					and TransactionType in (select transactionid
														from #TransactionIDs)
					and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
					AND DATA_Transaction.Transactionid not in (select distinct transactionid
																	from rr_Data_Revenue
																	where coaaccountid in (select distinct coaaccountid
																								from cnf_tax 
																							)
																	)
					group by COA.COAAccountId,    
						   RR_DATA_REVENUE.RRCalcTypeWhere,
						   RR_DATA_REVENUE.RRCalcTypeMethod,	   
						   RR_DATA_REVENUE.COAAccountConfigId,
						   COA.COAAccountTypeId,
						   COA.Code,
						   RR_DATA_REVENUE.Transactionid,
						   RR_DATA_REVENUE.saleid,
						   RR_DATA_REVENUE.Siteid,
						   RR_DATA_REVENUE.OperatingAreaId,
						   RR_DATA_REVENUE.Workstationid,
						   RR_DATA_REVENUE.UserGroupid,
						   RR_DATA_REVENUE.UserId,
						   DATA_Transaction.ftransactiondate, 
						   DATA_Transaction.transactiondate,
						   taxamount,
						   Transactiontype,
							p.Accountingtype,					   		
						   RR_DATA_REVENUE.RRCalcTypeTrigger,
						   RR_DATA_REVENUE.RRPercentage,
						   RR_DATA_REVENUE.RRDays,
						   AttributeIDs

					)p
					where revenueamount &lt;&gt; 0
					group by COAAccountId, 	   
							RRCalcTypeWhere,
							RRCalcTypeMethod,	   
							COAAccountConfigId,
							COAAccountTypeId,
							COACODE,
							Transactionid,
							saleid,
							Siteid,
							OperatingAreaId,
							Workstationid,
							UserGroupid,
							UserId,
							TransDate,
							Accountingtype,		
							RRCalcTypeTrigger,
							RRPercentage,
							RRDays,
							price,
							percentage,
							test,
							batchdate,
							TransactionType


																									
		--	--------Reverse Tax Out
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])	
				      select  COAAccountId, 
									   RevenueRecognitionRuleId,
									   RRCode,		   
									   RRCalcTypeWhere,
									   RRCalcTypeMethod,	   
									   COAAccountConfigId,
									   COAAccountTypeId,
									   COAAccountCode,
									   Transactionid,
									   saleid,
									   siteid,
									   OperatingAreaid,
									   workstationid,
									   usergroupid,
									   userid,
									   batchdate,
									   TransDate,
									   Quantity,
									   grossamount,
									   netamount,
									   price,
									   percentage,
									   tax,
									   ABS(sum(RevenueAmount))  as RevenueAmount,
									    case when p.accountingtype = 1 then 2
											else 1
										end Accountingtype,	
									   RRCalcTypeTrigger,
									   RRPercentage,
									   RRDays
					  from (		    
				             select distinct 
								       p.COAAccountId, 
									   p.RevenueRecognitionRuleId,
									   p.RRCode,		   
									   p.RRCalcTypeWhere,
									   p.RRCalcTypeMethod,	   
									   p.COAAccountConfigId,
									   p.COAAccountTypeId,
									   p.COAAccountCode,
									   rr_data_Revenue.Transactionid Transactionid,
									   rr_data_Revenue.saleid saleid,
									   rr_data_Revenue.Siteid siteid,
									   rr_data_Revenue.OperatingAreaId OperatingAreaid,
									   rr_data_Revenue.Workstationid workstationid,
									   rr_data_Revenue.UserGroupid usergroupid,
									   rr_data_Revenue.UserId userid,
									   @BatchDate batchdate,
									   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
											else DATA_Transaction.transactiondate
									   end as TransDate,
									   rr_data_Revenue.Quantity Quantity,
									   rr_data_Revenue.GrossAmount grossamount,
									   rr_data_Revenue.NetAmount netamount,
									   0 price,
									   100 percentage,
									   0 tax,
									   rr_data_Revenue.RevenueAmount  as RevenueAmount,
									   data_transaction.transactiontype,
								       p.Accountingtype,		
									   p.RRCalcTypeTrigger,
									   p.RRPercentage,
									   p.RRDays

							FROM rr_data_Revenue   				        WITH (NOLOCK)
								   INNER JOIN (select saleid, transactionid, RevenueRecognitionRuleId, RR_DATA_Revenue.RRCode, RRCalcTypeWhere, Saleitemid, RR_DATA_Revenue.COAAccountId, 
													   RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount, COA_CNF_Account.COAAccountTypeId,  Accountingtype,
													   RR_DATA_Revenue.COAAccountCode
													  from RR_DATA_Revenue
														INNER JOIN COA_CNF_Account		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
													 where COA_CNF_Account.coaAccountID = @TaxAccountID
													)p								ON p.Transactionid = 	rr_data_Revenue.Transactionid
									INNER JOIN data_transaction						on data_transaction.transactionid = rr_data_revenue.transactionid

							where RR_DATA_REVENUE.fcalcdate = @BatchDate
							  and rr_data_Revenue.RRCalcTypeTrigger = @Trigger
							  and DATA_Transaction.TransactionType in (select transactionid
																		from #TransactionIDs)
							  and rr_data_Revenue.coaaccountid in (select distinct coaaccountid
						                                             from cnf_tax
																    where coaaccountid is not null
															      )
							)p
							group by   COAAccountId, 
									   RevenueRecognitionRuleId,
									   RRCode,		   
									   RRCalcTypeWhere,
									   RRCalcTypeMethod,	   
									   COAAccountConfigId,
									   COAAccountTypeId,
									   COAAccountCode,
									   Transactionid,
									   saleid,
									   siteid,
									   OperatingAreaid,
									   workstationid,
									   usergroupid,
									   userid,
									   batchdate,
									   TransDate,
									   Quantity,
									   grossamount,
									   netamount,
									   price,
									   percentage,
									   tax,
								       Accountingtype,		
									   RRCalcTypeTrigger,
									   RRPercentage,
									   RRDays,
									   TransactionType


		----		--Normal Transaction Break out the discounts
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])
				   select *
				   from (				    
						select distinct COA.COAAccountId, 
						   RR_DATA_REVENUE.RevenueRecognitionRuleId,
						   RR_DATA_REVENUE.RRCode,		   
						   RR_DATA_REVENUE.RRCalcTypeWhere,
						   RR_DATA_REVENUE.RRCalcTypeMethod,	   
						   RR_DATA_REVENUE.COAAccountConfigId,
						   COA.COAAccountTypeId,
						   COA.Code,
						   RR_DATA_REVENUE.Transactionid as Transactionid,
						   RR_DATA_REVENUE.saleid as Saleid,
						   RR_DATA_REVENUE.Siteid as SiteID,
						   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
						   RR_DATA_REVENUE.Workstationid as Workstationid,
						   RR_DATA_REVENUE.UserGroupid as UserGroupID,
						   RR_DATA_REVENUE.UserId as userID,
						   @BatchDate as batchdate,
						   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
							    else DATA_Transaction.transactiondate
						   end as TransDate,
						   0 as quantity,
						   0 as grossamount,
						   0 as netamount,
						   0 as price,
						   100 as percentage,
						   0 as remaningValues, 	
						   abs(DATA_SaleItemRule.discountamount)
							as RevenueAmount,
						   p.Accountingtype,		
						   RR_DATA_REVENUE.RRCalcTypeTrigger,
						   RR_DATA_REVENUE.RRPercentage,
						   RR_DATA_REVENUE.RRDays

					from RR_DATA_REVENUE
						inner join rr_cnf_Product						ON ((RR_DATA_REVENUE.MATRIXCELLID = rr_cnf_Product.MATRIXCELLID) 
											or (RR_DATA_REVENUE.MatrixSheetId = rr_cnf_Product.MatrixSheetId)
											or (rr_cnf_product.Attributeid in (select top 1 Attributeid
																				from rr_cnf_product
																				where Attributeid in (select Value
																										from dbo.split((select rr.Attributeids
																														from rr_data_revenue rr
																														where rr.revenuerecognitiondataid = RR_DATA_REVENUE.revenuerecognitiondataid), '.')
																										)
																			)
												))
											and rr_cnf_Product.Enabled = 1
						inner join RR_CNF_RevenueRecognitionRule		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_cnf_Product.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  
						INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
						INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
						INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 
						INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
						LEFT  JOIN DATA_Sale				            ON DATA_Sale.SaleID = data_transaction.SaleID
						LEFT  JOIN DATA_SaleItem			            ON DATA_SaleItem.saleitemid = RR_DATA_REVENUE.saleitemid
						LEFT JOIN DATA_SaleItemRule						ON data_saleitemrule.saleitemid = DATA_SaleItem.saleitemid	 
						LEFT JOIN CNF_PromotionItemRule					ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
						LEFT JOIN CNF_PromotionItem						ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
						LEFT JOIN CNF_Promotion							ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId	
						LEFT JOIN COA_CNF_Account	COA			        ON COA.coaaccountid = CNF_Promotion.coaaccountid
						
						
						INNER JOIN (select transactionid, RevenueRecognitionRuleId, RR_DATA_Revenue.RRCode, RRCalcTypeWhere, 
											RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount,  Accountingtype
											from RR_DATA_Revenue
											INNER JOIN COA_CNF_Account		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
											where COA_CNF_Account.coaAccountID = @DiscountAccountID
										)p    on p.transactionid = 	DATA_Transaction.transactionid



					where COA_CNF_AccountConfig.coaaccountid in (@DiscountAccountID)
					and RR_DATA_REVENUE.coaaccountid = 1
					and DATA_Transaction.TransactionType in (select transactionid
																from #TransactionIDs)
					and RR_DATA_REVENUE.fcalcdate = @BatchDate
					and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
					AND DATA_Transaction.Transactionid not in (select distinct transactionid
																	from rr_Data_Revenue
																	where coaaccountid in (select distinct coaaccountid
																								from CNF_Promotion
																								where coaaccountid is not null 
																							)
																	)	
					)p
					where revenueamount &lt;&gt; 0	
					  and coaaccountid is not null													
																																								
		--		--Reverse out Discounts														
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[Saleitemid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])			    
				select distinct p.COAAccountId, 
						   p.RevenueRecognitionRuleId,
						   p.RRCode,		   
						   p.RRCalcTypeWhere,
						   p.RRCalcTypeMethod,	   
						   p.COAAccountConfigId,
						   p.COAAccountTypeId,
						   p.COAAccountCode,
						   rr_data_Revenue.Transactionid,
						   rr_data_Revenue.saleid,
						   rr_data_Revenue.saleitemid,
						   rr_data_Revenue.Siteid,
						   rr_data_Revenue.OperatingAreaId,
						   rr_data_Revenue.Workstationid,
						   rr_data_Revenue.UserGroupid,
						   rr_data_Revenue.UserId,
						   @BatchDate,
						   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
							    else DATA_Transaction.transactiondate
						   end as TransDate,
						   0,
						   0,
						   0,
						   0,
						   100,
						   0,
						   rr_data_Revenue.RevenueAmount  as RevenueAmount,
						   case when p.accountingtype = 1 then 2
					        else 1
						   end Accountingtype,
						   p.RRCalcTypeTrigger,
						   p.RRPercentage,
						   p.RRDays

						  FROM rr_data_Revenue   				        WITH (NOLOCK)
								   INNER JOIN (select saleid, transactionid, RevenueRecognitionRuleId, RR_DATA_Revenue.RRCode, RRCalcTypeWhere, Saleitemid, RR_DATA_Revenue.COAAccountId, 
													   RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount, COA_CNF_Account.COAAccountTypeId,  Accountingtype,
													   RR_DATA_Revenue.COAAccountCode
													  from RR_DATA_Revenue
														INNER JOIN COA_CNF_Account		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
													 where COA_CNF_Account.coaAccountID = @DiscountAccountID
													)p								ON p.saleid = 	rr_data_Revenue.saleid
								INNER JOIN data_transaction        on data_transaction.transactionid = rr_data_revenue.transactionid

						where  rr_data_Revenue.coaaccountid in (select distinct coaaccountid
						                                         from CNF_Promotion
															  )
						 and RR_DATA_REVENUE.fcalcdate = @BatchDate
						 and DATA_Transaction.TransactionType in (select transactionid
															from #TransactionIDs)
																																																																																											

		
		End
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_RR_RevenueData_OnTimePeriodTrigger]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_RR_RevenueData_OnTimePeriodTrigger
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE Procedure dbo.otn_sp_RR_RevenueData_OnTimePeriodTrigger
	@BatchDate Date,
	@RRTransDateType Integer
AS 
BEGIN
	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer
	Declare @OnTimePeriodTrigger Integer = 4	

	create table #RulesToRun
	(
		RRID int
	)

	Declare @TodayDayofWeek Int
	Declare @TodaySpecificDay Int
	Declare @TodayMonthlyWeek Int
	Declare @TodayMonth Int
	Declare @TodayDay Int
	Declare @TodayDaysofWeek Int

	select @TodayDayofWeek   = datePart(weekday, cast(@BatchDate as date)),
		   @TodayMonth       = datePart(mm, cast(@BatchDate as date)),
		   @TodaySpecificDay = datePart(dd, cast(@BatchDate as date)),
		   @TodayMonthlyWeek = datediff(week, dateadd(week, datediff(week, 0, dateadd(month, datediff(month, 0, cast(@BatchDate as date)), 0)), 0), getdate() - 1) + 1

	if @TodayDaysofWeek = 6 
	   SET @TodayDaysofWeek = 1

	insert into #RulesToRun
	select	distinct RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
		from RR_CNF_RevenueRecognitionRuleSchedule
			INNER JOIN RR_CNF_RevenueRecognitionRule					ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRuleSchedule.RevenueRecognitionRuleId

	where RR_CNF_RevenueRecognitionRule.Enabled = 1
	  and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
	  and ((PeriodOption = 1)
			  or ((PeriodOption = 2) and (((@TodayDayofWeek = 1) and (ActiveSunday = 1))
											or ((@TodayDayofWeek = 2) and (ActiveMonday = 1))
											or ((@TodayDayofWeek = 3) and (ActiveTuesday = 1))
											or ((@TodayDayofWeek = 4) and (ActiveWednesday = 1))
											or ((@TodayDayofWeek = 5) and (ActiveThursday = 1))
											or ((@TodayDayofWeek = 6) and (ActiveFriday = 1))
											or ((@TodayDayofWeek = 6) and (ActiveFriday = 1))
											or ((@TodayDayofWeek = 7) and (ActiveSaturday = 1))
										)))
			 or ((PeriodOption = 3) and ((SpecificDay = @TodaySpecificDay) 
										  or ((WeekOption = @TodayMonthlyWeek and (((@TodayDayofWeek = 1) and (ActiveSunday = 1))
																					or ((@TodayDayofWeek = 2) and (ActiveMonday = 1))
																					or ((@TodayDayofWeek = 3) and (ActiveTuesday = 1))
																					or ((@TodayDayofWeek = 4) and (ActiveWednesday = 1))
																					or ((@TodayDayofWeek = 5) and (ActiveThursday = 1))
																					or ((@TodayDayofWeek = 6) and (ActiveFriday = 1))
																					or ((@TodayDayofWeek = 6) and (ActiveFriday = 1))
																					or ((@TodayDayofWeek = 7) and (ActiveSaturday = 1))
																					or (LastDayOptionWeek = 1))
																				))))  
			 or ((PeriodOption = 4) and (((SpecificDay = @TodaySpecificDay) and (MonthOption = @TodayMonth))  
										   or ((WeekOption = @TodayMonthlyWeek and (((@TodayDayofWeek = 1) and (ActiveSunday = 1))
																					or ((@TodayDayofWeek = 2) and (ActiveMonday = 1))
																					or ((@TodayDayofWeek = 3) and (ActiveTuesday = 1))
																					or ((@TodayDayofWeek = 4) and (ActiveWednesday = 1))
																					or ((@TodayDayofWeek = 5) and (ActiveThursday = 1))
																					or ((@TodayDayofWeek = 6) and (ActiveFriday = 1))
																					or ((@TodayDayofWeek = 6) and (ActiveFriday = 1))
																					or ((@TodayDayofWeek = 7) and (ActiveSaturday = 1))
																					or (LastDayOptionWeek = 1))
																				)))
																				and (MonthOption = @TodayMonth))



			INSERT INTO [dbo].[RR_DATA_Revenue]
						   ([COAAccountId]
						   ,[RevenueRecognitionRuleId]
						   ,[RRCode]
						   ,[RRCalcTypeWhere]
						   ,[RRCalcTypeMethod]
						   ,[COAAccountConfigId]
						   ,[COAAccountType]
						   ,[COAAccountCode]
						   ,[SaleId]
						   ,[Ticketid]
						   ,[MatrixCellid]
						   ,[MatrixCellCode]
						   ,[MatrixSheetid]
						   ,[SiteId]
						   ,[OperatingAreaId]
						   ,[WorkstationId]
						   ,[Usergroupid]
						   ,[UserId]
						   ,[FCalcDate]
						   ,[FRevenueDate]
						   ,[Quantity]
						   ,[GrossAmount]
						   ,[NetAmount]
						   ,[Price]
						   ,[Percentage]
						   ,[RemaningValues]
						   ,[RevenueAmount]
						   ,[AccountingType]
						   ,[RRCalcTypeTrigger]
						   ,[RRPercentage]			
						   ,[RRDays]
						   ,[AttributeIDs]
						   )
						   select *
						   from (
							select distinct p.COAAccountId, 
								   p.RevenueRecognitionRuleId,
								   p.RRcode,		   
								   p.RRCalcTypeWhere,
								   p.RRCalcTypeMethod,	   
								   p.COAAccountConfigId,
								   p.COAAccountTypeId,
								   p.AccountCode as AccountCode,
								   RR_DATA_REVENUE.saleid as Saleid,
								   ISNULL(rdata.Ticketid, DATA_SaleItem2Ticket.Ticketid) TicketID, 
								   RR_DATA_REVENUE.Matrixcellid,
								   RR_DATA_REVENUE.MatrixcellCode,
								   RR_DATA_REVENUE.MatrixSheetId,
								   RR_DATA_REVENUE.Siteid,
								   RR_DATA_REVENUE.OperatingAreaId,
								   RR_DATA_REVENUE.Workstationid,
								   RR_DATA_REVENUE.UserGroupid,
								   RR_DATA_REVENUE.UserId as userID,
								   @BatchDate as BatchDate,
								   @BatchDate as TransDate,
								   RR_DATA_REVENUE.Quantity as Quantity,
								   RR_DATA_REVENUE.GrossAmount as GrossAmount,
								   RR_DATA_REVENUE.NetAmount as NetAmount,
								   p.Price as ConfigPrice,
								   p.Percentage as ConfigPercentage,
								   p.RemainingValues,																		
								  Case when p.Price &gt; 0 then (p.Price) 
									   else case when ((((DATA_Ticket.Price - DATA_Ticket.taxes) - ISNULL(rdata.TotalUsed, 0)) &gt; 0) and ((DATA_Ticket.Price - DATA_Ticket.taxes) - ISNULL(rdata.TotalUsed, 0)) &gt;= ((((DATA_Ticket.Price - DATA_Ticket.taxes) * p.RRPercentage)/100 * p.Percentage)/100)) 
										              then ((((DATA_Ticket.Price - DATA_Ticket.taxes) * p.RRPercentage)/100 * p.Percentage)/100)
									              else (((DATA_Ticket.Price - DATA_Ticket.taxes) - ISNULL(rdata.TotalUsed, 0)) * p.Percentage)/100
								            end
							       end as RevenueAmount,
								   p.Accountingtype,
								   p.RRCalcTypeTrigger,
								   p.RRPercentage,
								   p.Days,
								   RR_DATA_REVENUE.AttributeIDs

							from RR_DATA_REVENUE
								INNER JOIN DATA_SaleItem							ON data_saleitem.SaleItemId		   = rr_data_revenue.saleitemid
								INNER JOIN DATA_SaleItem2Ticket						on data_saleitem2ticket.Saleitemid = data_saleitem.saleitemid
								INNER JOIN DATA_Ticket								on data_ticket.ticketid = data_saleitem2ticket.ticketid
								INNER JOIN (  
										select  RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleid, 
										RR_CNF_RevenueRecognitionRule.Code as RRCode,
										RR_CNF_RevenueRecognitionRule.Days,
										RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
										RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,
										FromDate,
										ToDate,
										RR_CNF_RevenueRecognitionRule.rrCalcTypeTrigger,
										RR_CNF_RevenueRecognitionRule.Percentage as RRPercentage,
										COA_CNF_AccountConfig.CoaAccountid,
										COA_CNF_AccountConfig.AccountingType,
										COA_CNF_AccountConfig.Price,
										COA_CNF_AccountConfig.Percentage,
										COA_CNF_AccountConfig.RemainingValues,
										COA_CNF_AccountConfig.SiteID,
										coa_cnf_account.code as AccountCode,
										COA_CNF_AccountType.Code as AccountTypeCode,
										COA_CNF_AccountType.COAAccountTypeId,
										rr_cnf_Product.MatrixcellID,
										rr_cnf_Product.matrixsheetID,
										COA_CNF_AccountConfig.COAAccountConfigId,
										rr_cnf_Product.AttributeId

								from RR_CNF_RevenueRecognitionRule
									inner join rr_cnf_Product						ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_cnf_product.RevenueRecognitionRuleId and rr_cnf_Product.Enabled = 1		
									INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
									INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
									INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 

								where COA_CNF_AccountConfig.RemainingValues &lt;&gt; 1
								  and RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId in (select RRID 
								                                                                   from #RulesToRun)

									)p   ON ((RR_DATA_REVENUE.MATRIXCELLID = p.MATRIXCELLID) or (RR_DATA_REVENUE.MatrixSheetId = p.MatrixSheetId)
										or (p.Attributeid in (select Value
																								from dbo.split((select Attributeids
																												from RR_DATA_REVENUE rr
																												where rr.RevenueRecognitionDataId = rr_data_revenue.RevenueRecognitionDataId), '.')
																								)
																					    
													))

                                   LEFT JOIN (select ticketid, AttributeIDs coaaccountid, AccountingType, sum(revenueamount) as TotalUsed
												from rr_data_revenue
												where ticketid is not null
												group by ticketid, AccountingType, coaaccountid, AttributeIDs
												)rdata									ON rdata.ticketid = ISNULL(RR_DATA_REVENUE.ticketid, DATA_SaleItem2Ticket.ticketid)	and rdata.AccountingType = p.AccountingType 
												                                           and rdata.coaaccountid = p.coaaccountid
					where data_ticket.FEncodeDate &lt;= @BatchDate
					)p
					where Round(RevenueAmount, 12) &lt;&gt; 0 


					INSERT INTO [dbo].[RR_DATA_Revenue]
						   ([COAAccountId]
						   ,[RevenueRecognitionRuleId]
						   ,[RRCode]
						   ,[RRCalcTypeWhere]
						   ,[RRCalcTypeMethod]
						   ,[COAAccountConfigId]
						   ,[COAAccountType]
						   ,[COAAccountCode]
						   ,[SaleId]
						   ,[Ticketid]
						   ,[MatrixCellid]
						   ,[MatrixCellCode]
						   ,[MatrixSheetid]
						   ,[SiteId]
						   ,[OperatingAreaId]
						   ,[WorkstationId]
						   ,[Usergroupid]
						   ,[UserId]
						   ,[FCalcDate]
						   ,[FRevenueDate]
						   ,[Quantity]
						   ,[GrossAmount]
						   ,[NetAmount]
						   ,[Price]
						   ,[Percentage]
						   ,[RemaningValues]
						   ,[RevenueAmount]
						   ,[AccountingType]
						   ,[RRCalcTypeTrigger]
						   ,[RRPercentage]			
						   ,[RRDays]
						   ,[AttributeIDs]
						   )
						   select *
						   from (
							select distinct p.COAAccountId, 
								   p.RevenueRecognitionRuleId,
								   p.RRcode,		   
								   p.RRCalcTypeWhere,
								   p.RRCalcTypeMethod,	   
								   p.COAAccountConfigId,
								   p.COAAccountTypeId,
								   p.AccountCode as AccountCode,
								   RR_DATA_REVENUE.saleid as Saleid,
								   ISNULL(rdata.Ticketid, DATA_SaleItem2Ticket.Ticketid) TicketID , 
								   RR_DATA_REVENUE.Matrixcellid,
								   RR_DATA_REVENUE.MatrixcellCode,
								   RR_DATA_REVENUE.MatrixSheetId,
								   RR_DATA_REVENUE.Siteid,
								   RR_DATA_REVENUE.OperatingAreaId,
								   RR_DATA_REVENUE.Workstationid,
								   RR_DATA_REVENUE.UserGroupid,
								   RR_DATA_REVENUE.UserId as userID,
								   @BatchDate as BatchDate,
								   @BatchDate as TransDate,
								   RR_DATA_REVENUE.Quantity as Quantity,
								   RR_DATA_REVENUE.GrossAmount as GrossAmount,
								   RR_DATA_REVENUE.NetAmount as NetAmount,
								   p.Price as ConfigPrice,
								   p.Percentage as ConfigPercentage,
								   p.RemainingValues,																		
								  case when ((((DATA_Ticket.Price - DATA_Ticket.taxes) - ISNULL(TotalUsed, 0)) &gt; 0) and ((
																					(((DATA_Ticket.Price - DATA_Ticket.taxes) *  p.rrPercentage)/100) -  
																						((
																						(((DATA_Ticket.Price - DATA_Ticket.taxes) *  p.rrPercentage)/100) * (select sum(percentage)
																																							from coa_cnf_accountconfig AC
																																							where AC.revenuerecognitionruleid = p.RevenueRecognitionRuleId
																																							and ac.accountingtype = p.accountingtype
																																							)
																						)/100)) &lt;= ((DATA_Ticket.Price - DATA_Ticket.taxes) - ISNULL(TotalUsed, 0))))

														then 
														((((DATA_Ticket.Price - DATA_Ticket.taxes) *  p.rrPercentage)/100) -  ((((DATA_Ticket.Price - DATA_Ticket.taxes) *  p.RRPercentage)/100) * (select sum(percentage)
																																from coa_cnf_accountconfig AC
																																where AC.revenuerecognitionruleid = p.RevenueRecognitionRuleId
																																and ac.accountingtype = p.accountingtype
																																))/100)
													else (DATA_Ticket.Price - DATA_Ticket.taxes) - TotalUsed
												end as RevenueAmount,
								   p.Accountingtype,
								   p.RRCalcTypeTrigger,
								   p.RRPercentage,
								   p.Days,
								   RR_DATA_REVENUE.AttributeIDs

							from RR_DATA_REVENUE
								INNER JOIN DATA_SaleItem							ON data_saleitem.SaleItemId		   = rr_data_revenue.saleitemid
								INNER JOIN DATA_SaleItem2Ticket						on data_saleitem2ticket.Saleitemid = data_saleitem.saleitemid
								INNER JOIN DATA_Ticket								on data_ticket.ticketid = data_saleitem2ticket.ticketid
								INNER JOIN (  
										select  RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleid, 
										RR_CNF_RevenueRecognitionRule.Code as RRCode,
										RR_CNF_RevenueRecognitionRule.Days,
										RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
										RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,
										FromDate,
										ToDate,
										RR_CNF_RevenueRecognitionRule.rrCalcTypeTrigger,
										RR_CNF_RevenueRecognitionRule.Percentage as RRPercentage,
										COA_CNF_AccountConfig.CoaAccountid,
										COA_CNF_AccountConfig.AccountingType,
										COA_CNF_AccountConfig.Price,
										COA_CNF_AccountConfig.Percentage,
										COA_CNF_AccountConfig.RemainingValues,
										COA_CNF_AccountConfig.SiteID,
										coa_cnf_account.code as AccountCode,
										COA_CNF_AccountType.Code as AccountTypeCode,
										COA_CNF_AccountType.COAAccountTypeId,
										rr_cnf_Product.MatrixcellID,
										rr_cnf_Product.matrixsheetID,
										COA_CNF_AccountConfig.COAAccountConfigId,
										rr_cnf_Product.AttributeID

								from RR_CNF_RevenueRecognitionRule
									inner join rr_cnf_Product						ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_cnf_product.RevenueRecognitionRuleId and rr_cnf_Product.Enabled = 1		
									INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
									INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
									INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 

								where COA_CNF_AccountConfig.RemainingValues = 1
								  and RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId in (select RRID 
								                                                                   from #RulesToRun)

								)p   ON ((RR_DATA_REVENUE.MATRIXCELLID = p.MATRIXCELLID) or (RR_DATA_REVENUE.MatrixSheetId = p.MatrixSheetId)
										or (p.Attributeid in (select Value
																								from dbo.split((select Attributeids
																												from RR_DATA_REVENUE rr
																												where rr.RevenueRecognitionDataId = rr_data_revenue.RevenueRecognitionDataId), '.')
																								)
																					    
													))
                                   LEFT JOIN (select ticketid, AttributeIDs, coaaccountid, AccountingType, sum(revenueamount) as TotalUsed
												from rr_data_revenue
												where ticketid is not null
												group by ticketid, AccountingType, coaaccountid, AttributeIDs
												)rdata									ON rdata.ticketid = ISNULL(RR_DATA_REVENUE.ticketid, DATA_SaleItem2Ticket.ticketid)	and rdata.AccountingType = p.AccountingType 
												                                           and rdata.coaaccountid = p.coaaccountid
								where data_ticket.FEncodeDate &lt;= @BatchDate
								)r
								where Round(RevenueAmount, 12) &lt;&gt; 0 

    select 'OnTimePeriodTrigger' as TriggerType, @BatchDate as RunDate
END
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_RR_RevenueData_OnTicketUsageTrigger]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_RR_RevenueData_OnTicketUsageTrigger
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE Procedure dbo.otn_sp_RR_RevenueData_OnTicketUsageTrigger
	@BatchDate Date,
	@RRTransDateType Integer
AS 
BEGIN
	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer
	Declare @TicketUsageTrigger Integer = 2	

	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1



	BEGIN

		--Normal TicketExpired No Remaining Value
			INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[SaleId]
				   ,[UsageID]
				   ,[Ticketid]
				   ,[MatrixCellid]
				   ,[MatrixCellCode]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				   ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]			
				   ,[RRDays]
				   ,[AttributeIDs])
				   select *
				   from (
				     select coa_cnf_account.COAAccountId, 
							RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
							RR_CNF_RevenueRecognitionRule.code,		   
							RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
							RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
							COA_CNF_AccountConfig.COAAccountConfigId,
							coa_cnf_account.COAAccountTypeId,
							coa_cnf_account.Code as AccountCode,
							p.saleid as Saleid,
							p.Usageid,
							p.Ticketid as SaleitemID,
							p.Matrixcellid as Matrixcell,
							p.Code as MatrixCode,
							p.MatrixSheetId as MatrixSheetID,
							CASE When RR_CNF_RevenueRecognitionRule.rrCalcTypeWhere = 1 then p.AdmSiteid 
							else p.SaleSite
							end as SiteID,
							p.OperatingAreaId as OperatingAreaID,
							p.Workstationid as Workstationid,
							p.UserId as userID,
							@BatchDate as BatchDate,
							@BatchDate as TransDate,
							1 as Quantity,
							p.GrossAmount as GrossAmount,
							p.NetPrice as NetAmount,
							COA_CNF_AccountConfig.Price as ConfigPrice,
							COA_CNF_AccountConfig.Percentage as ConfigPercentage,
							COA_CNF_AccountConfig.RemainingValues,															   
							Case when COA_CNF_AccountConfig.Price &gt; 0 then (COA_CNF_AccountConfig.Price) 
								 else case when (((p.NetPrice - ISNULL(TotalUsed, 0)) &gt; 0) and (p.NetPrice - ISNULL(TotalUsed, 0)) &gt;= (((p.NetPrice * RR_CNF_RevenueRecognitionRule.Percentage)/100 * COA_CNF_AccountConfig.Percentage)/100)) 
												then (((p.NetPrice * RR_CNF_RevenueRecognitionRule.Percentage)/100 * COA_CNF_AccountConfig.Percentage)/100)
										   else 0
									   end
							end as RevenueAmount,
							COA_CNF_AccountConfig.AccountingType,
							RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
							RR_CNF_RevenueRecognitionRule.Percentage,
							RR_CNF_RevenueRecognitionRule.Days,
							AttributeIDs
						from (			
								select  data_ticketusage.ticketid,
								        data_ticketusage.UsageID,
										1 as Quantity, 
										case when data_ticket.ProductTaxType = 1 then (rawPrice - data_ticket.taxes) 
										     else rawPrice
										end NetPrice,
										DATA_Ticket.Price as GrossAmount,
										CNF_MatrixCell.matrixcellid, 
										CNF_MatrixCell.code,
										CNF_MatrixCell.matrixsheetid, 
										DATA_Ticket.Siteid SaleSite,	  
										cnf_workstation.OperatingAreaId,
										cnf_workstation.workstationid,
										(select top 1 DATA_Sale.userid
											from data_saleitem
											INNER JOIN DATA_Sale		on data_sale.saleid = data_saleitem.saleid
											where data_saleitem.saleitemid = data_ticket.saleitemid
										) as userid,
										(select top 1 data_saleitem.saleid
											from data_saleitem
											where data_saleitem.saleitemid = data_ticket.saleitemid
										) as Saleid,
										(DATA_Ticket.RawPrice) as TicketPrice,
										CNF_Location.Siteid as AdmSiteid,
										CNF_AttributeSet.AttributeIDs,
										CNF_AttributeSet.AttributeSetId
								from data_ticketusage
									INNER JOIN DATA_Ticket											on DATA_Ticket.ticketid = data_ticketusage.ticketid
									INNER JOIN CNF_MatrixCell										on cnf_matrixcell.matrixcellid = data_ticket.matrixcellid
									INNER JOIN CNF_AttributeSet										on cnf_attributeset.AttributeSetId = CNF_MatrixCell.AttributeSetId
									INNER JOIN CNF_Workstation										on cnf_workstation.workstationid = data_ticket.WorkstationId
									INNER JOIN ADM_Gate												on ADM_Gate.gateid = data_ticketusage.gateid
									INNER JOIN CNF_Location											on CNF_Location.locationid = ADM_Gate.locationid
								where  data_ticketusage.validateResult &lt;=99
								and data_ticketusage.UsageType = 1							
								and cast(fusagedate as date) = @batchdate
						)p 
						INNER JOIN rr_cnf_product						ON ((RR_CNF_Product.matrixcellid = p.matrixcellid) or (RR_CNF_Product.matrixsheetid = p.matrixsheetid)
																				or (rr_cnf_product.Attributeid in (select Value
																										from dbo.split((select Attributeids
																														from CNF_AttributeSet
																														where CNF_AttributeSet.AttributeSetId = p.AttributeSetId), '.')
																										)
																					    
															))
						INNER JOIN RR_CNF_RevenueRecognitionRule			ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_cnf_product.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @TicketUsageTrigger
						INNER JOIN COA_CNF_AccountConfig					ON COA_CNF_AccountConfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
						INNER JOIN COA_CNF_Account							ON COA_CNF_Account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
						LEFT JOIN (select ticketid, AccountingType, sum(revenueamount) as TotalUsed
									from rr_data_revenue
									where rr_data_revenue.RRCalcTypeTrigger = @TicketUsageTrigger
									group by ticketid, AccountingType
									)rdata									ON rdata.ticketid = p.ticketid	and rdata.AccountingType = coa_cnf_accountconfig.AccountingType
						where p.TicketPrice &lt;&gt; 0
							and RR_CNF_RevenueRecognitionRule.Enabled = 1
							and coa_cnf_account.Enabled = 1
							and COA_CNF_AccountConfig.Enabled = 1
							and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
							and COA_CNF_AccountConfig.RemainingValues &lt;&gt; 1
							and (((RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere = 1) and ((coa_cnf_accountConfig.Siteid = p.AdmSiteid) or (coa_cnf_accountConfig.Siteid is null)))
							or (RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere = 2) and ((coa_cnf_accountConfig.Siteid = p.SaleSite) or (coa_cnf_accountConfig.Siteid is null))) 
						)k
						where RevenueAmount &lt;&gt; 0




		--Normal TicketExpired with Remaining Value
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[SaleId]
				   ,[UsageID]
				   ,[Ticketid]
				   ,[MatrixCellid]
				   ,[MatrixCellCode]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				   ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays]
				   ,[AttributeIDs])
				   select *
				   from (
						select   	coa_cnf_account.COAAccountId, 
									RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
									RR_CNF_RevenueRecognitionRule.code,		   
									RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
									RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
									COA_CNF_AccountConfig.COAAccountConfigId,
									coa_cnf_account.COAAccountTypeId,
									coa_cnf_account.Code as AccountCode,
									p.saleid as Saleid,
									p.Usageid,
									p.Ticketid as SaleitemID,
									p.Matrixcellid as Matrixcell,
									p.Code as MatrixCode,
									p.MatrixSheetId as MatrixSheetID,
									CASE When RR_CNF_RevenueRecognitionRule.rrCalcTypeWhere = 1 then p.AdmSiteid 
									else p.SaleSite
									end as SiteID,
									p.OperatingAreaId as OperatingAreaID,
									p.Workstationid as Workstationid,
									p.UserId as userID,
									@BatchDate as BatchDate,
									@BatchDate as TransDate,
									1 as Quantity,
									p.GrossAmount as GrossAmount,
									p.NetPrice as NetAmount,
									COA_CNF_AccountConfig.Price as ConfigPrice,
									COA_CNF_AccountConfig.Percentage as ConfigPercentage,
									COA_CNF_AccountConfig.RemainingValues,															   
										case when (((p.NetPrice - ISNULL(TotalUsed, 0)) &gt; 0) and ((
																					((p.NetPrice *  RR_CNF_RevenueRecognitionRule.Percentage)/100) -  
																						((
																						((p.NetPrice *  RR_CNF_RevenueRecognitionRule.Percentage)/100) * (select sum(percentage)
																																							from coa_cnf_accountconfig AC
																																							where AC.revenuerecognitionruleid = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																																							and ac.accountingtype = coa_cnf_accountconfig.accountingtype
																																							)
																						)/100)) &lt;= (p.NetPrice - ISNULL(TotalUsed, 0))))







														then 
														(((p.NetPrice *  RR_CNF_RevenueRecognitionRule.Percentage)/100) -  (((p.NetPrice *  RR_CNF_RevenueRecognitionRule.Percentage)/100) * (select sum(percentage)
																																from coa_cnf_accountconfig AC
																																where AC.revenuerecognitionruleid = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																																and ac.accountingtype = coa_cnf_accountconfig.accountingtype
																																))/100)
													else 0
												end as RevenueAmount,
									COA_CNF_AccountConfig.AccountingType,
									RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
									RR_CNF_RevenueRecognitionRule.Percentage,
									RR_CNF_RevenueRecognitionRule.Days,
									AttributeIDs
								from (			
										select  data_ticketusage.ticketid,
										data_ticketusage.UsageID,
												1 as Quantity, 
												case when data_ticket.ProductTaxType = 1 then (rawPrice - data_ticket.taxes) 
													 else rawPrice
												end NetPrice,
												DATA_Ticket.Price as GrossAmount,
												CNF_MatrixCell.matrixcellid, 
												CNF_MatrixCell.code,
												CNF_MatrixCell.matrixsheetid, 
												DATA_Ticket.Siteid SaleSite,	  
												cnf_workstation.OperatingAreaId,
												cnf_workstation.workstationid,
												(select top 1 DATA_Sale.userid
													from data_saleitem
													INNER JOIN DATA_Sale		on data_sale.saleid = data_saleitem.saleid
													where data_saleitem.saleitemid = data_ticket.saleitemid
												) as userid,
												(select top 1 data_saleitem.saleid
													from data_saleitem
													where data_saleitem.saleitemid = data_ticket.saleitemid
												) as Saleid,
												(DATA_Ticket.RawPrice) as TicketPrice,
												CNF_Location.Siteid as AdmSiteid,
												CNF_AttributeSet.AttributeIDs,
												CNF_AttributeSet.AttributeSetId
										from data_ticketusage
											INNER JOIN DATA_Ticket											on DATA_Ticket.ticketid = data_ticketusage.ticketid
											INNER JOIN CNF_MatrixCell										on cnf_matrixcell.matrixcellid = data_ticket.matrixcellid
											INNER JOIN CNF_AttributeSet										on cnf_attributeset.AttributeSetId = CNF_MatrixCell.AttributeSetId
											INNER JOIN CNF_Workstation										on cnf_workstation.workstationid = data_ticket.WorkstationId
											INNER JOIN ADM_Gate												on ADM_Gate.gateid = data_ticketusage.gateid
											INNER JOIN CNF_Location											on CNF_Location.locationid = ADM_Gate.locationid
										where data_ticketusage.validateResult &lt;=99
										and data_ticketusage.UsageType = 1
										and cast(fusagedate as date) = @batchdate
								)p 
								INNER JOIN rr_cnf_product						ON ((RR_CNF_Product.matrixcellid = p.matrixcellid) or (RR_CNF_Product.matrixsheetid = p.matrixsheetid)
																				or (rr_cnf_product.Attributeid in (select Value
																										from dbo.split((select Attributeids
																														from CNF_AttributeSet
																														where CNF_AttributeSet.AttributeSetId = p.AttributeSetId), '.')
																										)
																					    
															))
								INNER JOIN RR_CNF_RevenueRecognitionRule			ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_cnf_product.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @TicketUsageTrigger
								INNER JOIN COA_CNF_AccountConfig					ON COA_CNF_AccountConfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
								INNER JOIN COA_CNF_Account							ON COA_CNF_Account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
								LEFT JOIN (select ticketid, accountingtype, sum(revenueamount) as TotalUsed
											from rr_data_revenue
											where rr_data_revenue.RRCalcTypeTrigger = @TicketUsageTrigger
											group by ticketid, accountingtype
											)rdata									ON rdata.ticketid = p.ticketid	and rdata.accountingtype = COA_CNF_AccountConfig.accountingtype
								where p.TicketPrice &lt;&gt; 0
									and RR_CNF_RevenueRecognitionRule.Enabled = 1
									and coa_cnf_account.Enabled = 1
									and COA_CNF_AccountConfig.Enabled = 1
									and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
									and COA_CNF_AccountConfig.RemainingValues = 1
									and (((RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere = 1) and ((coa_cnf_accountConfig.Siteid = p.AdmSiteid) or (coa_cnf_accountConfig.Siteid is null)))
									or (RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere = 2) and ((coa_cnf_accountConfig.Siteid = p.SaleSite) or (coa_cnf_accountConfig.Siteid is null))) 
						)k
						where RevenueAmount &lt;&gt; 0

	end

	select 'OnTicketUsageTrigger' as TriggerType, @BatchDate as RunDate

END
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_RR_RevenueData_OnTicketExpiredTrigger]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_RR_RevenueData_OnTicketExpiredTrigger
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE Procedure dbo.otn_sp_RR_RevenueData_OnTicketExpiredTrigger
	@BatchDate Date,
	@RRTransDateType Integer
AS 
BEGIN

	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer
	Declare @TicketExpiredTrigger Integer = 3	

	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1

	BEGIN
		--Normal TicketExpired No Remaining Value
			INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[Ticketid]
				   ,[MatrixCellid]
				   ,[MatrixCellCode]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				   ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays]
				   ,[AttributeIDs])
				   select *
				   from(
				   select COA_CNF_AccountConfig.COAAccountId, 
												   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
												   RR_CNF_RevenueRecognitionRule.code,		   
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
												   COA_CNF_AccountConfig.COAAccountConfigId,
												   coa_cnf_account.COAAccountTypeId,
												   coa_cnf_account.Code as AccountCode,
												   p.Ticketid as Ticketid,
												   p.Matrixcellid as Matrixcell,
												   p.Code as MatrixCode,
												   p.MatrixSheetId as MatrixSheetID,
												   p.Siteid as SiteID,
												   @BatchDate as BatchDate,
												   p.ActiveTo,
												   1 as Quantity,
												   0 as GrossAmount,
												   0 as NetAmount,
												   COA_CNF_AccountConfig.Price as ConfigPrice,
												   COA_CNF_AccountConfig.Percentage as ConfigPercentage,
												   COA_CNF_AccountConfig.RemainingValues,									   
							case when p.netprice &gt; 0 then
								case when (select ISNULL(sum(round(RevenueAmount/rr_data_revenue.Quantity, 2)), 0)
											from rr_data_revenue 
											where rr_data_revenue.accountingtype = 1
											and ((rr_data_revenue.ticketid = p.TicketID)
													or (rr_data_revenue.saleitemid in (select saleitemid
																						from data_saleitem2Ticket
																					where data_saleitem2ticket.ticketid = p.TicketID)
																					))
											and rr_data_revenue.coaaccountid in (select coa_cnf_accountconfig.COAAccountId
																			from coa_cnf_accountconfig
																			where coa_cnf_accountconfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																				and coa_cnf_accountconfig.accountingtype = 1)) &gt; 0 
										and (p.NetPrice - (select ISNULL(sum(round(RevenueAmount/rr_data_revenue.Quantity, 2)), 0)
															from rr_data_revenue 
															where rr_data_revenue.accountingtype = 1
															and ((rr_data_revenue.ticketid = p.TicketID)
																	or (rr_data_revenue.saleitemid in (select saleitemid
																										from data_saleitem2Ticket
																									where data_saleitem2ticket.ticketid = p.TicketID)
																									))
															and rr_data_revenue.coaaccountid in (select coa_cnf_accountconfig.COAAccountId
																							from coa_cnf_accountconfig
																							where coa_cnf_accountconfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																								and coa_cnf_accountconfig.accountingtype = 1)))	&gt; 0
										THEN Case when COA_CNF_AccountConfig.Price &gt; 0 then (COA_CNF_AccountConfig.Price)
												  else (p.NetPrice - (select ISNULL(sum(round(RevenueAmount/rr_data_revenue.Quantity, 2)), 0)
																									from rr_data_revenue 
																									where rr_data_revenue.accountingtype = 1
																									and ((rr_data_revenue.ticketid = p.TicketID)
																											or (rr_data_revenue.saleitemid in (select saleitemid
																																				from data_saleitem2Ticket
																																			where data_saleitem2ticket.ticketid = p.TicketID)
																																			))
																									and rr_data_revenue.coaaccountid in (select coa_cnf_accountconfig.COAAccountId
																																	from coa_cnf_accountconfig
																																	where coa_cnf_accountconfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																																		and coa_cnf_accountconfig.accountingtype = 1))) * COA_CNF_AccountConfig.Percentage/100

												end
										when (select ISNULL(sum(round(RevenueAmount/rr_data_revenue.Quantity, 2)), 0)
																	from rr_data_revenue 
																	where rr_data_revenue.accountingtype = 1
																	and ((rr_data_revenue.ticketid = p.TicketID)
																			or (rr_data_revenue.saleitemid in (select saleitemid
																												from data_saleitem2Ticket
																											where data_saleitem2ticket.ticketid = p.TicketID)
																											))
																	and rr_data_revenue.coaaccountid in (select coa_cnf_accountconfig.COAAccountId
																									from coa_cnf_accountconfig
																									where coa_cnf_accountconfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																										and coa_cnf_accountconfig.accountingtype = 1)) &gt; 0 
											and (p.NetPrice - (select ISNULL(sum(round(RevenueAmount/rr_data_revenue.Quantity, 2)), 0)
															from rr_data_revenue 
															where rr_data_revenue.accountingtype = 1
															and ((rr_data_revenue.ticketid = p.TicketID)
																	or (rr_data_revenue.saleitemid in (select saleitemid
																										from data_saleitem2Ticket
																									where data_saleitem2ticket.ticketid = p.TicketID)
																									))
															and rr_data_revenue.coaaccountid in (select coa_cnf_accountconfig.COAAccountId
																							from coa_cnf_accountconfig
																							where coa_cnf_accountconfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																								and coa_cnf_accountconfig.accountingtype = 1)))	= 0
										   THEN Case when COA_CNF_AccountConfig.Price &gt; 0 then (COA_CNF_AccountConfig.Price)
													 else p.netprice * COA_CNF_AccountConfig.Percentage/100
											END

										when (select ISNULL(sum(round(RevenueAmount/rr_data_revenue.Quantity, 2)), 0)
																	from rr_data_revenue 
																	where rr_data_revenue.accountingtype = 1
																	and ((rr_data_revenue.ticketid = p.TicketID)
																			or (rr_data_revenue.saleitemid in (select saleitemid
																												from data_saleitem2Ticket
																											where data_saleitem2ticket.ticketid = p.TicketID)
																											))
																	and rr_data_revenue.coaaccountid in (select coa_cnf_accountconfig.COAAccountId
																									from coa_cnf_accountconfig
																									where coa_cnf_accountconfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																										and coa_cnf_accountconfig.accountingtype = 1)) = 0 
										 and (select ISNULL(sum(round(RevenueAmount/rr_data_revenue.Quantity, 2)), 0)
																	from rr_data_revenue 
																	where rr_data_revenue.accountingtype = 2
																	and ((rr_data_revenue.ticketid = p.TicketID)
																			or (rr_data_revenue.saleitemid in (select saleitemid
																												from data_saleitem2Ticket
																											where data_saleitem2ticket.ticketid = p.TicketID)
																											))
																	and rr_data_revenue.coaaccountid in (select coa_cnf_accountconfig.COAAccountId
																									from coa_cnf_accountconfig
																									where coa_cnf_accountconfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																										and coa_cnf_accountconfig.accountingtype = 1)) &gt; 0
										   THEN Case when COA_CNF_AccountConfig.Price &gt; 0 then (COA_CNF_AccountConfig.Price)
													 else p.netprice * COA_CNF_AccountConfig.Percentage/100
											END
											else 0							
											end 
											else Case when COA_CNF_AccountConfig.Price &gt; 0 then (COA_CNF_AccountConfig.Price)											
											       else (select ABS(ISNULL(sum(data_ledger.entryamount), 0))
														from data_ticket DT
															INNER JOIN data_ledger					on data_ledger.ticketid = DT.ticketid
														where DT.ticketid = p.TicketID
														group by data_ledger.ticketid) * COA_CNF_AccountConfig.Percentage/100
													END
											end as revenueamount,
									
							COA_CNF_AccountConfig.AccountingType,
							RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
												   RR_CNF_RevenueRecognitionRule.Percentage,
												   RR_CNF_RevenueRecognitionRule.Days,
												   p.AttributeIDs

				  from RR_CNF_RevenueRecognitionRule
					   INNER JOIN RR_CNF_Product						ON RR_CNF_Product.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
					   INNER JOIN COA_CNF_AccountConfig					ON COA_CNF_AccountConfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId 
					   INNER JOIN COA_CNF_Account						on coa_cnf_account.COAAccountId = COA_CNF_AccountConfig.coaaccountid and  COA_CNF_Account.enabled = 1
					   INNER JOIN (select	distinct CNF_MatrixCell.matrixcellid, DATA_Ticket.price, DATA_Ticket.rawprice, DATA_Ticket.ticketid, CNF_MatrixCell.AttributeSetId, AttributeIDs,
					                                 CNF_MatrixCell.Code, MatrixSheetId, DATA_Ticket.siteid, DAta_Ticket.ActiveTo, (data_ticket.price - data_ticket.taxes) NetPrice
														from DATA_Ticket
															INNER JOIN CNF_MatrixCell					on cnf_matrixcell.matrixcellid = data_ticket.matrixcellid
															INNER JOIN CNF_AttributeSet					on cnf_attributeset.AttributeSetId = CNF_MatrixCell.AttributeSetId
										
														where VoidType = 0
															and cast(data_ticket.activeto as date) = @batchdate
									)p  on						((p.matrixcellid   = rr_cnf_product.matrixcellid) or(p.matrixsheetid = rr_cnf_product.matrixsheetid)
																	or (rr_cnf_product.Attributeid in (select Value
																										from dbo.split((select Attributeids
																														from CNF_AttributeSet
																														where CNF_AttributeSet.AttributeSetId = p.AttributeSetId), '.')
																										)
																					    
															))
				where RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @TicketExpiredTrigger
				  and rr_cnf_revenuerecognitionRule.Enabled = 1
				  and COA_CNF_AccountConfig.Enabled = 1
				  and COA_CNF_AccountConfig.RemainingValues &lt;&gt; 1
				)p
				where RevenueAmount &lt;&gt; 0 



		--Normal TicketExpired with Remaining Value
			INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[Ticketid]
				   ,[MatrixCellid]
				   ,[MatrixCellCode]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				   ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays]
				   ,[AttributeIDs])
				   select *
				   from(
				   select COA_CNF_AccountConfig.COAAccountId, 
												   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
												   RR_CNF_RevenueRecognitionRule.code,		   
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
												   COA_CNF_AccountConfig.COAAccountConfigId,
												   coa_cnf_account.COAAccountTypeId,
												   coa_cnf_account.Code as AccountCode,
												   p.Ticketid as Ticketid,
												   p.Matrixcellid as Matrixcell,
												   p.Code as MatrixCode,
												   p.MatrixSheetId as MatrixSheetID,
												   p.Siteid as SiteID,
												   @BatchDate as BatchDate,
												   p.ActiveTo,
												   1 as Quantity,
												   0 as GrossAmount,
												   0 as NetAmount,
												   COA_CNF_AccountConfig.Price as ConfigPrice,
												   COA_CNF_AccountConfig.Percentage as ConfigPercentage,
												   COA_CNF_AccountConfig.RemainingValues,	
												   	case when p.netprice &gt; 0 then								   
												case when (select ISNULL(sum(round(RevenueAmount/rr_data_revenue.Quantity, 2)), 0)
													from rr_data_revenue 
													where rr_data_revenue.accountingtype = 1
													and ((rr_data_revenue.ticketid = p.TicketID)
															or (rr_data_revenue.saleitemid in (select saleitemid
																								from data_saleitem2Ticket
																							where data_saleitem2ticket.ticketid = p.TicketID)
																							))
													and rr_data_revenue.coaaccountid in (select coa_cnf_accountconfig.COAAccountId
																					from coa_cnf_accountconfig
																					where coa_cnf_accountconfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																						and coa_cnf_accountconfig.accountingtype = 1)) &gt; 0 
												and (p.NetPrice - (select ISNULL(sum(round(RevenueAmount/rr_data_revenue.Quantity, 2)), 0)
																	from rr_data_revenue 
																	where rr_data_revenue.accountingtype = 1
																	and ((rr_data_revenue.ticketid = p.TicketID)
																			or (rr_data_revenue.saleitemid in (select saleitemid
																												from data_saleitem2Ticket
																											where data_saleitem2ticket.ticketid = p.TicketID)
																											))
																	and rr_data_revenue.coaaccountid in (select coa_cnf_accountconfig.COAAccountId
																									from coa_cnf_accountconfig
																									where coa_cnf_accountconfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																										and coa_cnf_accountconfig.accountingtype = 1)))	&gt; 0
												THEN  (p.NetPrice - (select ISNULL(sum(round(RevenueAmount/rr_data_revenue.Quantity, 2)), 0)
																											from rr_data_revenue 
																											where rr_data_revenue.accountingtype = 1
																											and ((rr_data_revenue.ticketid = p.TicketID)
																													or (rr_data_revenue.saleitemid in (select saleitemid
																																						from data_saleitem2Ticket
																																					where data_saleitem2ticket.ticketid = p.TicketID)
																																					))
																											and rr_data_revenue.coaaccountid in (select coa_cnf_accountconfig.COAAccountId
																																			from coa_cnf_accountconfig
																																			where coa_cnf_accountconfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																																				and coa_cnf_accountconfig.accountingtype = 1)))
																																																								 
												when (select ISNULL(sum(round(RevenueAmount/rr_data_revenue.Quantity, 2)), 0)
																			from rr_data_revenue 
																			where rr_data_revenue.accountingtype = 1
																			and ((rr_data_revenue.ticketid = p.TicketID)
																					or (rr_data_revenue.saleitemid in (select saleitemid
																														from data_saleitem2Ticket
																													where data_saleitem2ticket.ticketid = p.TicketID)
																													))
																			and rr_data_revenue.coaaccountid in (select coa_cnf_accountconfig.COAAccountId
																											from coa_cnf_accountconfig
																											where coa_cnf_accountconfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																												and coa_cnf_accountconfig.accountingtype = 1)) &gt; 0 
													and (p.NetPrice - (select ISNULL(sum(round(RevenueAmount/rr_data_revenue.Quantity, 2)), 0)
																	from rr_data_revenue 
																	where rr_data_revenue.accountingtype = 1
																	and ((rr_data_revenue.ticketid = p.TicketID)
																			or (rr_data_revenue.saleitemid in (select saleitemid
																												from data_saleitem2Ticket
																											where data_saleitem2ticket.ticketid = p.TicketID)
																											))
																	and rr_data_revenue.coaaccountid in (select coa_cnf_accountconfig.COAAccountId
																									from coa_cnf_accountconfig
																									where coa_cnf_accountconfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																										and coa_cnf_accountconfig.accountingtype = 1)))	= 0
												   THEN Case when COA_CNF_AccountConfig.Price &gt; 0 then (COA_CNF_AccountConfig.Price)
															 else p.netprice - 	(ISNULL((select sum(RevenueAmount)
																					from rr_data_revenue 
																					where RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																					and ((rr_data_revenue.ticketid = p.Ticketid)
																									or (rr_data_revenue.saleitemid in (select saleitemid
																																		from data_saleitem2Ticket
																																	where data_saleitem2ticket.ticketid = p.Ticketid)
																																	))
																					and rr_data_revenue.accountingtype = COA_CNF_AccountConfig.accountingtype
																					and rr_data_revenue.coaaccountid in (select CC.COAAccountId
																															from coa_cnf_accountconfig CC
																															where CC.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																																and CC.accountingtype = coa_cnf_accountconfig.Accountingtype)
																				), 0))
													END

												when (select ISNULL(sum(round(RevenueAmount/rr_data_revenue.Quantity, 2)), 0)
																			from rr_data_revenue 
																			where rr_data_revenue.accountingtype = 1
																			and ((rr_data_revenue.ticketid = p.TicketID)
																					or (rr_data_revenue.saleitemid in (select saleitemid
																														from data_saleitem2Ticket
																													where data_saleitem2ticket.ticketid = p.TicketID)
																													))
																			and rr_data_revenue.coaaccountid in (select coa_cnf_accountconfig.COAAccountId
																											from coa_cnf_accountconfig
																											where coa_cnf_accountconfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																												and coa_cnf_accountconfig.accountingtype = 1)) = 0 
												 and (select ISNULL(sum(round(RevenueAmount/rr_data_revenue.Quantity, 2)), 0)
																			from rr_data_revenue 
																			where rr_data_revenue.accountingtype = 2
																			and ((rr_data_revenue.ticketid = p.TicketID)
																					or (rr_data_revenue.saleitemid in (select saleitemid
																														from data_saleitem2Ticket
																													where data_saleitem2ticket.ticketid = p.TicketID)
																													))
																			and rr_data_revenue.coaaccountid in (select coa_cnf_accountconfig.COAAccountId
																											from coa_cnf_accountconfig
																											where coa_cnf_accountconfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																												and coa_cnf_accountconfig.accountingtype = 1)) &gt; 0
												   THEN p.netprice - 	(ISNULL((select sum(RevenueAmount)
																					from rr_data_revenue 
																					where RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																					and ((rr_data_revenue.ticketid = p.Ticketid)
																									or (rr_data_revenue.saleitemid in (select saleitemid
																																		from data_saleitem2Ticket
																																	where data_saleitem2ticket.ticketid = p.Ticketid)
																																	))
																					and rr_data_revenue.accountingtype = COA_CNF_AccountConfig.accountingtype
																					and rr_data_revenue.coaaccountid in (select CC.COAAccountId
																															from coa_cnf_accountconfig CC
																															where CC.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																																and CC.accountingtype = coa_cnf_accountconfig.Accountingtype)
																				), 0))
											else 0							
											end 
											else  (select ABS(ISNULL(sum(data_ledger.entryamount), 0))
														from data_ticket DT
															INNER JOIN data_ledger					on data_ledger.ticketid = DT.ticketid
														where DT.ticketid = p.TicketID
														group by data_ledger.ticketid) - 
														(ISNULL((select sum(RevenueAmount)
																					from rr_data_revenue 
																					where RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																					and ((rr_data_revenue.ticketid = p.Ticketid)
																									or (rr_data_revenue.saleitemid in (select saleitemid
																																		from data_saleitem2Ticket
																																	where data_saleitem2ticket.ticketid = p.Ticketid)
																																	))
																					and rr_data_revenue.accountingtype = COA_CNF_AccountConfig.accountingtype
																					and rr_data_revenue.coaaccountid in (select CC.COAAccountId
																															from coa_cnf_accountconfig CC
																															where CC.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																																and CC.accountingtype = coa_cnf_accountconfig.Accountingtype)
																				), 0))
													
											end as revenueamount,
												   COA_CNF_AccountConfig.AccountingType,
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
												   RR_CNF_RevenueRecognitionRule.Percentage,
												   RR_CNF_RevenueRecognitionRule.Days,
												   p.AttributeIDs

				  from RR_CNF_RevenueRecognitionRule
					   INNER JOIN RR_CNF_Product						ON RR_CNF_Product.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
					   INNER JOIN COA_CNF_AccountConfig					ON COA_CNF_AccountConfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId 
					   INNER JOIN COA_CNF_Account						on coa_cnf_account.COAAccountId = COA_CNF_AccountConfig.coaaccountid and  COA_CNF_Account.enabled = 1
					   INNER JOIN (select	distinct CNF_MatrixCell.matrixcellid, DATA_Ticket.price, DATA_Ticket.rawprice, DATA_Ticket.ticketid, CNF_MatrixCell.AttributeSetId, AttributeIDs,
					                                 CNF_MatrixCell.Code, MatrixSheetId, DATA_Ticket.siteid, DAta_Ticket.ActiveTo, (data_ticket.price - data_ticket.taxes) NetPrice
														from DATA_Ticket
															INNER JOIN CNF_MatrixCell					on cnf_matrixcell.matrixcellid = data_ticket.matrixcellid
															INNER JOIN CNF_AttributeSet					on cnf_attributeset.AttributeSetId = CNF_MatrixCell.AttributeSetId
										
														where VoidType = 0
															and data_ticket.activeto = @batchdate
									)p  on						((p.matrixcellid   = rr_cnf_product.matrixcellid) or(p.matrixsheetid = rr_cnf_product.matrixsheetid)
																	or (rr_cnf_product.Attributeid in (select Value
																										from dbo.split((select Attributeids
																														from CNF_AttributeSet
																														where CNF_AttributeSet.AttributeSetId = p.AttributeSetId), '.')
																										)
																					    
															))

				where RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @TicketExpiredTrigger
				  and rr_cnf_revenuerecognitionRule.Enabled = 1
				  and COA_CNF_AccountConfig.Enabled = 1
				  and COA_CNF_AccountConfig.RemainingValues = 1
				)p
				where RevenueAmount &lt;&gt; 0 


	end

    select 'OnTicketExpiredTrigger' as TriggerType, @BatchDate as RunDate
END
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_RR_RevenueData_OnSaleTrigger]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_RR_RevenueData_OnSaleTrigger
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE Procedure dbo.otn_sp_RR_RevenueData_OnSaleTrigger
	@BatchDate Date,
	@RRTransDateType Integer
AS 
BEGIN

	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer
	Declare @OnSaleTrigger Integer = 1

	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1

	BEGIN
																		  
	--Normal Transaction No Remaining Values
			INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[Saleitemid]
				   ,[MatrixCellid]
				   ,[MatrixCellCode]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays]
				   ,[AttributeIDs])
				   select *
				   from(
							select distinct coa_cnf_account.COAAccountId, 
								   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
								   RR_CNF_RevenueRecognitionRule.code,		   
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
								   COA_CNF_AccountConfig.COAAccountConfigId,
								   coa_cnf_account.COAAccountTypeId,
								   coa_cnf_account.Code as AccountCode,
								   RR_DATA_REVENUE.Transactionid as Transactionid,
								   RR_DATA_REVENUE.saleid as Saleid,
								   RR_DATA_REVENUE.SaleitemID as SaleitemID,
								   RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								   RR_DATA_REVENUE.MatrixcellCode as MatrixCode,
								   RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								   RR_DATA_REVENUE.Siteid as SiteID,
								   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								   RR_DATA_REVENUE.Workstationid as Workstationid,
								   RR_DATA_REVENUE.UserGroupid as UserGroupID,
								   RR_DATA_REVENUE.UserId as userID,
								   @BatchDate as BatchDate,
								   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
								        else DATA_Transaction.transactiondate
								   end as TransDate,
								   RR_DATA_REVENUE.Quantity as Quantity,
								   RR_DATA_REVENUE.GrossAmount as GrossAmount,
								   RR_DATA_REVENUE.NetAmount as NetAmount,
								   COA_CNF_AccountConfig.Price as ConfigPrice,
								   COA_CNF_AccountConfig.Percentage as ConfigPercentage,
								   COA_CNF_AccountConfig.RemainingValues,								
									Case when COA_CNF_AccountConfig.Price &gt; 0 then (COA_CNF_AccountConfig.Price * RR_DATA_REVENUE.Quantity) 
											else ISNULL(ABS((RR_DATA_REVENUE.RevenueAmount * COA_CNF_AccountConfig.percentage)/100), 0)
									end 																		                                                                                                                                                                                              
									as RevenueAmount,

								   case when TransactionType in (5, 17, 18, 20, 22, 30) and COA_CNF_AccountConfig.Accountingtype = 1 then 2
								        when TransactionType in (5, 17, 18, 20, 22, 30) and COA_CNF_AccountConfig.Accountingtype = 2 then 1
									--	when TransactionType in (7) and rr_data_revenue.RevenueAmount &gt; 0 and COA_CNF_AccountConfig.Accountingtype = 1 then 2
										when TransactionType in (7) and rr_data_revenue.RevenueAmount &lt; 0 and COA_CNF_AccountConfig.Accountingtype = 2 then 1
								        else COA_CNF_AccountConfig.Accountingtype
									end Accountingtype,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
								   RR_CNF_RevenueRecognitionRule.Percentage,
								   RR_CNF_RevenueRecognitionRule.Days,
								   RR_DATA_Revenue.AttributeIDs
		   
							from RR_DATA_REVENUE
									inner join rr_cnf_Product						ON ((RR_DATA_REVENUE.MATRIXCELLID = rr_cnf_Product.MATRIXCELLID) 
                                                      or (RR_DATA_REVENUE.MatrixSheetId = rr_cnf_Product.MatrixSheetId)
													  or (rr_cnf_product.Attributeid in (select top 1 Attributeid
																							from rr_cnf_product
																							where Attributeid in (select Value
																													from dbo.split((select rr.Attributeids
																																	from rr_data_revenue rr
																																	where rr.revenuerecognitiondataid = RR_DATA_REVENUE.revenuerecognitiondataid), '.')
																												   )
																					    )
															))
													  and rr_cnf_Product.Enabled = 1
									inner join RR_CNF_RevenueRecognitionRule		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_cnf_Product.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  
									INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
									INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
									INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 
									INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid

							where RR_CNF_RevenueRecognitionRule.Enabled = 1
							  and coa_cnf_account.Enabled = 1
							  and COA_CNF_AccountConfig.Enabled = 1
							  and TransactionType in (5, 7, 9, 14, 18, 20, 22, 16, 30, 101, 102, 103, 104, 105)
							  and ((coa_cnf_accountConfig.Siteid = RR_Data_Revenue.SiteId) or (coa_cnf_accountConfig.Siteid is null))
							  and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger IN (@OnSaleTrigger)
							  and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
							  and COA_CNF_AccountConfig.RemainingValues &lt;&gt; 1
							  and RR_DATA_REVENUE.fcalcdate = @BatchDate
							  and RR_DATA_REVENUE.coaaccountid = @suspendid
					)p
					where RevenueAmount &lt;&gt; 0

				----Normal Transaction with Remaining Values
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[Saleitemid]
				   ,[MatrixCellid]
				   ,[MatrixCellCode]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays]
				   ,[AttributeIDs])
				   select *
				   from(
						select distinct coa_cnf_account.COAAccountId, 
								   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
								   RR_CNF_RevenueRecognitionRule.code,		   
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
								   COA_CNF_AccountConfig.COAAccountConfigId,
								   coa_cnf_account.COAAccountTypeId,
								   coa_cnf_account.Code as AccountCode,
								   RR_DATA_REVENUE.Transactionid as Transactionid,
								   RR_DATA_REVENUE.saleid as Saleid,
								   RR_DATA_REVENUE.SaleitemID as SaleitemID,
								   RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								   RR_DATA_REVENUE.MatrixcellCode as MatrixCode,
								   RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								   RR_DATA_REVENUE.Siteid as SiteID,
								   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								   RR_DATA_REVENUE.Workstationid as Workstationid,
								   RR_DATA_REVENUE.UserGroupid as UserGroupID,
								   RR_DATA_REVENUE.UserId as userID,
								   @BatchDate as BatchDate,
								   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
								        else DATA_Transaction.transactiondate
								   end as TransDate,
								   RR_DATA_REVENUE.Quantity as Quantity,
								   RR_DATA_REVENUE.GrossAmount as GrossAmount,
								   RR_DATA_REVENUE.NetAmount as NetAmount,
								   COA_CNF_AccountConfig.Price as ConfigPrice,
								   COA_CNF_AccountConfig.Percentage as ConfigPercentage,
								   COA_CNF_AccountConfig.RemainingValues,							 	
									ISNULL(
									abs(ISNULL((select sum(revenueamount)
												 from rr_data_revenue rdr1
												 where rdr1.saleitemid = RR_DATA_REVENUE.Saleitemid 
												 and rdr1.coaaccountid = @SuspendID
												), 0))
									-															  								  								  					
									ISNULL((select ABS(sum(RevenueAmount))
												from RR_Data_Revenue rdr
												where rdr.saleitemid = RR_DATA_REVENUE.Saleitemid
													and rdr.COAAccountid NOT in (@SuspendID, @ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)
											), 0)
									, RR_DATA_REVENUE.revenueamount)
									as RevenueAmount,
								   case when TransactionType in (5, 17, 18, 20, 22, 30) and COA_CNF_AccountConfig.Accountingtype = 1 then 2
								        when TransactionType in (5, 17, 18, 20, 22, 30) and COA_CNF_AccountConfig.Accountingtype = 2 then 1
										when TransactionType in (7) and rr_data_revenue.RevenueAmount &lt; 0 and COA_CNF_AccountConfig.Accountingtype = 2 then 1
								        else COA_CNF_AccountConfig.Accountingtype
									end Accountingtype,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
								   RR_CNF_RevenueRecognitionRule.Percentage,
								   RR_CNF_RevenueRecognitionRule.Days,
								   RR_DATA_Revenue.AttributeIDs

						from RR_DATA_REVENUE
								inner join rr_cnf_Product						ON ((RR_DATA_REVENUE.MATRIXCELLID = rr_cnf_Product.MATRIXCELLID) 
                                                      or (RR_DATA_REVENUE.MatrixSheetId = rr_cnf_Product.MatrixSheetId)
													  or (rr_cnf_product.Attributeid in (select top 1 Attributeid
																							from rr_cnf_product
																							where Attributeid in (select Value
																													from dbo.split((select rr.Attributeids
																																	from rr_data_revenue rr
																																	where rr.revenuerecognitiondataid = RR_DATA_REVENUE.revenuerecognitiondataid), '.')
																												   )
																					    )
															))
													  and rr_cnf_Product.Enabled = 1
								inner join RR_CNF_RevenueRecognitionRule		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_cnf_Product.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  
								INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
								INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
								INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 
								INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid

							where RR_CNF_RevenueRecognitionRule.Enabled = 1
							  and coa_cnf_account.Enabled = 1
							  and COA_CNF_AccountConfig.Enabled = 1
							  and TransactionType in (5, 7, 9, 14, 18, 20, 22, 16, 30, 101, 102, 103, 104, 105)
							  and ((coa_cnf_accountConfig.Siteid = RR_Data_Revenue.SiteId) or (coa_cnf_accountConfig.Siteid is null))
							  and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger IN (@OnSaleTrigger)
							  and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
							  and COA_CNF_AccountConfig.RemainingValues = 1
							  and RR_DATA_REVENUE.fcalcdate = @BatchDate
							  and RR_DATA_REVENUE.coaaccountid = @suspendid
					)p
					where RevenueAmount &lt;&gt; 0


--Reverse of a Deposit 
			INSERT INTO [dbo].[RR_DATA_Revenue]
					   ([COAAccountId]
					   ,[RevenueRecognitionRuleId]
					   ,[RRCode]
					   ,[RRCalcTypeWhere]
					   ,[RRCalcTypeMethod]
					   ,[COAAccountConfigId]
					   ,[COAAccountType]
					   ,[COAAccountCode]
					   ,[TransactionId]
					   ,[SaleId]
					   ,[SiteId]
					   ,[OperatingAreaId]
					   ,[WorkstationId]
					   ,[UserGroupId]
					   ,[UserId]
					   ,[FCalcDate]
					   ,[FRevenueDate]
					   ,[Quantity]
					   ,[GrossAmount]
					   ,[NetAmount]
					   ,[Price]
					   ,[Percentage]
					   ,[RemaningValues]
					   ,[RevenueAmount]
					   ,[AccountingType]
					   ,[RRCalcTypeTrigger]
					   ,[RRPercentage]
					   ,[RRDays]
					   ,[AttributeIDs])
			select distinct RR_DATA_REVENUE.COAAccountId, 
								RR_DATA_REVENUE.RevenueRecognitionRuleId,
								RR_DATA_REVENUE.rrcode,		   
								RR_DATA_REVENUE.RRCalcTypeWhere,
								RR_DATA_REVENUE.RRCalcTypeMethod,	   
								RR_DATA_REVENUE.COAAccountConfigId,
								RR_DATA_REVENUE.COAAccountType,
								RR_DATA_REVENUE.COAAccountCode,
								p.Transactionid as Transactionid,					
								ISNULL(p.saleid, RR_DATA_REVENUE.saleid) as Saleid,
								p.Siteid as SiteID,
								p.OperatingAreaId as OperatingAreaID,
								p.Workstationid as Workstationid,
								p.UserGroupid as UserGroupID,
								p.UserId as userID,
								@BatchDate as BatchDate,
								case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
								     else DATA_Transaction.transactiondate
								end as TransDate,
								RR_DATA_REVENUE.Quantity as Quantity,
								RR_DATA_REVENUE.GrossAmount as GrossAmount,
								RR_DATA_REVENUE.NetAmount as NetAmount,
								RR_DATA_REVENUE.Price as ConfigPrice,
								RR_DATA_REVENUE.Percentage as ConfigPercentage,
								RR_DATA_REVENUE.RemaningValues, 
								RR_DATA_REVENUE.revenueamount  as RevenueAmount,
								case when RR_DATA_REVENUE.accountingtype = 1 then 2
								     else 1
								end as Accountingtype,
								RR_DATA_REVENUE.RRCalcTypeTrigger,
								RR_DATA_REVENUE.rrPercentage,
								RR_DATA_REVENUE.rrDays,
								RR_DATA_REVENUE.attributeids
										
							from RR_DATA_REVENUE
									INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
									INNER JOIN (select distinct RR_DATA_REVENUE.Accountingtype, rr_data_revenue.siteid, rr_data_revenue.transactionid, rr_data_revenue.saleid, rr_data_revenue.Operatingareaid, rr_data_revenue.workstationid, rr_data_revenue.usergroupid, rr_data_revenue.userid
												  from rr_data_revenue
														INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
												  where  DATA_Transaction.transactiontype = 16 and data_transaction.paid = 1
												  and RR_DATA_REVENUE.FCalcDate = @BatchDate
												  and rr_data_revenue.coaaccountid = @suspendid
												  and rr_data_revenue.usergroupid is not null
											   )p    on p.saleid = rr_data_revenue.saleid

							where transactiontype in (12)	
							and rr_data_revenue.coaaccountid not in (select coaaccountid
																	   from cnf_paymentMethod
																	  where coaaccountid is not null
																	  Union all
																	  select coaaccountid
																	   from cnf_paymentcard
																	  where coaaccountid is not null
																	  Union all 
																	  select coaaccountid
																	   from cnf_tax
																	  where coaaccountid is not null
																	  Union all 
																	  select coaaccountid
																	   from cnf_promotion
																	  where coaaccountid is not null
																	 )											  										
									and RR_DATA_REVENUE.fcalcdate = @BatchDate
									and RR_DATA_REVENUE.coaaccountid not in  (@suspendid, @ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)



				
		exec otn_sp_RR_RevenueData_PaymentMethodTaxDiscounts @BatchDate, '5, 7, 9, 14, 18, 20, 22, 16, 30, 101, 102, 103, 104, 105,',   @OnSaleTrigger, @RRTransDateType
																																																																																													
		End

	select 'OnSalePaidTrigger' as TriggerType, @BatchDate as RunDate
END
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_RR_RevenueData_OnMoneyRefundTrigger]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_RR_RevenueData_OnMoneyRefundTrigger
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE Procedure dbo.otn_sp_RR_RevenueData_OnMoneyRefundTrigger
	@BatchDate Date,
	@RRTransDateType Integer
AS 
BEGIN

	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer
	Declare @MoneyRefund Integer = 6

	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1

	
		BEGIN

			--Normal Transaction No Remaining Values
			INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[Saleitemid]
				   ,[MatrixCellid]
				   ,[MatrixCellCode]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				   ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])
				   select *
				   from (
					select distinct p.COAAccountId, 
								p.RevenueRecognitionRuleId,
								p.code,		   
								p.RRCalcTypeWhere,
								p.RRCalcTypeMethod,	   
								p.COAAccountConfigId,
								p.COAAccountTypeId,
								p.AccountCode,
								RR_DATA_REVENUE.Transactionid as Transactionid,
								RR_DATA_REVENUE.saleid as Saleid,
								RR_DATA_REVENUE.SaleitemID as SaleitemID,
								RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								RR_DATA_REVENUE.MatrixcellCode as MatrixCode,
								RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								RR_DATA_REVENUE.Siteid as SiteID,
								RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								RR_DATA_REVENUE.Workstationid as Workstationid,
								RR_DATA_REVENUE.UserGroupid as UserGroupID,
								RR_DATA_REVENUE.UserId as userID,
								@BatchDate as BatchDate,
								case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
								     else DATA_Transaction.transactiondate
								end as TransDate,
								RR_DATA_REVENUE.Quantity as Quantity,
								RR_DATA_REVENUE.GrossAmount as GrossAmount,
								RR_DATA_REVENUE.NetAmount as NetAmount,
								p.Price as ConfigPrice,
								p.Percentage as ConfigPercentage,
								p.RemainingValues,
								(CASE WHEN p.coaaccountid not in (@ACCPaymentMethod, @TaxAccountID, @DiscountAccountID) then   --Accounts not Tax not PaymentMethods 
									Case when p.Price &gt; 0 then (p.Price * RR_DATA_REVENUE.Quantity) 
											else (ISNULL((((ABS(RR_DATA_REVENUE.RevenueAmount)) - ISNULL((select (ABS((sum(TaxAmount) * RR_DATA_REVENUE.Quantity)))
																									from data_saleitemTax
																									where saleitemid = RR_DATA_REVENUE.SaleitemID), 0)) * p.Percentage/100), 0))
									end 																		                                                                                                                                                                                              
								end)  as RevenueAmount,
								case when TransactionType in (5, 13, 17, 18, 20, 22, 30) and p.Accountingtype = 1 then 2
										when TransactionType in (5, 13, 17, 18, 20, 22, 30) and p.Accountingtype = 2 then 1
										when TransactionType in (7) and rr_data_revenue.RevenueAmount &lt; 0 and p.Accountingtype = 1 then 2
										when TransactionType in (7) and rr_data_revenue.RevenueAmount &lt; 0 and p.Accountingtype = 2 then 1
										else p.Accountingtype
									end Accountingtype,
									p.RRCalcTypeTrigger,
									p.rrPercentage,
									p.Days						
						
						
							from RR_DATA_REVENUE
								INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
								INNER JOIN (select '1' as PCOAAccountid, 
												   coa_cnf_accountConfig.Siteid, 
												   RR_CNF_RevenueRecognitionRule.Enabled, 
												   RR_CNF_RevenueRecognitionRule.FromDate, 
												   RR_CNF_RevenueRecognitionRule.ToDate,
												   COA_CNF_AccountConfig.RemainingValues,
												   coa_cnf_account.coaaccountid,
												   COA_CNF_AccountConfig.Price,
												   COA_CNF_AccountConfig.Percentage,
												   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
												   RR_CNF_RevenueRecognitionRule.code,		   
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
												   COA_CNF_AccountConfig.COAAccountConfigId,
												   coa_cnf_account.COAAccountTypeId,
												   coa_cnf_account.Code as accountcode,
												   coa_cnf_accountconfig.Accountingtype,
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
												   RR_CNF_RevenueRecognitionRule.Percentage rrPercentage,
												   RR_CNF_RevenueRecognitionRule.Days	

												from RR_CNF_RevenueRecognitionRule	
												INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
												INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid and coa_cnf_account.Enabled = 1
												INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
											where  RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @MoneyRefund
											and RR_CNF_RevenueRecognitionRule.Enabled = 1
											and coa_cnf_account.coaaccountid not in (@ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)) p				on p.PCOAAccountid = rr_data_revenue.coaaccountid 

							where transactiontype in (13)													 
								and p.Enabled = 1
								and ((p.Siteid = RR_DATA_REVENUE.Siteid) or (p.Siteid is null))
								and @BatchDate between p.FromDate and p.ToDate
								and p.RemainingValues &lt;&gt; 1
								and RR_DATA_REVENUE.fcalcdate = @BatchDate
					)r 
					where r.revenueAmount &lt;&gt; 0


				--Normal Transaction with Remaining Values
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[Saleitemid]
				   ,[MatrixCellid]
				   ,[MatrixCellCode]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])
				   select *
				   from (
					select distinct p.COAAccountId, 
								p.RevenueRecognitionRuleId,
								p.code,		   
								p.RRCalcTypeWhere,
								p.RRCalcTypeMethod,	   
								p.COAAccountConfigId,
								p.COAAccountTypeId,
								p.AccountCode,
								RR_DATA_REVENUE.Transactionid as Transactionid,
								RR_DATA_REVENUE.saleid as Saleid,
								RR_DATA_REVENUE.SaleitemID as SaleitemID,
								RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								RR_DATA_REVENUE.MatrixcellCode as MatrixCode,
								RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								RR_DATA_REVENUE.Siteid as SiteID,
								RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								RR_DATA_REVENUE.Workstationid as Workstationid,
								RR_DATA_REVENUE.UserGroupid as UserGroupID,
								RR_DATA_REVENUE.UserId as userID,
								@BatchDate as BatchDate,
								case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
								     else DATA_Transaction.transactiondate
								  end as TransDate,
								RR_DATA_REVENUE.Quantity as Quantity,
								RR_DATA_REVENUE.GrossAmount as GrossAmount,
								RR_DATA_REVENUE.NetAmount as NetAmount,
								p.Price as ConfigPrice,
								p.Percentage as ConfigPercentage,
								p.RemainingValues,
								CASE WHEN p.coaaccountid not in (@ACCPaymentMethod, @TaxAccountID, @DiscountAccountID) then																																													 
							    ABS(ABS(RR_DATA_REVENUE.RevenueAmount) -					 
								ISNULL((select ABS(sum(RevenueAmount))
										from RR_DATA_Revenue rrd
									    where rrd.RevenueRecognitionRuleId = p.RevenueRecognitionRuleId
										and rrd.RevenueRecognitionRuleId not in (@SuspendID, @ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)
										and rrd.transactionid = RR_DATA_REVENUE.transactionid
								), 0)) 
								else 0
								end RevenueAmount,
								case when TransactionType in (5, 13, 17, 18, 20, 22, 30) and p.Accountingtype = 1 then 2
										when TransactionType in (5, 13, 17, 18, 20, 22, 30) and p.Accountingtype = 2 then 1
										when TransactionType in (7) and rr_data_revenue.RevenueAmount &lt; 0 and p.Accountingtype = 1 then 2
										when TransactionType in (7) and rr_data_revenue.RevenueAmount &lt; 0 and p.Accountingtype = 2 then 1
										else p.Accountingtype
									end Accountingtype,
									p.RRCalcTypeTrigger,
									p.rrPercentage,
									p.Days						
						
						
							from RR_DATA_REVENUE
								INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
								INNER JOIN (select '1' as PCOAAccountid, 
												   coa_cnf_accountConfig.Siteid, 
												   RR_CNF_RevenueRecognitionRule.Enabled, 
												   RR_CNF_RevenueRecognitionRule.FromDate, 
												   RR_CNF_RevenueRecognitionRule.ToDate,
												   COA_CNF_AccountConfig.RemainingValues,
												   coa_cnf_account.coaaccountid,
												   COA_CNF_AccountConfig.Price,
												   COA_CNF_AccountConfig.Percentage,
												   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
												   RR_CNF_RevenueRecognitionRule.code,		   
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
												   COA_CNF_AccountConfig.COAAccountConfigId,
												   coa_cnf_account.COAAccountTypeId,
												   coa_cnf_account.Code as accountcode,
												   coa_cnf_accountconfig.Accountingtype,
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
												   RR_CNF_RevenueRecognitionRule.Percentage rrPercentage,
												   RR_CNF_RevenueRecognitionRule.Days	

												from RR_CNF_RevenueRecognitionRule	
												INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
												INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid and coa_cnf_account.Enabled = 1
												INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
											where  RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @MoneyRefund
											and RR_CNF_RevenueRecognitionRule.Enabled = 1
											and coa_cnf_account.coaaccountid not in (@ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)) p				on p.PCOAAccountid = rr_data_revenue.coaaccountid 

							where transactiontype in (13)													 
								and p.Enabled = 1
								and ((p.Siteid = RR_DATA_REVENUE.Siteid) or (p.Siteid is null))
								and @BatchDate between p.FromDate and p.ToDate
								and p.RemainingValues = 1
								and RR_DATA_REVENUE.fcalcdate = @BatchDate		
					)r 
					where r.revenueAmount &lt;&gt; 0

				exec otn_sp_RR_RevenueData_PaymentMethodTaxDiscounts2 @BatchDate, '13,',   @MoneyRefund, @RRTransDateType
	end

	select 'OnMoneyRefundTrigger' as TriggerType, @BatchDate as RunDate

END
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_RR_RevenueData_OnMoneyCardLoad]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_RR_RevenueData_OnMoneyCardLoad
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE Procedure dbo.otn_sp_RR_RevenueData_OnMoneyCardLoad
	@BatchDate Date,
	@RRTransDateType Integer
AS 
BEGIN
	
	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer
	Declare @OnMoneyCardCashOut Integer = 10

	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1


		BEGIN

			--Normal Transaction No Remaining Values
			INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[Saleitemid]
				   ,[MatrixCellid]
				   ,[MatrixCellCode]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays]
				   ,[AttributeIDs])
				   select *
				   from(
						select distinct coa_cnf_account.COAAccountId, 
								   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
								   RR_CNF_RevenueRecognitionRule.code,		   
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
								   COA_CNF_AccountConfig.COAAccountConfigId,
								   coa_cnf_account.COAAccountTypeId,
								   coa_cnf_account.Code as AccountCode,
								   RR_DATA_REVENUE.Transactionid as Transactionid,
								   RR_DATA_REVENUE.saleid as Saleid,
								   RR_DATA_REVENUE.SaleitemID as SaleitemID,
								   RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								   RR_DATA_REVENUE.MatrixcellCode as MatrixCode,
								   RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								   RR_DATA_REVENUE.Siteid as SiteID,
								   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								   RR_DATA_REVENUE.Workstationid as Workstationid,
								   RR_DATA_REVENUE.UserGroupid as UserGroupID,
								   RR_DATA_REVENUE.UserId as userID,
								   @BatchDate as BatchDate,
								   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
								        else DATA_Transaction.transactiondate
								   end as TransDate,
								   RR_DATA_REVENUE.Quantity as Quantity,
								   RR_DATA_REVENUE.GrossAmount as GrossAmount,
								   RR_DATA_REVENUE.NetAmount as NetAmount,
								   COA_CNF_AccountConfig.Price as ConfigPrice,
								   COA_CNF_AccountConfig.Percentage as ConfigPercentage,
								   COA_CNF_AccountConfig.RemainingValues,																		
									Case when COA_CNF_AccountConfig.Price &gt; 0 then (COA_CNF_AccountConfig.Price * RR_DATA_REVENUE.Quantity) 
										 else (ISNULL(((ABS((select unitrecharge
															   from data_saleitem
															  where saleitemid = RR_DATA_REVENUE.saleitemid
										))) * COA_CNF_AccountConfig.Percentage/100), 0))																		                                                                                                                                                                                              
									end  as RevenueAmount,

								   case when TransactionType in (5, 17, 18, 20, 22, 30) and COA_CNF_AccountConfig.Accountingtype = 1 then 2
								        when TransactionType in (5, 17, 18, 20, 22, 30) and COA_CNF_AccountConfig.Accountingtype = 2 then 1
										when TransactionType in (7) and rr_data_revenue.RevenueAmount &lt; 0 and COA_CNF_AccountConfig.Accountingtype = 2 then 1
								        else COA_CNF_AccountConfig.Accountingtype
									end Accountingtype,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
								   RR_CNF_RevenueRecognitionRule.Percentage,
								   RR_CNF_RevenueRecognitionRule.Days,
								   RR_DATA_REVENUE.AttributeIDs

							from RR_DATA_REVENUE
									inner join rr_cnf_Product						ON ((RR_DATA_REVENUE.MATRIXCELLID = rr_cnf_Product.MATRIXCELLID) 
                                                      or (RR_DATA_REVENUE.MatrixSheetId = rr_cnf_Product.MatrixSheetId)
													  or (rr_cnf_product.Attributeid in (select top 1 Attributeid
																							from rr_cnf_product
																							where Attributeid in (select Value
																													from dbo.split((select rr.Attributeids
																																	from rr_data_revenue rr
																																	where rr.revenuerecognitiondataid = RR_DATA_REVENUE.revenuerecognitiondataid), '.')
																												   )
																					    )
															))
													  and rr_cnf_Product.Enabled = 1
									inner join RR_CNF_RevenueRecognitionRule		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_cnf_Product.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  
									INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
									INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
									INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 
									INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid

							where RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger IN (@OnMoneyCardCashOut)

							  and RR_CNF_RevenueRecognitionRule.Enabled = 1
							  and coa_cnf_account.Enabled = 1
							  and COA_CNF_AccountConfig.Enabled = 1
							  and ((TransactionType in (10, 20, 18, 22)) or (RR_DATA_REVENUE.transactionid in (select transactionid
																									 from data_transaction
																										Inner join data_saleitem   on data_saleitem.saleid = data_transaction.saleid
																									where data_transaction.transactiontype in (14)
																									  and data_saleitem.unitrecharge &lt;&gt; 0
																								 )
																))
							  and ((coa_cnf_accountConfig.Siteid = RR_DATA_REVENUE.SiteId) or (coa_cnf_accountConfig.Siteid is null))
							  and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
							  and COA_CNF_AccountConfig.RemainingValues &lt;&gt; 1
							  and RR_DATA_REVENUE.fcalcdate = @BatchDate
							  and RR_DATA_REVENUE.coaaccountid = @suspendid
						
					)p
					where RevenueAmount &lt;&gt; 0

				--Normal Transaction with Remaining Values
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[Saleitemid]
				   ,[MatrixCellid]
				   ,[MatrixCellCode]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays]
				   ,[AttributeIDs])
				   select *
				   from(
						select distinct coa_cnf_account.COAAccountId, 
								   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
								   RR_CNF_RevenueRecognitionRule.code,		   
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
								   COA_CNF_AccountConfig.COAAccountConfigId,
								   coa_cnf_account.COAAccountTypeId,
								   coa_cnf_account.Code as AccountCode,
								   RR_DATA_REVENUE.Transactionid as Transactionid,
								   RR_DATA_REVENUE.saleid as Saleid,
								   RR_DATA_REVENUE.SaleitemID as SaleitemID,
								   RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								   RR_DATA_REVENUE.MatrixcellCode as MatrixCode,
								   RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								   RR_DATA_REVENUE.Siteid as SiteID,
								   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								   RR_DATA_REVENUE.Workstationid as Workstationid,
								   RR_DATA_REVENUE.UserGroupid as UserGroupID,
								   RR_DATA_REVENUE.UserId as userID,
								   @BatchDate as BatchDate,
								   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
								        else DATA_Transaction.transactiondate
								   end as TransDate,
								   RR_DATA_REVENUE.Quantity as Quantity,
								   RR_DATA_REVENUE.GrossAmount as GrossAmount,
								   RR_DATA_REVENUE.NetAmount as NetAmount,
								   COA_CNF_AccountConfig.Price as ConfigPrice,
								   COA_CNF_AccountConfig.Percentage as ConfigPercentage,
								   COA_CNF_AccountConfig.RemainingValues,							 
								   ISNULL((RR_DATA_REVENUE.RevenueAmount - (select ISNULL(sum(revenueamount), 0)
								                            from RR_DATA_Revenue rr
												              where rr.saleitemid = RR_DATA_REVENUE.SaleitemID
												        and rr.COAAccountid not in (@SuspendID, @ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)
												 )
									), 0)
									as RevenueAmount,
								   case when TransactionType in (5, 17, 18, 20, 22, 30) and COA_CNF_AccountConfig.Accountingtype = 1 then 2
								        when TransactionType in (5, 17, 18, 20, 22, 30) and COA_CNF_AccountConfig.Accountingtype = 2 then 1
										when TransactionType in (7) and rr_data_revenue.RevenueAmount &lt; 0 and COA_CNF_AccountConfig.Accountingtype = 2 then 1
								        else COA_CNF_AccountConfig.Accountingtype
									end Accountingtype,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
								   RR_CNF_RevenueRecognitionRule.Percentage,
								   RR_CNF_RevenueRecognitionRule.Days,
								   RR_DATA_REVENUE.AttributeIDs

						from RR_DATA_REVENUE
									inner join rr_cnf_Product						ON ((RR_DATA_REVENUE.MATRIXCELLID = rr_cnf_Product.MATRIXCELLID) 
                                                      or (RR_DATA_REVENUE.MatrixSheetId = rr_cnf_Product.MatrixSheetId)
													  or (rr_cnf_product.Attributeid in (select top 1 Attributeid
																							from rr_cnf_product
																							where Attributeid in (select Value
																													from dbo.split((select rr.Attributeids
																																	from rr_data_revenue rr
																																	where rr.revenuerecognitiondataid = RR_DATA_REVENUE.revenuerecognitiondataid), '.')
																												   )
																					    )
															))
													  and rr_cnf_Product.Enabled = 1
								inner join RR_CNF_RevenueRecognitionRule		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_cnf_Product.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  
								INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
								INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
								INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 
								INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid

							where RR_CNF_RevenueRecognitionRule.Enabled = 1
							  and coa_cnf_account.Enabled = 1
							  and COA_CNF_AccountConfig.Enabled = 1
							  and TransactionType in (10, 20, 18, 22)
							  and ((coa_cnf_accountConfig.Siteid = RR_DATA_REVENUE.SiteId) or (coa_cnf_accountConfig.Siteid is null))
							  and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger IN (@OnMoneyCardCashOut)
							  and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
							  and COA_CNF_AccountConfig.RemainingValues = 1
							  and RR_DATA_REVENUE.fcalcdate = @BatchDate
							  and RR_DATA_REVENUE.coaaccountid = @suspendid
					)p
					where RevenueAmount &lt;&gt; 0

		
		exec otn_sp_RR_RevenueData_PaymentMethodTaxDiscounts @BatchDate, '10,', @OnMoneyCardCashOut, @RRTransDateType									

	end
	select '@OnMoneyCardLoad' as TriggerType, @BatchDate as RunDate
END
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_RR_RevenueData_OnMoneyCardCashOut]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_RR_RevenueData_OnMoneyCardCashOut
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE Procedure dbo.otn_sp_RR_RevenueData_OnMoneyCardCashOut
	@BatchDate Date,
	@RRTransDateType Integer
AS 
BEGIN
	
	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer
	Declare @OnMoneyCardCashOut Integer = 11

	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1


		BEGIN

			--Normal Transaction No Remaining Values
			INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[Saleitemid]
				   ,[MatrixCellid]
				   ,[MatrixCellCode]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays]
				   ,[AttributeIDs])
				   select *
				   from(
							select coa_cnf_account.COAAccountId, 
								   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
								   RR_CNF_RevenueRecognitionRule.code,		   
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
								   COA_CNF_AccountConfig.COAAccountConfigId,
								   coa_cnf_account.COAAccountTypeId,
								   coa_cnf_account.Code as AccountCode,
								   RR_DATA_REVENUE.Transactionid as Transactionid,
								   RR_DATA_REVENUE.saleid as Saleid,
								   RR_DATA_REVENUE.SaleitemID as SaleitemID,
								   RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								   RR_DATA_REVENUE.MatrixcellCode as MatrixCode,
								   RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								   RR_DATA_REVENUE.Siteid as SiteID,
								   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								   RR_DATA_REVENUE.Workstationid as Workstationid,
								   RR_DATA_REVENUE.UserGroupid as UserGroupID,
								   RR_DATA_REVENUE.UserId as userID,
								   @BatchDate as BatchDate,
								   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
								        else DATA_Transaction.transactiondate
								   end as TransDate,
								   RR_DATA_REVENUE.Quantity as Quantity,
								   RR_DATA_REVENUE.GrossAmount as GrossAmount,
								   RR_DATA_REVENUE.NetAmount as NetAmount,
								   COA_CNF_AccountConfig.Price as ConfigPrice,
								   COA_CNF_AccountConfig.Percentage as ConfigPercentage,
								   COA_CNF_AccountConfig.RemainingValues,																		
									(CASE WHEN coa_cnf_account.coaaccountid not in (@ACCPaymentMethod, @TaxAccountID, @DiscountAccountID) then   --Accounts not Tax not PaymentMethods 
										Case when COA_CNF_AccountConfig.Price &gt; 0 then (COA_CNF_AccountConfig.Price * RR_DATA_REVENUE.Quantity) 
												else (ISNULL((((ABS(RR_DATA_REVENUE.RevenueAmount)) - ISNULL((select (ABS((sum(TaxAmount) * RR_DATA_REVENUE.Quantity)))
																										from data_saleitemTax
																										where saleitemid = RR_DATA_REVENUE.SaleitemID), 0)) * COA_CNF_AccountConfig.Percentage/100), 0))
										end 																		                                                                                                                                                                                              
									end)  as RevenueAmount,

								   COA_CNF_AccountConfig.Accountingtype,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
								   RR_CNF_RevenueRecognitionRule.Percentage,
								   RR_CNF_RevenueRecognitionRule.Days,
								   RR_DATA_REVENUE.AttributeIDs
		   
							from RR_DATA_REVENUE
									inner join rr_cnf_Product						ON ((RR_DATA_REVENUE.MATRIXCELLID = rr_cnf_Product.MATRIXCELLID) 
                                                      or (RR_DATA_REVENUE.MatrixSheetId = rr_cnf_Product.MatrixSheetId)
													  or (rr_cnf_product.Attributeid in (select top 1 Attributeid
																							from rr_cnf_product
																							where Attributeid in (select Value
																													from dbo.split((select rr.Attributeids
																																	from rr_data_revenue rr
																																	where rr.revenuerecognitiondataid = RR_DATA_REVENUE.revenuerecognitiondataid), '.')
																												   )
																					    )
															))
													  and rr_cnf_Product.Enabled = 1
									inner join RR_CNF_RevenueRecognitionRule		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_cnf_Product.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  
									INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
									INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
									INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 
									INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid

							where RR_CNF_RevenueRecognitionRule.Enabled = 1
							  and coa_cnf_account.Enabled = 1
							  and COA_CNF_AccountConfig.Enabled = 1
							  and TransactionType in (31)
							  and ((coa_cnf_accountConfig.Siteid = RR_DATA_REVENUE.SiteId) or (coa_cnf_accountConfig.Siteid is null))
							  and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger IN (@OnMoneyCardCashOut)
							  and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
							  and COA_CNF_AccountConfig.RemainingValues &lt;&gt; 1
							  and RR_DATA_REVENUE.fcalcdate = @BatchDate
							  and RR_DATA_REVENUE.coaaccountid = @suspendid
						
					)p
					where RevenueAmount &lt;&gt; 0

				--Normal Transaction with Remaining Values
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[Saleitemid]
				   ,[MatrixCellid]
				   ,[MatrixCellCode]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays]
				   ,[AttributeIDs])
				   select *
				   from(
						select distinct coa_cnf_account.COAAccountId, 
								   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
								   RR_CNF_RevenueRecognitionRule.code,		   
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
								   COA_CNF_AccountConfig.COAAccountConfigId,
								   coa_cnf_account.COAAccountTypeId,
								   coa_cnf_account.Code as AccountCode,
								   RR_DATA_REVENUE.Transactionid as Transactionid,
								   RR_DATA_REVENUE.saleid as Saleid,
								   RR_DATA_REVENUE.SaleitemID as SaleitemID,
								   RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								   RR_DATA_REVENUE.MatrixcellCode as MatrixCode,
								   RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								   RR_DATA_REVENUE.Siteid as SiteID,
								   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								   RR_DATA_REVENUE.Workstationid as Workstationid,
								   RR_DATA_REVENUE.UserGroupid as UserGroupID,
								   RR_DATA_REVENUE.UserId as userID,
								   @BatchDate as BatchDate,
								   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
								        else DATA_Transaction.transactiondate
								   end as TransDate,
								   RR_DATA_REVENUE.Quantity as Quantity,
								   RR_DATA_REVENUE.GrossAmount as GrossAmount,
								   RR_DATA_REVENUE.NetAmount as NetAmount,
								   COA_CNF_AccountConfig.Price as ConfigPrice,
								   COA_CNF_AccountConfig.Percentage as ConfigPercentage,
								   COA_CNF_AccountConfig.RemainingValues,							 
								   ISNULL((RR_DATA_REVENUE.RevenueAmount - (select ISNULL(sum(revenueamount), 0)
								                            from RR_DATA_Revenue rr
												              where rr.saleitemid = RR_DATA_REVENUE.SaleitemID
												        and rr.COAAccountid not in (@SuspendID, @ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)
												 )
									), 0)
									as RevenueAmount,
								   case when TransactionType in (5, 17, 18, 20, 22, 30) and COA_CNF_AccountConfig.Accountingtype = 1 then 2
								        when TransactionType in (5, 17, 18, 20, 22, 30) and COA_CNF_AccountConfig.Accountingtype = 2 then 1
								        else COA_CNF_AccountConfig.Accountingtype
									end Accountingtype,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
								   RR_CNF_RevenueRecognitionRule.Percentage,
								   RR_CNF_RevenueRecognitionRule.Days,
								   RR_DATA_REVENUE.AttributeIDs

						from RR_DATA_REVENUE
								inner join rr_cnf_Product						ON ((RR_DATA_REVENUE.MATRIXCELLID = rr_cnf_Product.MATRIXCELLID) 
                                                    or (RR_DATA_REVENUE.MatrixSheetId = rr_cnf_Product.MatrixSheetId)
													or (rr_cnf_product.Attributeid in (select top 1 Attributeid
																						from rr_cnf_product
																						where Attributeid in (select Value
																												from dbo.split((select rr.Attributeids
																																from rr_data_revenue rr
																																where rr.revenuerecognitiondataid = RR_DATA_REVENUE.revenuerecognitiondataid), '.')
																												)
																					)
														))
													and rr_cnf_Product.Enabled = 1
								inner join RR_CNF_RevenueRecognitionRule		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_cnf_Product.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  
								INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
								INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
								INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 
								INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid

							where RR_CNF_RevenueRecognitionRule.Enabled = 1
							  and coa_cnf_account.Enabled = 1
							  and COA_CNF_AccountConfig.Enabled = 1
							  and TransactionType in (31)
							  and ((coa_cnf_accountConfig.Siteid = RR_DATA_REVENUE.SiteId) or (coa_cnf_accountConfig.Siteid is null))
							  and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger IN (@OnMoneyCardCashOut)
							  and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
							  and COA_CNF_AccountConfig.RemainingValues = 1
							  and RR_DATA_REVENUE.fcalcdate = @BatchDate
							  and RR_DATA_REVENUE.coaaccountid = @suspendid
					)p
					where RevenueAmount &lt;&gt; 0

		
		exec otn_sp_RR_RevenueData_PaymentMethodTaxDiscounts @BatchDate, '31,', @OnMoneyCardCashOut, @RRTransDateType									

	end
	select '@OnMoneyCardCashOut' as TriggerType, @BatchDate as RunDate
END
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_RR_RevenueData_OnEventTrigger]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_RR_RevenueData_OnEventTrigger
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE Procedure dbo.otn_sp_RR_RevenueData_OnEventTrigger
	@BatchDate Date,
	@RRTransDateType Integer
AS 
BEGIN

	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer
	Declare @OnEventTrigger Integer = 17
	Declare @TicketUsageTrigger Integer = 2	

	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1

	BEGIN
																		  
			--Normal Transaction No Remaining Values
		INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[Ticketid]
				   ,[MatrixCellid]
				   ,[MatrixCellCode]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				   ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays]
				   ,[AttributeIDs])
				   select *
				   from(
				 select	COA_CNF_AccountConfig.COAAccountId, 
							RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
							RR_CNF_RevenueRecognitionRule.code,		   
							RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
							RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
							COA_CNF_AccountConfig.COAAccountConfigId,
							coa_cnf_account.COAAccountTypeId,
							coa_cnf_account.Code as AccountCode,
							p.Ticketid as Ticketid,
							p.Matrixcellid as Matrixcell,
							p.Code as MatrixCode,
							p.MatrixSheetId as MatrixSheetID,
							p.TicketSite as SiteID,
							@BatchDate as BatchDate,
							p.PerfDateTime,
							1 as Quantity,
							0 as GrossAmount,
							0 as NetAmount,
							COA_CNF_AccountConfig.Price as ConfigPrice,
							COA_CNF_AccountConfig.Percentage as ConfigPercentage,
							COA_CNF_AccountConfig.RemainingValues,									   
							CASE WHEN rdata.Ticketid is null then 									   
								Case when COA_CNF_AccountConfig.Price &gt; 0 then (COA_CNF_AccountConfig.Price)
										else ABS(NetAmount1 * COA_CNF_AccountConfig.Percentage/100)																	                                                                                                                                                                                              
								END 
							else case when rdata.totalprice &lt;&gt; rdata.totalused then
										ABS((rdata.totalprice - rdata.totalused) * COA_CNF_AccountConfig.Percentage/100)
									  else 0
								  END							               
							END as RevenueAmount,
							COA_CNF_AccountConfig.AccountingType,
							RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
							RR_CNF_RevenueRecognitionRule.Percentage,
							RR_CNF_RevenueRecognitionRule.Days,
							p.AttributeIDs

				  from RR_CNF_RevenueRecognitionRule
					   INNER JOIN RR_CNF_Product						ON RR_CNF_Product.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
					   INNER JOIN COA_CNF_AccountConfig					ON COA_CNF_AccountConfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId 
					   INNER JOIN COA_CNF_Account						on coa_cnf_account.COAAccountId = COA_CNF_AccountConfig.coaaccountid and  COA_CNF_Account.enabled = 1
					   INNER JOIN (	select *, (NetAmount/TotalCount) as NetAmount1
										from
										(
											select data_saleitem.saleitemid, 
													data_saleitem.matrixcellid, 
													cnf_matrixcell.matrixSheetid, 
													cnf_matrixcell.code, 
													data_saleitem.TotalAmount, 
													data_ticket.Price - data_ticket.taxes as NetAmount,
													cnf_performance.PerfDateTime as PerfDateTime, 
													(select top 1 siteid from data_transaction where data_transaction.saleid = data_saleitem.saleid) as SaleSite,
													data_ticket.Siteid as TicketSite,
													data_ticket.ticketID,
													cnf_matrixcell.AttributeSetId,
													AttributeIDs,
													1 as TotalCount

											from data_saleitem WITH(NOLOCK)
												INNER JOIN data_saleitem2performance WITH(NOLOCK)				on data_saleitem2performance.Saleitemid = data_saleitem.saleitemid
												INNER JOIN cnf_performance WITH(NOLOCK)							on cnf_performance.PerformanceId = data_saleitem2performance.performanceid
												INNER JOIN cnf_matrixcell WITH(NOLOCK)							on cnf_matrixcell.matrixcellid = data_saleitem.matrixcellid
												INNER JOIN CNF_AttributeSet	WITH(NOLOCK)						on cnf_matrixcell.AttributeSetId = cnf_matrixcell.AttributeSetId
												INNER JOIN data_saleitem2ticket WITH(NOLOCK)					on data_saleitem2ticket.SaleitemID = data_saleitem.saleitemID
												INNER JOIN data_ticket WITH(NOLOCK)								on data_ticket.ticketid = data_saleitem2ticket.ticketid

											where cast(cnf_performance.PerfDateTime as date) = @BatchDate
										)p1	
									)p  on						((p.matrixcellid   = rr_cnf_product.matrixcellid) or (p.matrixsheetid = rr_cnf_product.matrixsheetid)
																	or (rr_cnf_product.Attributeid in (select Value
																										from dbo.split((select Attributeids
																														from CNF_AttributeSet
																														where CNF_AttributeSet.AttributeSetId = p.AttributeSetId), '.')
																										)
																					    
															))
			                 left join (select *
													from 
													(
														select rr_data_revenue.ticketid, coaaccountid, (data_ticket.price-taxes) as TotalPrice, accountingtype, sum(revenueamount) as TotalUsed
														from rr_data_revenue
														INNER JOIN data_ticket with(nolock)    on data_ticket.ticketid = rr_data_revenue.ticketid
														where rr_data_revenue.RRCalcTypeTrigger = @TicketUsageTrigger
														group by rr_data_revenue.ticketid, accountingtype, coaaccountid, data_ticket.price, taxes
													)p1
															)rdata ON rdata.ticketid = p.ticketid	and rdata.AccountingType = coa_cnf_accountconfig.AccountingType

				where RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @OnEventTrigger
				  and rr_cnf_revenuerecognitionRule.Enabled = 1
				  and COA_CNF_AccountConfig.Enabled = 1
				  and COA_CNF_AccountConfig.RemainingValues &lt;&gt; 1
				)p
				where RevenueAmount &lt;&gt; 0 



		--Normal TicketExpired with Remaining Value
			INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[Ticketid]
				   ,[MatrixCellid]
				   ,[MatrixCellCode]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				   ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays]
				   ,[AttributeIDs])
				   select *
				   from(
				   select	COA_CNF_AccountConfig.COAAccountId, 
							RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
							RR_CNF_RevenueRecognitionRule.code,		   
							RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
							RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
							COA_CNF_AccountConfig.COAAccountConfigId,
							coa_cnf_account.COAAccountTypeId,
							coa_cnf_account.Code as AccountCode,
							p.Ticketid as Ticketid,
							p.Matrixcellid as Matrixcell,
							p.Code as MatrixCode,
							p.MatrixSheetId as MatrixSheetID,
							p.TicketSite as SiteID,
							@BatchDate as BatchDate,
							p.PerfDateTime,
							1 as Quantity,
							0 as GrossAmount,
							0 as NetAmount,
							COA_CNF_AccountConfig.Price as ConfigPrice,
							COA_CNF_AccountConfig.Percentage as ConfigPercentage,
							COA_CNF_AccountConfig.RemainingValues,									   
							CASE WHEN rdata.Ticketid is null then						   
								NetAmount1 -
										(ISNULL((select sum(revenueamount)
														from rr_data_revenue 
														where rr_data_revenue.ticketid = p.Ticketid
														and rr_data_revenue.FCalcDate = @BatchDate
														and rr_data_revenue.accountingtype = COA_CNF_AccountConfig.accountingtype
														and rr_data_revenue.coaaccountid in (select coa_cnf_accountconfig.COAAccountId
																								from coa_cnf_accountconfig
																								where coa_cnf_accountconfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId)
													), 0)) 
							else case when rdata.totalprice &lt;&gt; rdata.totalused then
										ABS((rdata.totalprice - rdata.totalused) * COA_CNF_AccountConfig.Percentage/100)
									  else 0
								  END							               
							END as RevenueAmount,
							COA_CNF_AccountConfig.AccountingType,
							RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
							RR_CNF_RevenueRecognitionRule.Percentage,
							RR_CNF_RevenueRecognitionRule.Days,
							p.AttributeIDs

				  from RR_CNF_RevenueRecognitionRule
					   INNER JOIN RR_CNF_Product						ON RR_CNF_Product.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
					   INNER JOIN COA_CNF_AccountConfig					ON COA_CNF_AccountConfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId 
					   INNER JOIN COA_CNF_Account						on coa_cnf_account.COAAccountId = COA_CNF_AccountConfig.coaaccountid and  COA_CNF_Account.enabled = 1
					   INNER JOIN (	select *, (NetAmount/TotalCount) as NetAmount1
										from
										(
											select data_saleitem.saleitemid, 
													data_saleitem.matrixcellid, 
													cnf_matrixcell.matrixSheetid, 
													cnf_matrixcell.code, 
													data_saleitem.TotalAmount, 
													data_ticket.Price - data_ticket.taxes as NetAmount,
													cnf_performance.PerfDateTime as PerfDateTime, 
													(select top 1 siteid from data_transaction where data_transaction.saleid = data_saleitem.saleid) as SaleSite,
													data_ticket.Siteid as TicketSite,
													data_ticket.ticketID,
													cnf_matrixcell.AttributeSetId,
													CNF_AttributeSet.AttributeIDs,
													(select count(*) 
														from data_saleitem DSI WITH(NOLOCK) 
															INNER JOIN data_saleitem2performance WITH(NOLOCK)				on data_saleitem2performance.Saleitemid = DSI.saleitemid
															INNER JOIN cnf_performance WITH(NOLOCK)							on cnf_performance.PerformanceId = data_saleitem2performance.performanceid
															INNER JOIN cnf_matrixcell WITH(NOLOCK)							on cnf_matrixcell.matrixcellid = data_saleitem.matrixcellid															
															INNER JOIN data_saleitem2ticket WITH(NOLOCK)					on data_saleitem2ticket.SaleitemID = data_saleitem.saleitemID
															INNER JOIN data_ticket WITH(NOLOCK)								on data_ticket.ticketid = data_saleitem2ticket.ticketid
														where DSI.saleitemid = data_saleitem.saleitemid
														) as TotalCount

											from data_saleitem WITH(NOLOCK)
												INNER JOIN data_saleitem2performance WITH(NOLOCK)				on data_saleitem2performance.Saleitemid = data_saleitem.saleitemid
												INNER JOIN cnf_performance WITH(NOLOCK)							on cnf_performance.PerformanceId = data_saleitem2performance.performanceid
												INNER JOIN cnf_matrixcell WITH(NOLOCK)							on cnf_matrixcell.matrixcellid = data_saleitem.matrixcellid
												INNER JOIN CNF_AttributeSet	WITH(NOLOCK)						on cnf_matrixcell.AttributeSetId = cnf_matrixcell.AttributeSetId
												INNER JOIN data_saleitem2ticket WITH(NOLOCK)					on data_saleitem2ticket.SaleitemID = data_saleitem.saleitemID
												INNER JOIN data_ticket WITH(NOLOCK)								on data_ticket.ticketid = data_saleitem2ticket.ticketid

											where cast(cnf_performance.PerfDateTime as date) = @BatchDate
										)p1	
									)p  on						((p.matrixcellid   = rr_cnf_product.matrixcellid) or (p.matrixsheetid = rr_cnf_product.matrixsheetid)
																	or (rr_cnf_product.Attributeid in (select Value
																										from dbo.split((select Attributeids
																														from CNF_AttributeSet
																														where CNF_AttributeSet.AttributeSetId = p.AttributeSetId), '.')
																										)
																					    
															))
									left join (select *
													from 
													(
														select rr_data_revenue.ticketid, coaaccountid, (data_ticket.price-taxes) as TotalPrice, accountingtype, sum(revenueamount) as TotalUsed
														from rr_data_revenue
														INNER JOIN data_ticket with(nolock)    on data_ticket.ticketid = rr_data_revenue.ticketid
														where rr_data_revenue.RRCalcTypeTrigger = @TicketUsageTrigger
														group by rr_data_revenue.ticketid, accountingtype, coaaccountid, data_ticket.price, taxes
													)p1
															)rdata									ON rdata.ticketid = p.ticketid	and rdata.AccountingType = coa_cnf_accountconfig.AccountingType

				where RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @OnEventTrigger
				  and rr_cnf_revenuerecognitionRule.Enabled = 1
				  and COA_CNF_AccountConfig.Enabled = 1
				  and COA_CNF_AccountConfig.RemainingValues = 1
				)p

																																																																																																
		End

	select 'OnEventTrigger' as TriggerType, @BatchDate as RunDate
END
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_RR_RevenueData_OnDepositTrigger]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_RR_RevenueData_OnDepositTrigger
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE Procedure dbo.otn_sp_RR_RevenueData_OnDepositTrigger
	@BatchDate Date,
	@RRTransDateType Integer
AS 
BEGIN

	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer
	Declare @DepositTrigger Integer = 5

	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1

	BEGIN																			
	--Normal Transaction No Remaining Values
			INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[Saleitemid]
				   ,[MatrixCellid]
				   ,[MatrixCellCode]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				   ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])
				   select *
				   from (
					select distinct p.COAAccountId, 
								p.RevenueRecognitionRuleId,
								p.code,		   
								p.RRCalcTypeWhere,
								p.RRCalcTypeMethod,	   
								p.COAAccountConfigId,
								p.COAAccountTypeId,
								p.AccountCode,
								RR_DATA_REVENUE.Transactionid as Transactionid,
								RR_DATA_REVENUE.saleid as Saleid,
								RR_DATA_REVENUE.SaleitemID as SaleitemID,
								RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								RR_DATA_REVENUE.MatrixcellCode as MatrixCode,
								RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								RR_DATA_REVENUE.Siteid as SiteID,
								RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								RR_DATA_REVENUE.Workstationid as Workstationid,
								RR_DATA_REVENUE.UserGroupid as UserGroupID,
								RR_DATA_REVENUE.UserId as userID,
								@BatchDate as BatchDate,
								case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
								     else DATA_Transaction.transactiondate
								  end as TransDate,
								RR_DATA_REVENUE.Quantity as Quantity,
								RR_DATA_REVENUE.GrossAmount as GrossAmount,
								RR_DATA_REVENUE.NetAmount as NetAmount,
								p.Price as ConfigPrice,
								p.Percentage as ConfigPercentage,
								p.RemainingValues,
								(CASE WHEN p.coaaccountid not in (@ACCPaymentMethod, @TaxAccountID, @DiscountAccountID) then   --Accounts not Tax not PaymentMethods 
									Case when p.Price &gt; 0 then (p.Price * RR_DATA_REVENUE.Quantity) 
											else (ISNULL((((ABS(RR_DATA_REVENUE.RevenueAmount)) - ISNULL((select (ABS((sum(TaxAmount) * RR_DATA_REVENUE.Quantity)))
																									from data_saleitemTax
																									where saleitemid = RR_DATA_REVENUE.SaleitemID), 0)) * p.Percentage/100), 0))
									end 																		                                                                                                                                                                                              
								end)  as RevenueAmount,
								case when TransactionType in (5, 17, 18, 20, 22, 30) and p.Accountingtype = 1 then 2
										when TransactionType in (5, 17, 18, 20, 22, 30) and p.Accountingtype = 2 then 1
										when TransactionType in (7) and rr_data_revenue.RevenueAmount &lt; 0 and p.Accountingtype = 1 then 2
										when TransactionType in (7) and rr_data_revenue.RevenueAmount &lt; 0 and p.Accountingtype = 2 then 1
										else p.Accountingtype
									end Accountingtype,
									p.RRCalcTypeTrigger,
									p.rrPercentage,
									p.Days						
						
						
							from RR_DATA_REVENUE
								INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
								INNER JOIN (select '1' as PCOAAccountid, 
												   coa_cnf_accountConfig.Siteid, 
												   RR_CNF_RevenueRecognitionRule.Enabled, 
												   RR_CNF_RevenueRecognitionRule.FromDate, 
												   RR_CNF_RevenueRecognitionRule.ToDate,
												   COA_CNF_AccountConfig.RemainingValues,
												   coa_cnf_account.coaaccountid,
												   COA_CNF_AccountConfig.Price,
												   COA_CNF_AccountConfig.Percentage,
												   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
												   RR_CNF_RevenueRecognitionRule.code,		   
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
												   COA_CNF_AccountConfig.COAAccountConfigId,
												   coa_cnf_account.COAAccountTypeId,
												   coa_cnf_account.Code as accountcode,
												   coa_cnf_accountconfig.Accountingtype,
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
												   RR_CNF_RevenueRecognitionRule.Percentage rrPercentage,
												   RR_CNF_RevenueRecognitionRule.Days	

												from RR_CNF_RevenueRecognitionRule	
												INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
												INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid and coa_cnf_account.Enabled = 1
												INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
											where  RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @DepositTrigger
											and RR_CNF_RevenueRecognitionRule.Enabled = 1
											and coa_cnf_account.coaaccountid not in (@ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)) p				on p.PCOAAccountid = rr_data_revenue.coaaccountid 

							where transactiontype in (12)													 
								and p.Enabled = 1
								and ((p.Siteid = RR_DATA_REVENUE.Siteid) or (p.Siteid is null))
								and @BatchDate between p.FromDate and p.ToDate
								and p.RemainingValues &lt;&gt; 1
								and RR_DATA_REVENUE.fcalcdate = @BatchDate
					)r 
					where r.revenueAmount &lt;&gt; 0


				--Normal Transaction with Remaining Values
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[Saleitemid]
				   ,[MatrixCellid]
				   ,[MatrixCellCode]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])
				   select *
				   from (
					select distinct p.COAAccountId, 
								p.RevenueRecognitionRuleId,
								p.code,		   
								p.RRCalcTypeWhere,
								p.RRCalcTypeMethod,	   
								p.COAAccountConfigId,
								p.COAAccountTypeId,
								p.AccountCode,
								RR_DATA_REVENUE.Transactionid as Transactionid,
								RR_DATA_REVENUE.saleid as Saleid,
								RR_DATA_REVENUE.SaleitemID as SaleitemID,
								RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								RR_DATA_REVENUE.MatrixcellCode as MatrixCode,
								RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								RR_DATA_REVENUE.Siteid as SiteID,
								RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								RR_DATA_REVENUE.Workstationid as Workstationid,
								RR_DATA_REVENUE.UserGroupid as UserGroupID,
								RR_DATA_REVENUE.UserId as userID,
								@BatchDate as BatchDate,
								case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
								     else DATA_Transaction.transactiondate
								  end as TransDate,
								RR_DATA_REVENUE.Quantity as Quantity,
								RR_DATA_REVENUE.GrossAmount as GrossAmount,
								RR_DATA_REVENUE.NetAmount as NetAmount,
								p.Price as ConfigPrice,
								p.Percentage as ConfigPercentage,
								p.RemainingValues,
								CASE WHEN p.coaaccountid not in (@ACCPaymentMethod, @TaxAccountID, @DiscountAccountID) then																																													 
							    ABS(ABS(RR_DATA_REVENUE.RevenueAmount) -					 
								ISNULL((select ABS(sum(RevenueAmount))
										from RR_DATA_Revenue rrd
									    where rrd.RevenueRecognitionRuleId = p.RevenueRecognitionRuleId
										and rrd.RevenueRecognitionRuleId not in (@SuspendID, @ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)
										and rrd.transactionid = RR_DATA_REVENUE.transactionid
								), 0)) 
								else 0
								end RevenueAmount,
								case when TransactionType in (5, 17, 18, 20, 22, 30) and p.Accountingtype = 1 then 2
										when TransactionType in (5, 17, 18, 20, 22, 30) and p.Accountingtype = 2 then 1
										when TransactionType in (7) and rr_data_revenue.RevenueAmount &lt; 0 and p.Accountingtype = 1 then 2
										when TransactionType in (7) and rr_data_revenue.RevenueAmount &lt; 0 and p.Accountingtype = 2 then 1
										else p.Accountingtype
									end Accountingtype,
									p.RRCalcTypeTrigger,
									p.rrPercentage,
									p.Days						
						
						
							from RR_DATA_REVENUE
								INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
								INNER JOIN (select '1' as PCOAAccountid, 
												   coa_cnf_accountConfig.Siteid, 
												   RR_CNF_RevenueRecognitionRule.Enabled, 
												   RR_CNF_RevenueRecognitionRule.FromDate, 
												   RR_CNF_RevenueRecognitionRule.ToDate,
												   COA_CNF_AccountConfig.RemainingValues,
												   coa_cnf_account.coaaccountid,
												   COA_CNF_AccountConfig.Price,
												   COA_CNF_AccountConfig.Percentage,
												   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
												   RR_CNF_RevenueRecognitionRule.code,		   
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
												   COA_CNF_AccountConfig.COAAccountConfigId,
												   coa_cnf_account.COAAccountTypeId,
												   coa_cnf_account.Code as accountcode,
												   coa_cnf_accountconfig.Accountingtype,
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
												   RR_CNF_RevenueRecognitionRule.Percentage rrPercentage,
												   RR_CNF_RevenueRecognitionRule.Days	

												from RR_CNF_RevenueRecognitionRule	
												INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
												INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid and coa_cnf_account.Enabled = 1
												INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
											where  RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @DepositTrigger
											and RR_CNF_RevenueRecognitionRule.Enabled = 1
											and coa_cnf_account.coaaccountid not in (@ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)) p				on p.PCOAAccountid = rr_data_revenue.coaaccountid 

							where transactiontype in (12)													 
								and p.Enabled = 1
								and ((p.Siteid = RR_DATA_REVENUE.Siteid) or (p.Siteid is null))
								and @BatchDate between p.FromDate and p.ToDate
								and p.RemainingValues = 1
								and RR_DATA_REVENUE.fcalcdate = @BatchDate		
					)r 
					where r.revenueAmount &lt;&gt; 0	

		exec otn_sp_RR_RevenueData_PaymentMethodTaxDiscounts2 @BatchDate, '12,',   @DepositTrigger, @RRTransDateType
	end
	
	select 'OnDepositTrigger' as TriggerType, @BatchDate as RunDate

END
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_RR_RevenueData_OnCreditWriteoff]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_RR_RevenueData_OnCreditWriteoff
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE Procedure dbo.otn_sp_RR_RevenueData_OnCreditWriteoff
	@BatchDate Date,
	@RRTransDateType Integer
AS 
BEGIN

	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer
	Declare @OnCreditWriteoff Integer = 9

	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1

	
BEGIN	
			--Normal Transaction No Remaining Values
			INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[Saleitemid]
				   ,[MatrixCellid]
				   ,[MatrixCellCode]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				   ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])
				   select *
				   from (
					select distinct p.COAAccountId, 
								p.RevenueRecognitionRuleId,
								p.code,		   
								p.RRCalcTypeWhere,
								p.RRCalcTypeMethod,	   
								p.COAAccountConfigId,
								p.COAAccountTypeId,
								p.AccountCode,
								RR_DATA_REVENUE.Transactionid as Transactionid,
								RR_DATA_REVENUE.saleid as Saleid,
								RR_DATA_REVENUE.SaleitemID as SaleitemID,
								RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								RR_DATA_REVENUE.MatrixcellCode as MatrixCode,
								RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								RR_DATA_REVENUE.Siteid as SiteID,
								RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								RR_DATA_REVENUE.Workstationid as Workstationid,
								RR_DATA_REVENUE.UserGroupid as UserGroupID,
								RR_DATA_REVENUE.UserId as userID,
								@BatchDate as BatchDate,
								case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
								     else DATA_Transaction.transactiondate
								  end as TransDate,
								RR_DATA_REVENUE.Quantity as Quantity,
								RR_DATA_REVENUE.GrossAmount as GrossAmount,
								RR_DATA_REVENUE.NetAmount as NetAmount,
								p.Price as ConfigPrice,
								p.Percentage as ConfigPercentage,
								p.RemainingValues,
								(CASE WHEN p.coaaccountid not in (@ACCPaymentMethod, @TaxAccountID, @DiscountAccountID) then   --Accounts not Tax not PaymentMethods 
									Case when p.Price &gt; 0 then (p.Price * RR_DATA_REVENUE.Quantity) 
											else (ISNULL((((ABS(RR_DATA_REVENUE.RevenueAmount)) - ISNULL((select (ABS((sum(TaxAmount) * RR_DATA_REVENUE.Quantity)))
																									from data_saleitemTax
																									where saleitemid = RR_DATA_REVENUE.SaleitemID), 0)) * p.Percentage/100), 0))
									end 																		                                                                                                                                                                                              
								end)  as RevenueAmount,
								case when TransactionType in (5, 17, 18, 20, 22, 30) and p.Accountingtype = 1 then 2
										when TransactionType in (5, 17, 18, 20, 22, 30) and p.Accountingtype = 2 then 1
										when TransactionType in (7) and rr_data_revenue.RevenueAmount &lt; 0 and p.Accountingtype = 1 then 2
										when TransactionType in (7) and rr_data_revenue.RevenueAmount &lt; 0 and p.Accountingtype = 2 then 1
										else p.Accountingtype
									end Accountingtype,
									p.RRCalcTypeTrigger,
									p.rrPercentage,
									p.Days						
						
						
							from RR_DATA_REVENUE
								INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
								INNER JOIN (select '1' as PCOAAccountid, 
												   coa_cnf_accountConfig.Siteid, 
												   RR_CNF_RevenueRecognitionRule.Enabled, 
												   RR_CNF_RevenueRecognitionRule.FromDate, 
												   RR_CNF_RevenueRecognitionRule.ToDate,
												   COA_CNF_AccountConfig.RemainingValues,
												   coa_cnf_account.coaaccountid,
												   COA_CNF_AccountConfig.Price,
												   COA_CNF_AccountConfig.Percentage,
												   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
												   RR_CNF_RevenueRecognitionRule.code,		   
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
												   COA_CNF_AccountConfig.COAAccountConfigId,
												   coa_cnf_account.COAAccountTypeId,
												   coa_cnf_account.Code as accountcode,
												   coa_cnf_accountconfig.Accountingtype,
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
												   RR_CNF_RevenueRecognitionRule.Percentage rrPercentage,
												   RR_CNF_RevenueRecognitionRule.Days	

												from RR_CNF_RevenueRecognitionRule	
												INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
												INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid and coa_cnf_account.Enabled = 1
												INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
											where  RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @OnCreditWriteoff
											and RR_CNF_RevenueRecognitionRule.Enabled = 1
											and coa_cnf_account.coaaccountid not in (@ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)) p				on p.PCOAAccountid = rr_data_revenue.coaaccountid 

							where transactiontype in (8)													 
								and p.Enabled = 1
								and ((p.Siteid = RR_DATA_REVENUE.Siteid) or (p.Siteid is null))
								and @BatchDate between p.FromDate and p.ToDate
								and p.RemainingValues &lt;&gt; 1
								and RR_DATA_REVENUE.fcalcdate = @BatchDate
					)r 
					where r.revenueAmount &lt;&gt; 0


				--Normal Transaction with Remaining Values
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[Saleitemid]
				   ,[MatrixCellid]
				   ,[MatrixCellCode]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])
				   select *
				   from (
					select distinct p.COAAccountId, 
								p.RevenueRecognitionRuleId,
								p.code,		   
								p.RRCalcTypeWhere,
								p.RRCalcTypeMethod,	   
								p.COAAccountConfigId,
								p.COAAccountTypeId,
								p.AccountCode,
								RR_DATA_REVENUE.Transactionid as Transactionid,
								RR_DATA_REVENUE.saleid as Saleid,
								RR_DATA_REVENUE.SaleitemID as SaleitemID,
								RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								RR_DATA_REVENUE.MatrixcellCode as MatrixCode,
								RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								RR_DATA_REVENUE.Siteid as SiteID,
								RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								RR_DATA_REVENUE.Workstationid as Workstationid,
								RR_DATA_REVENUE.UserGroupid as UserGroupID,
								RR_DATA_REVENUE.UserId as userID,
								@BatchDate as BatchDate,
								case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
								     else DATA_Transaction.transactiondate
								  end as TransDate,
								RR_DATA_REVENUE.Quantity as Quantity,
								RR_DATA_REVENUE.GrossAmount as GrossAmount,
								RR_DATA_REVENUE.NetAmount as NetAmount,
								p.Price as ConfigPrice,
								p.Percentage as ConfigPercentage,
								p.RemainingValues,
								CASE WHEN p.coaaccountid not in (@ACCPaymentMethod, @TaxAccountID, @DiscountAccountID) then																																													 
							    ABS(ABS(RR_DATA_REVENUE.RevenueAmount) -					 
								ISNULL((select ABS(sum(RevenueAmount))
										from RR_DATA_Revenue rrd
									    where rrd.RevenueRecognitionRuleId = p.RevenueRecognitionRuleId
										and rrd.RevenueRecognitionRuleId not in (@SuspendID, @ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)
										and rrd.transactionid = RR_DATA_REVENUE.transactionid
								), 0)) 
								else 0
								end RevenueAmount,
								case when TransactionType in (5, 17, 18, 20, 22, 30) and p.Accountingtype = 1 then 2
										when TransactionType in (5, 17, 18, 20, 22, 30) and p.Accountingtype = 2 then 1
										when TransactionType in (7) and rr_data_revenue.RevenueAmount &lt; 0 and p.Accountingtype = 1 then 2
										when TransactionType in (7) and rr_data_revenue.RevenueAmount &lt; 0 and p.Accountingtype = 2 then 1
										else p.Accountingtype
									end Accountingtype,
									p.RRCalcTypeTrigger,
									p.rrPercentage,
									p.Days						
						
						
							from RR_DATA_REVENUE
								INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
								INNER JOIN (select '1' as PCOAAccountid, 
												   coa_cnf_accountConfig.Siteid, 
												   RR_CNF_RevenueRecognitionRule.Enabled, 
												   RR_CNF_RevenueRecognitionRule.FromDate, 
												   RR_CNF_RevenueRecognitionRule.ToDate,
												   COA_CNF_AccountConfig.RemainingValues,
												   coa_cnf_account.coaaccountid,
												   COA_CNF_AccountConfig.Price,
												   COA_CNF_AccountConfig.Percentage,
												   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
												   RR_CNF_RevenueRecognitionRule.code,		   
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
												   COA_CNF_AccountConfig.COAAccountConfigId,
												   coa_cnf_account.COAAccountTypeId,
												   coa_cnf_account.Code as accountcode,
												   coa_cnf_accountconfig.Accountingtype,
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
												   RR_CNF_RevenueRecognitionRule.Percentage rrPercentage,
												   RR_CNF_RevenueRecognitionRule.Days	

												from RR_CNF_RevenueRecognitionRule	
												INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
												INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid and coa_cnf_account.Enabled = 1
												INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
											where  RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @OnCreditWriteoff
											and RR_CNF_RevenueRecognitionRule.Enabled = 1
											and coa_cnf_account.coaaccountid not in (@ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)) p				on p.PCOAAccountid = rr_data_revenue.coaaccountid 

							where transactiontype in (8)													 
								and p.Enabled = 1
								and ((p.Siteid = RR_DATA_REVENUE.Siteid) or (p.Siteid is null))
								and @BatchDate between p.FromDate and p.ToDate
								and p.RemainingValues = 1
								and RR_DATA_REVENUE.fcalcdate = @BatchDate		
					)r 
					where r.revenueAmount &lt;&gt; 0

				exec otn_sp_RR_RevenueData_PaymentMethodTaxDiscounts2 @BatchDate, '8,',   @OnCreditWriteoff, @RRTransDateType
	end

	select 'OnCreditWriteoffTrigger' as TriggerType, @BatchDate as RunDate

END
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_RR_RevenueData_OnAdvancedPaymentTrigger]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_RR_RevenueData_OnAdvancedPaymentTrigger
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE Procedure dbo.otn_sp_RR_RevenueData_OnAdvancedPaymentTrigger
	@BatchDate Date,
	@RRTransDateType Integer
AS 
BEGIN

	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer
	Declare @OnAdvancePaymentTrigger Integer = 7

	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1


BEGIN	
			--Normal Transaction No Remaining Values
			INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[Saleitemid]
				   ,[MatrixCellid]
				   ,[MatrixCellCode]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				   ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])
				   select *
				   from (
					select distinct p.COAAccountId, 
								p.RevenueRecognitionRuleId,
								p.code,		   
								p.RRCalcTypeWhere,
								p.RRCalcTypeMethod,	   
								p.COAAccountConfigId,
								p.COAAccountTypeId,
								p.AccountCode,
								RR_DATA_REVENUE.Transactionid as Transactionid,
								RR_DATA_REVENUE.saleid as Saleid,
								RR_DATA_REVENUE.SaleitemID as SaleitemID,
								RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								RR_DATA_REVENUE.MatrixcellCode as MatrixCode,
								RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								RR_DATA_REVENUE.Siteid as SiteID,
								RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								RR_DATA_REVENUE.Workstationid as Workstationid,
								RR_DATA_REVENUE.UserGroupid as UserGroupID,
								RR_DATA_REVENUE.UserId as userID,
								@BatchDate as BatchDate,
								case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
								     else DATA_Transaction.transactiondate
								  end as TransDate,
								RR_DATA_REVENUE.Quantity as Quantity,
								RR_DATA_REVENUE.GrossAmount as GrossAmount,
								RR_DATA_REVENUE.NetAmount as NetAmount,
								p.Price as ConfigPrice,
								p.Percentage as ConfigPercentage,
								p.RemainingValues,
								(CASE WHEN p.coaaccountid not in (@ACCPaymentMethod, @TaxAccountID, @DiscountAccountID) then   --Accounts not Tax not PaymentMethods 
									Case when p.Price &gt; 0 then (p.Price * RR_DATA_REVENUE.Quantity) 
											else (ISNULL((((ABS(RR_DATA_REVENUE.RevenueAmount)) - ISNULL((select (ABS((sum(TaxAmount) * RR_DATA_REVENUE.Quantity)))
																									from data_saleitemTax
																									where saleitemid = RR_DATA_REVENUE.SaleitemID), 0)) * p.Percentage/100), 0))
									end 																		                                                                                                                                                                                              
								end)  as RevenueAmount,
								case when TransactionType in (5, 17, 18, 20, 22, 30) and p.Accountingtype = 1 then 2
										when TransactionType in (5, 17, 18, 20, 22, 30) and p.Accountingtype = 2 then 1
										when TransactionType in (7) and rr_data_revenue.RevenueAmount &lt; 0 and p.Accountingtype = 1 then 2
										when TransactionType in (7) and rr_data_revenue.RevenueAmount &lt; 0 and p.Accountingtype = 2 then 1
										else p.Accountingtype
									end Accountingtype,
									p.RRCalcTypeTrigger,
									p.rrPercentage,
									p.Days						
						
						
							from RR_DATA_REVENUE
								INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
								INNER JOIN (select '1' as PCOAAccountid, 
												   coa_cnf_accountConfig.Siteid, 
												   RR_CNF_RevenueRecognitionRule.Enabled, 
												   RR_CNF_RevenueRecognitionRule.FromDate, 
												   RR_CNF_RevenueRecognitionRule.ToDate,
												   COA_CNF_AccountConfig.RemainingValues,
												   coa_cnf_account.coaaccountid,
												   COA_CNF_AccountConfig.Price,
												   COA_CNF_AccountConfig.Percentage,
												   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
												   RR_CNF_RevenueRecognitionRule.code,		   
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
												   COA_CNF_AccountConfig.COAAccountConfigId,
												   coa_cnf_account.COAAccountTypeId,
												   coa_cnf_account.Code as accountcode,
												   coa_cnf_accountconfig.Accountingtype,
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
												   RR_CNF_RevenueRecognitionRule.Percentage rrPercentage,
												   RR_CNF_RevenueRecognitionRule.Days	

												from RR_CNF_RevenueRecognitionRule	
												INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
												INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid and coa_cnf_account.Enabled = 1
												INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
											where  RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @OnAdvancePaymentTrigger
											and RR_CNF_RevenueRecognitionRule.Enabled = 1
											and coa_cnf_account.coaaccountid not in (@ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)) p				on p.PCOAAccountid = rr_data_revenue.coaaccountid 

							where transactiontype in (34)													 
								and p.Enabled = 1
								and ((p.Siteid = RR_DATA_REVENUE.Siteid) or (p.Siteid is null))
								and @BatchDate between p.FromDate and p.ToDate
								and p.RemainingValues &lt;&gt; 1
								and RR_DATA_REVENUE.fcalcdate = @BatchDate
					)r 
					where r.revenueAmount &lt;&gt; 0


				--Normal Transaction with Remaining Values
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[Saleitemid]
				   ,[MatrixCellid]
				   ,[MatrixCellCode]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])
				   select *
				   from (
					select distinct p.COAAccountId, 
								p.RevenueRecognitionRuleId,
								p.code,		   
								p.RRCalcTypeWhere,
								p.RRCalcTypeMethod,	   
								p.COAAccountConfigId,
								p.COAAccountTypeId,
								p.AccountCode,
								RR_DATA_REVENUE.Transactionid as Transactionid,
								RR_DATA_REVENUE.saleid as Saleid,
								RR_DATA_REVENUE.SaleitemID as SaleitemID,
								RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								RR_DATA_REVENUE.MatrixcellCode as MatrixCode,
								RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								RR_DATA_REVENUE.Siteid as SiteID,
								RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								RR_DATA_REVENUE.Workstationid as Workstationid,
								RR_DATA_REVENUE.UserGroupid as UserGroupID,
								RR_DATA_REVENUE.UserId as userID,
								@BatchDate as BatchDate,
								case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
								     else DATA_Transaction.transactiondate
								  end as TransDate,
								RR_DATA_REVENUE.Quantity as Quantity,
								RR_DATA_REVENUE.GrossAmount as GrossAmount,
								RR_DATA_REVENUE.NetAmount as NetAmount,
								p.Price as ConfigPrice,
								p.Percentage as ConfigPercentage,
								p.RemainingValues,
								CASE WHEN p.coaaccountid not in (@ACCPaymentMethod, @TaxAccountID, @DiscountAccountID) then																																													 
							    ABS(ABS(RR_DATA_REVENUE.RevenueAmount) -					 
								ISNULL((select ABS(sum(RevenueAmount))
										from RR_DATA_Revenue rrd
									    where rrd.RevenueRecognitionRuleId = p.RevenueRecognitionRuleId
										and rrd.RevenueRecognitionRuleId not in (@SuspendID, @ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)
										and rrd.transactionid = RR_DATA_REVENUE.transactionid
								), 0)) 
								else 0
								end RevenueAmount,
								case when TransactionType in (5, 17, 18, 20, 22, 30) and p.Accountingtype = 1 then 2
										when TransactionType in (5, 17, 18, 20, 22, 30) and p.Accountingtype = 2 then 1
										when TransactionType in (7) and rr_data_revenue.RevenueAmount &lt; 0 and p.Accountingtype = 1 then 2
										when TransactionType in (7) and rr_data_revenue.RevenueAmount &lt; 0 and p.Accountingtype = 2 then 1
										else p.Accountingtype
									end Accountingtype,
									p.RRCalcTypeTrigger,
									p.rrPercentage,
									p.Days						
						
						
							from RR_DATA_REVENUE
								INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
								INNER JOIN (select '1' as PCOAAccountid, 
												   coa_cnf_accountConfig.Siteid, 
												   RR_CNF_RevenueRecognitionRule.Enabled, 
												   RR_CNF_RevenueRecognitionRule.FromDate, 
												   RR_CNF_RevenueRecognitionRule.ToDate,
												   COA_CNF_AccountConfig.RemainingValues,
												   coa_cnf_account.coaaccountid,
												   COA_CNF_AccountConfig.Price,
												   COA_CNF_AccountConfig.Percentage,
												   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
												   RR_CNF_RevenueRecognitionRule.code,		   
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
												   COA_CNF_AccountConfig.COAAccountConfigId,
												   coa_cnf_account.COAAccountTypeId,
												   coa_cnf_account.Code as accountcode,
												   coa_cnf_accountconfig.Accountingtype,
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
												   RR_CNF_RevenueRecognitionRule.Percentage rrPercentage,
												   RR_CNF_RevenueRecognitionRule.Days	

												from RR_CNF_RevenueRecognitionRule	
												INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
												INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid and coa_cnf_account.Enabled = 1
												INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
											where  RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @OnAdvancePaymentTrigger
											and RR_CNF_RevenueRecognitionRule.Enabled = 1
											and coa_cnf_account.coaaccountid not in (@ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)) p				on p.PCOAAccountid = rr_data_revenue.coaaccountid 

							where transactiontype in (34)													 
								and p.Enabled = 1
								and ((p.Siteid = RR_DATA_REVENUE.Siteid) or (p.Siteid is null))
								and @BatchDate between p.FromDate and p.ToDate
								and p.RemainingValues = 1
								and RR_DATA_REVENUE.fcalcdate = @BatchDate		
					)r 
					where r.revenueAmount &lt;&gt; 0

				exec otn_sp_RR_RevenueData_PaymentMethodTaxDiscounts2 @BatchDate, '34,',   @OnAdvancePaymentTrigger, @RRTransDateType
	end

	select 'OnAdvancePaymentTrigger' as TriggerType, @BatchDate as RunDate

END
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_RR_RevenueData_OnExternalMoneyCardLoad]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_RR_RevenueData_OnExternalMoneyCardLoad
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE Procedure dbo.otn_sp_RR_RevenueData_OnExternalMoneyCardLoad
	@BatchDate Date,
	@RRTransDateType Integer
AS 
BEGIN
	
	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer
	Declare @OnMoneyCardCashOut Integer = 15

	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1


		BEGIN

			--Normal Transaction No Remaining Values
			INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[Saleitemid]
				   ,[MatrixCellid]
				   ,[MatrixCellCode]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays]
				   ,[AttributeIDs])
				   select *
				   from(
							select coa_cnf_account.COAAccountId, 
								   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
								   RR_CNF_RevenueRecognitionRule.code,		   
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
								   COA_CNF_AccountConfig.COAAccountConfigId,
								   coa_cnf_account.COAAccountTypeId,
								   coa_cnf_account.Code as AccountCode,
								   RR_DATA_REVENUE.Transactionid as Transactionid,
								   RR_DATA_REVENUE.saleid as Saleid,
								   RR_DATA_REVENUE.SaleitemID as SaleitemID,
								   RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								   RR_DATA_REVENUE.MatrixcellCode as MatrixCode,
								   RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								   RR_DATA_REVENUE.Siteid as SiteID,
								   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								   RR_DATA_REVENUE.Workstationid as Workstationid,
								   RR_DATA_REVENUE.UserGroupid as UserGroupID,
								   RR_DATA_REVENUE.UserId as userID,
								   @BatchDate as BatchDate,
								   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
								        else DATA_Transaction.transactiondate
								   end as TransDate,
								   RR_DATA_REVENUE.Quantity as Quantity,
								   RR_DATA_REVENUE.GrossAmount as GrossAmount,
								   RR_DATA_REVENUE.NetAmount as NetAmount,
								   COA_CNF_AccountConfig.Price as ConfigPrice,
								   COA_CNF_AccountConfig.Percentage as ConfigPercentage,
								   COA_CNF_AccountConfig.RemainingValues,																		
									(CASE WHEN coa_cnf_account.coaaccountid not in (@ACCPaymentMethod, @TaxAccountID, @DiscountAccountID) then   --Accounts not Tax not PaymentMethods 
										Case when COA_CNF_AccountConfig.Price &gt; 0 then (COA_CNF_AccountConfig.Price * RR_DATA_REVENUE.Quantity) 
												else (ISNULL((((ABS(RR_DATA_REVENUE.RevenueAmount)) - ISNULL((select (ABS((sum(TaxAmount) * RR_DATA_REVENUE.Quantity)))
																										from data_saleitemTax
																										where saleitemid = RR_DATA_REVENUE.SaleitemID), 0)) * COA_CNF_AccountConfig.Percentage/100), 0))
										end 																		                                                                                                                                                                                              
									end)  as RevenueAmount,

								   COA_CNF_AccountConfig.Accountingtype,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
								   RR_CNF_RevenueRecognitionRule.Percentage,
								   RR_CNF_RevenueRecognitionRule.Days,
								   RR_DATA_REVENUE.AttributeIDs
		   
							from RR_DATA_REVENUE
									inner join rr_cnf_Product						ON ((RR_DATA_REVENUE.MATRIXCELLID = rr_cnf_Product.MATRIXCELLID) 
                                                      or (RR_DATA_REVENUE.MatrixSheetId = rr_cnf_Product.MatrixSheetId)
													  or (rr_cnf_product.Attributeid in (select top 1 Attributeid
																							from rr_cnf_product
																							where Attributeid in (select Value
																													from dbo.split((select rr.Attributeids
																																	from rr_data_revenue rr
																																	where rr.revenuerecognitiondataid = RR_DATA_REVENUE.revenuerecognitiondataid), '.')
																												   )
																					    )
															))
													  and rr_cnf_Product.Enabled = 1
									inner join RR_CNF_RevenueRecognitionRule		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_cnf_Product.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  
									INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
									INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
									INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 
									INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid

							where RR_CNF_RevenueRecognitionRule.Enabled = 1
							  and coa_cnf_account.Enabled = 1
							  and COA_CNF_AccountConfig.Enabled = 1
							  and TransactionType in (42, 43, 49)
							  and ((coa_cnf_accountConfig.Siteid = RR_DATA_REVENUE.SiteId) or (coa_cnf_accountConfig.Siteid is null))
							  and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger IN (@OnMoneyCardCashOut)
							  and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
							  and COA_CNF_AccountConfig.RemainingValues &lt;&gt; 1
							  and RR_DATA_REVENUE.fcalcdate = @BatchDate
							  and RR_DATA_REVENUE.coaaccountid = @suspendid
						
					)p
					where RevenueAmount &lt;&gt; 0

				--Normal Transaction with Remaining Values
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[Saleitemid]
				   ,[MatrixCellid]
				   ,[MatrixCellCode]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays]
				   ,[AttributeIDs])
				   select *
				   from(
						select distinct coa_cnf_account.COAAccountId, 
								   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
								   RR_CNF_RevenueRecognitionRule.code,		   
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
								   COA_CNF_AccountConfig.COAAccountConfigId,
								   coa_cnf_account.COAAccountTypeId,
								   coa_cnf_account.Code as AccountCode,
								   RR_DATA_REVENUE.Transactionid as Transactionid,
								   RR_DATA_REVENUE.saleid as Saleid,
								   RR_DATA_REVENUE.SaleitemID as SaleitemID,
								   RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								   RR_DATA_REVENUE.MatrixcellCode as MatrixCode,
								   RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								   RR_DATA_REVENUE.Siteid as SiteID,
								   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								   RR_DATA_REVENUE.Workstationid as Workstationid,
								   RR_DATA_REVENUE.UserGroupid as UserGroupID,
								   RR_DATA_REVENUE.UserId as userID,
								   @BatchDate as BatchDate,
								   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
								        else DATA_Transaction.transactiondate
								   end as TransDate,
								   RR_DATA_REVENUE.Quantity as Quantity,
								   RR_DATA_REVENUE.GrossAmount as GrossAmount,
								   RR_DATA_REVENUE.NetAmount as NetAmount,
								   COA_CNF_AccountConfig.Price as ConfigPrice,
								   COA_CNF_AccountConfig.Percentage as ConfigPercentage,
								   COA_CNF_AccountConfig.RemainingValues,							 
								   ISNULL((RR_DATA_REVENUE.RevenueAmount - (select ISNULL(sum(revenueamount), 0)
								                            from RR_DATA_Revenue rr
												              where rr.saleitemid = RR_DATA_REVENUE.SaleitemID
												        and rr.COAAccountid not in (@SuspendID, @ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)
												 )
									), 0)
									as RevenueAmount,
								   case when TransactionType in (5, 17, 18, 20, 22, 30) and COA_CNF_AccountConfig.Accountingtype = 1 then 2
								        when TransactionType in (5, 17, 18, 20, 22, 30) and COA_CNF_AccountConfig.Accountingtype = 2 then 1
								        else COA_CNF_AccountConfig.Accountingtype
									end Accountingtype,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
								   RR_CNF_RevenueRecognitionRule.Percentage,
								   RR_CNF_RevenueRecognitionRule.Days,
								   RR_DATA_REVENUE.AttributeIDs

						from RR_DATA_REVENUE
								inner join rr_cnf_Product						ON ((RR_DATA_REVENUE.MATRIXCELLID = rr_cnf_Product.MATRIXCELLID) 
                                                      or (RR_DATA_REVENUE.MatrixSheetId = rr_cnf_Product.MatrixSheetId)
													  or (rr_cnf_product.Attributeid in (select top 1 Attributeid
																							from rr_cnf_product
																							where Attributeid in (select Value
																													from dbo.split((select rr.Attributeids
																																	from rr_data_revenue rr
																																	where rr.revenuerecognitiondataid = RR_DATA_REVENUE.revenuerecognitiondataid), '.')
																												   )
																					    )
															))
													  and rr_cnf_Product.Enabled = 1
								inner join RR_CNF_RevenueRecognitionRule		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_cnf_Product.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  
								INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
								INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
								INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 
								INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid

							where RR_CNF_RevenueRecognitionRule.Enabled = 1
							  and coa_cnf_account.Enabled = 1
							  and COA_CNF_AccountConfig.Enabled = 1
							  and TransactionType in (42, 43, 49)
							  and ((coa_cnf_accountConfig.Siteid = RR_DATA_REVENUE.SiteId) or (coa_cnf_accountConfig.Siteid is null))
							  and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger IN (@OnMoneyCardCashOut)
							  and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
							  and COA_CNF_AccountConfig.RemainingValues = 1
							  and RR_DATA_REVENUE.fcalcdate = @BatchDate
							  and RR_DATA_REVENUE.coaaccountid = @suspendid
					)p
					where RevenueAmount &lt;&gt; 0

		
		exec otn_sp_RR_RevenueData_PaymentMethodTaxDiscounts @BatchDate, '42, 43, 49,', @OnMoneyCardCashOut, @RRTransDateType										

	end
	select '@OnExternalMoneyCardLoad' as TriggerType, @BatchDate as RunDate
END
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_RR_RevenueData_OnExternalMoneyCardCashOut]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_RR_RevenueData_OnExternalMoneyCardCashOut
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE Procedure dbo.otn_sp_RR_RevenueData_OnExternalMoneyCardCashOut
	@BatchDate Date,
	@RRTransDateType Integer
AS 
BEGIN

	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer
	Declare @OnMoneyCardCashOut Integer = 16

	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1


		BEGIN

			--Normal Transaction No Remaining Values
			INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[Saleitemid]
				   ,[MatrixCellid]
				   ,[MatrixCellCode]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays]
				   ,[AttributeIDs])
				   select *
				   from(
							select coa_cnf_account.COAAccountId, 
								   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
								   RR_CNF_RevenueRecognitionRule.code,		   
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
								   COA_CNF_AccountConfig.COAAccountConfigId,
								   coa_cnf_account.COAAccountTypeId,
								   coa_cnf_account.Code as AccountCode,
								   RR_DATA_REVENUE.Transactionid as Transactionid,
								   RR_DATA_REVENUE.saleid as Saleid,
								   RR_DATA_REVENUE.SaleitemID as SaleitemID,
								   RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								   RR_DATA_REVENUE.MatrixcellCode as MatrixCode,
								   RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								   RR_DATA_REVENUE.Siteid as SiteID,
								   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								   RR_DATA_REVENUE.Workstationid as Workstationid,
								   RR_DATA_REVENUE.UserGroupid as UserGroupID,
								   RR_DATA_REVENUE.UserId as userID,
								   @BatchDate as BatchDate,
								   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
								        else DATA_Transaction.transactiondate
								   end as TransDate,
								   RR_DATA_REVENUE.Quantity as Quantity,
								   RR_DATA_REVENUE.GrossAmount as GrossAmount,
								   RR_DATA_REVENUE.NetAmount as NetAmount,
								   COA_CNF_AccountConfig.Price as ConfigPrice,
								   COA_CNF_AccountConfig.Percentage as ConfigPercentage,
								   COA_CNF_AccountConfig.RemainingValues,																		
									(CASE WHEN coa_cnf_account.coaaccountid not in (@ACCPaymentMethod, @TaxAccountID, @DiscountAccountID) then   --Accounts not Tax not PaymentMethods 
										Case when COA_CNF_AccountConfig.Price &gt; 0 then (COA_CNF_AccountConfig.Price * RR_DATA_REVENUE.Quantity) 
												else (ISNULL((((ABS(RR_DATA_REVENUE.RevenueAmount)) - ISNULL((select (ABS((sum(TaxAmount) * RR_DATA_REVENUE.Quantity)))
																										from data_saleitemTax
																										where saleitemid = RR_DATA_REVENUE.SaleitemID), 0)) * COA_CNF_AccountConfig.Percentage/100), 0))
										end 																		                                                                                                                                                                                              
									end)  as RevenueAmount,

								   COA_CNF_AccountConfig.Accountingtype,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
								   RR_CNF_RevenueRecognitionRule.Percentage,
								   RR_CNF_RevenueRecognitionRule.Days,
								   RR_DATA_REVENUE.AttributeIDs
		   
							from RR_DATA_REVENUE
									inner join rr_cnf_Product						ON ((RR_DATA_REVENUE.MATRIXCELLID = rr_cnf_Product.MATRIXCELLID) 
                                                      or (RR_DATA_REVENUE.MatrixSheetId = rr_cnf_Product.MatrixSheetId)
													  or (rr_cnf_product.Attributeid in (select top 1 Attributeid
																							from rr_cnf_product
																							where Attributeid in (select Value
																													from dbo.split((select rr.Attributeids
																																	from rr_data_revenue rr
																																	where rr.revenuerecognitiondataid = RR_DATA_REVENUE.revenuerecognitiondataid), '.')
																												   )
																					    )
															))
													  and rr_cnf_Product.Enabled = 1
									inner join RR_CNF_RevenueRecognitionRule		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_cnf_Product.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  
									INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
									INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
									INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 
									INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid

							where RR_CNF_RevenueRecognitionRule.Enabled = 1
							  and coa_cnf_account.Enabled = 1
							  and COA_CNF_AccountConfig.Enabled = 1
							  and TransactionType in (48, 52)
							  and ((coa_cnf_accountConfig.Siteid = RR_DATA_REVENUE.SiteId) or (coa_cnf_accountConfig.Siteid is null))
							  and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger IN (@OnMoneyCardCashOut)
							  and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
							  and COA_CNF_AccountConfig.RemainingValues &lt;&gt; 1
							  and RR_DATA_REVENUE.fcalcdate = @BatchDate
							  and RR_DATA_REVENUE.coaaccountid = @suspendid
						
					)p
					where RevenueAmount &lt;&gt; 0

				--Normal Transaction with Remaining Values
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[Saleitemid]
				   ,[MatrixCellid]
				   ,[MatrixCellCode]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays]
				   ,[AttributeIDs])
				   select *
				   from(
						select distinct coa_cnf_account.COAAccountId, 
								   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
								   RR_CNF_RevenueRecognitionRule.code,		   
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
								   COA_CNF_AccountConfig.COAAccountConfigId,
								   coa_cnf_account.COAAccountTypeId,
								   coa_cnf_account.Code as AccountCode,
								   RR_DATA_REVENUE.Transactionid as Transactionid,
								   RR_DATA_REVENUE.saleid as Saleid,
								   RR_DATA_REVENUE.SaleitemID as SaleitemID,
								   RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								   RR_DATA_REVENUE.MatrixcellCode as MatrixCode,
								   RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								   RR_DATA_REVENUE.Siteid as SiteID,
								   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								   RR_DATA_REVENUE.Workstationid as Workstationid,
								   RR_DATA_REVENUE.UserGroupid as UserGroupID,
								   RR_DATA_REVENUE.UserId as userID,
								   @BatchDate as BatchDate,
								   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
									    else DATA_Transaction.transactiondate
								   end as TransDate,
								   RR_DATA_REVENUE.Quantity as Quantity,
								   RR_DATA_REVENUE.GrossAmount as GrossAmount,
								   RR_DATA_REVENUE.NetAmount as NetAmount,
								   COA_CNF_AccountConfig.Price as ConfigPrice,
								   COA_CNF_AccountConfig.Percentage as ConfigPercentage,
								   COA_CNF_AccountConfig.RemainingValues,							 
								   ISNULL((RR_DATA_REVENUE.RevenueAmount - (select ISNULL(sum(revenueamount), 0)
								                            from RR_DATA_Revenue rr
												              where rr.saleitemid = RR_DATA_REVENUE.SaleitemID
												        and rr.COAAccountid not in (@SuspendID, @ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)
												 )
									), 0)
									as RevenueAmount,
								   case when TransactionType in (5, 17, 18, 20, 22, 30) and COA_CNF_AccountConfig.Accountingtype = 1 then 2
								        when TransactionType in (5, 17, 18, 20, 22, 30) and COA_CNF_AccountConfig.Accountingtype = 2 then 1
								        else COA_CNF_AccountConfig.Accountingtype
									end Accountingtype,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
								   RR_CNF_RevenueRecognitionRule.Percentage,
								   RR_CNF_RevenueRecognitionRule.Days,
								   RR_DATA_REVENUE.AttributeIDs

						from RR_DATA_REVENUE
								inner join rr_cnf_Product						ON ((RR_DATA_REVENUE.MATRIXCELLID = rr_cnf_Product.MATRIXCELLID) 
                                                      or (RR_DATA_REVENUE.MatrixSheetId = rr_cnf_Product.MatrixSheetId)
													  or (rr_cnf_product.Attributeid in (select top 1 Attributeid
																							from rr_cnf_product
																							where Attributeid in (select Value
																													from dbo.split((select rr.Attributeids
																																	from rr_data_revenue rr
																																	where rr.revenuerecognitiondataid = RR_DATA_REVENUE.revenuerecognitiondataid), '.')
																												   )
																					    )
															))
													  and rr_cnf_Product.Enabled = 1
								inner join RR_CNF_RevenueRecognitionRule		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_cnf_Product.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  
								INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
								INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
								INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 
								INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid

							where RR_CNF_RevenueRecognitionRule.Enabled = 1
							  and coa_cnf_account.Enabled = 1
							  and COA_CNF_AccountConfig.Enabled = 1
							  and TransactionType in (48, 52)
							  and ((coa_cnf_accountConfig.Siteid = RR_DATA_REVENUE.SiteId) or (coa_cnf_accountConfig.Siteid is null))
							  and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger IN (@OnMoneyCardCashOut)
							  and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
							  and COA_CNF_AccountConfig.RemainingValues = 1
							  and RR_DATA_REVENUE.fcalcdate = @BatchDate
							  and RR_DATA_REVENUE.coaaccountid = @suspendid
					)p
					where RevenueAmount &lt;&gt; 0

		
		exec otn_sp_RR_RevenueData_PaymentMethodTaxDiscounts @BatchDate, '48,52,', @OnMoneyCardCashOut, @RRTransDateType										

	end
	select '@OnExternalMoneyCardCashOut' as TriggerType, @BatchDate as RunDate
END
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_RR_RevenueData_SettleUpSuspendAccount]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_RR_RevenueData_SettleUpSuspendAccount
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE Procedure dbo.otn_sp_RR_RevenueData_SettleUpSuspendAccount
	@BatchDate Date,
	@RRTransDateType Integer
AS 
BEGIN
	Declare @SuspendRRRId Integer
	Declare @SuspendCOAAccountId Integer
	Declare @SuspendRRRCode varchar(10)
	Declare @SuspendRRCalcTypeTrigger Integer
	Declare @SuspendRRCalcTypeWhere Integer
	Declare @SuspendRRCalcTypeMethod Integer
	Declare @SuspendCOAAccountConfigId Integer
	Declare @SuspendCOAAccountTypeId Integer
	Declare @SuspendCOAAccountCode varchar(10)
	Declare @SuspendPercentage float
	Declare @SuspendDays Integer
	Declare @SuspendPrice float
	Declare @SuspendCOAAccount_Percentage Float
	Declare @SuspendRemainingValues Integer
	Declare @SuspendRRCOAAccountingType Integer

	Declare @TransactionID Integer
	Declare @TransactionType Integer
	Declare @FCalcDate date
	Declare @UsageID Integer
	Declare @TicketID Integer
	Declare @UsagePrice float
	Declare @AmountLeft float

	Declare @saleid Integer
	Declare @Siteid Integer
	Declare @OperatingAreaId Integer
	Declare @Workstationid Integer
	Declare @UserGroupid Integer
	Declare @UserId Integer
	Declare @Quantity Integer
	Declare @GrossAmount Float
	Declare @NetAmount Float
	Declare @RevenueAmount Float
	Declare @PaymentMethod Integer
	Declare @PaymentAmount Float
	Declare @TransDate Date
	Declare @Matrixcell Integer
	Declare @MatrixcellCode varchar(10)
	Declare @MatrixSheetId Integer 
	Declare @SaleitemID Integer
	Declare @PaymentDriver Integer

	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer
	Declare @UsageTrigger Integer = 2
	Declare @DepositTrigger Integer = 5
	Declare @MoneyRefund Integer = 6
	Declare @OnSaleTrigger Integer = 1
	Declare @OnAdvancePaymentTrigger Integer = 7
	Declare @SuspendRule Integer
	Declare @StartTime DateTime

	Set @StartTime = Getdate();
	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @SuspendRule = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleid
	from coa_cnf_account
		INNER JOIN COA_CNF_AccountType				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
		INNER JOIN COA_CNF_AccountConfig			on COA_CNF_AccountConfig.COAAccountId = coa_cnf_account.COAAccountId
		INNER JOIN RR_CNF_RevenueRecognitionRule	on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId
	where coa_cnf_account.COAAccountID = @SuspendID

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1

	select @SuspendRRRId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
		   @SuspendRRRCode = RR_CNF_RevenueRecognitionRule.code,
		   @SuspendRRCalcTypeTrigger = RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
		   @SuspendRRCalcTypeWhere = RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
		   @SuspendRRCalcTypeMethod = RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
		   @SuspendCOAAccountConfigId = COA_CNF_AccountConfig.COAAccountConfigId,
		   @SuspendCOAAccountTypeId = COA_CNF_AccountType.COAAccountTypeId,
		   @SuspendCOAAccountId = coa_cnf_account.COAAccountId,
		   @SuspendPercentage = RR_CNF_RevenueRecognitionRule.Percentage,
		   @SuspendDays = RR_CNF_RevenueRecognitionRule.Days,
		   @SuspendPrice = COA_CNF_AccountConfig.Price,
		   @SuspendCOAAccount_Percentage = COA_CNF_AccountConfig.Percentage,
		   @SuspendRemainingValues = COA_CNF_AccountConfig.RemainingValues,
		   @SuspendCOAAccountCode = coa_cnf_account.Code,
		   @SuspendRRCOAAccountingType = COA_CNF_AccountConfig.AccountingType

	from coa_cnf_account
		INNER JOIN COA_CNF_AccountType				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
		INNER JOIN COA_CNF_AccountConfig			on COA_CNF_AccountConfig.COAAccountId = coa_cnf_account.COAAccountId
		INNER JOIN RR_CNF_RevenueRecognitionRule	on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId
	where coa_cnf_account.COAAccountID = @SuspendID
	  and RR_CNF_RevenueRecognitionRule.enabled = 1
	  and COA_CNF_AccountConfig.enabled = 1


	update rr_data_revenue
	   set revenueamount = abs(revenueamount)		   
	 where FCalcDate = @BatchDate
	   and coaaccountid = @SuspendID

	BEGIN
		
			INSERT INTO [dbo].[RR_DATA_Revenue]
					   ([COAAccountId]
					   ,[RevenueRecognitionRuleId]
					   ,[RRCode]
					   ,[RRCalcTypeWhere]
					   ,[RRCalcTypeMethod]
					   ,[COAAccountConfigId]
					   ,[COAAccountType]
					   ,[COAAccountCode]
					   ,[TransactionId]
					   ,[SaleId]
					   ,[SiteId]
					   ,[OperatingAreaId]
					   ,[WorkstationId]
					   ,[UserGroupId]
					   ,[UserId]
					   ,[FCalcDate]
					   ,[FRevenueDate]
					   ,[Quantity]
					   ,[GrossAmount]
					   ,[NetAmount]
					   ,[Price]
					   ,[Percentage]
					   ,[RemaningValues]
					   ,[RevenueAmount]
					   ,[AccountingType]
					   ,[RRCalcTypeTrigger]
					   ,[RRPercentage]
					   ,[RRDays]
					   ,[AttributeIDs])
				select SuspendCOAAccountId,
					   SuspendRRRId,
					   SuspendRRRCode,
					   SuspendRRCalcTypeWhere,
					   SuspendRRCalcTypeMethod,
					   SuspendCOAAccountConfigId,
					   SuspendCOAAccountTypeId,
					   SuspendCOAAccountCode,
					   Transactionid,
					   saleid,
					   Siteid,
					   OperatingAreaId,
					   Workstationid,
					   UserGroupid,
					   UserId,
					   BatchDate,
					   TransDate,
					   0,
					   GrossAmount,
					   NetAmount,
					   SuspendPrice,
					   percentage,
					   RemainingValues,
					   sum(ABS(RevenueAmount)),
					   case when accountingtype = 1 then 2
					        else 1
						end Accountingtype,
					   rrtrigger,
					   percentage2,
					   rrdays,
					   AttributeIDs
				from (
				select distinct @SuspendCOAAccountId SuspendCOAAccountId,
					   @SuspendRRRId SuspendRRRId,
					   @SuspendRRRCode SuspendRRRCode,
					   @SuspendRRCalcTypeWhere SuspendRRCalcTypeWhere,
					   @SuspendRRCalcTypeMethod SuspendRRCalcTypeMethod,
					   @SuspendCOAAccountConfigId SuspendCOAAccountConfigId,
					   @SuspendCOAAccountTypeId SuspendCOAAccountTypeId,
					   @SuspendCOAAccountCode SuspendCOAAccountCode,
					   RR_DATA_Revenue.Transactionid Transactionid,
					   RR_DATA_Revenue.saleid saleid,
					   RR_DATA_Revenue.SaleItemid saleitemid,
					   RR_DATA_Revenue.Matrixcellid Matrixcell,
					   RR_DATA_Revenue.MatrixcellCode MatrixcellCode,
					   RR_DATA_Revenue.MatrixSheetId MatrixSheetId,
					   RR_DATA_Revenue.Siteid Siteid,
					   RR_DATA_Revenue.OperatingAreaId OperatingAreaId,
					   RR_DATA_Revenue.Workstationid Workstationid,
					   @UserGroupid UserGroupid,
					   RR_DATA_Revenue.UserId UserId,
					   @BatchDate BatchDate,
						case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
							else DATA_Transaction.transactiondate
						end as TransDate,
					   0 GrossAmount,
					   0 NetAmount,
					   @SuspendPrice SuspendPrice,
					   @SuspendCOAAccount_Percentage percentage,
					   @SuspendRemainingValues RemainingValues,
					   case when RR_DATA_Revenue.RRCalcTypeTrigger = 5 and data_transaction.transactiontype &lt;&gt; 12 then 0
					        else RevenueAmount
						end RevenueAmount, 
					   ISNULL((select top 1 AccountingType 
								  from rr_data_revenue tt
								  where tt.COAAccountId = @SuspendID
									and tt.transactionid = rr_data_revenue.transactionid
									and tt.saleitemid = rr_data_revenue.saleitemid),
								(select top 1 AccountingType 
								  from rr_data_revenue tt
								  where tt.COAAccountId = @SuspendID
									and tt.transactionid = rr_data_revenue.transactionid)
								)	 as Accountingtype,
					   @SuspendRRCalcTypeTrigger rrtrigger,
					   @SuspendPercentage percentage2,
					   @SuspendDays rrdays,
					   RR_DATA_Revenue.AttributeIDs
	  
				from RR_DATA_Revenue
						INNER JOIN data_transaction					on data_transaction.transactionid = rr_data_revenue.transactionid
						LEFT JOIN DATA_SaleItem					on data_saleitem.saleid = data_transaction.saleid
				   where TransactionType in (5, 7, 8, 9, 10, 12, 13, 14, 18, 20, 22, 16, 30, 31, 34, 42, 43, 48, 49, 52) 
				     and rr_data_revenue.fcalcdate = @BatchDate
					 and rr_data_revenue.RevenueRecognitionRuleId &lt;&gt; @SuspendRRRId
					 and rr_data_revenue.coaaccountid not in (@SuspendID, @ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)
				)p	
				
				group by   SuspendCOAAccountId,
						   SuspendRRRId,
						   SuspendRRRCode,
						   SuspendRRCalcTypeWhere,
						   SuspendRRCalcTypeMethod,
						   SuspendCOAAccountConfigId,
						   SuspendCOAAccountTypeId,
						   SuspendCOAAccountCode,
						   Transactionid,
						   saleid,
						   Siteid,
						   OperatingAreaId,
						   Workstationid,
						   UserGroupid,
						   UserId,
						   BatchDate,
						   TransDate,
						   GrossAmount,
						   NetAmount,
						   SuspendPrice,
						   percentage,
						   RemainingValues,
						   accountingtype,
						   rrtrigger,
						   percentage2,
					       rrdays,
						   AttributeIDs									  																			
	end
END
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_RR_RevenueData_batchJob]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_RR_RevenueData_batchJob
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE Procedure dbo.otn_sp_RR_RevenueData_batchJob	 
	@BatchDate Date
AS 
BEGIN
	Declare @RRTransDateType Integer


	Declare @SuspendRRRId Integer
	Declare @SuspendCOAAccountId Integer
	Declare @SuspendRRRCode varchar(10)
	Declare @SuspendRRCalcTypeTrigger Integer
	Declare @SuspendRRCalcTypeWhere Integer
	Declare @SuspendRRCalcTypeMethod Integer
	Declare @SuspendCOAAccountConfigId Integer
	Declare @SuspendCOAAccountTypeId Integer
	Declare @SuspendCOAAccountCode varchar(10)
	Declare @SuspendPercentage float
	Declare @SuspendDays Integer
	Declare @SuspendPrice float
	Declare @SuspendCOAAccount_Percentage Float
	Declare @SuspendRemainingValues Integer
	Declare @SuspendRRCOAAccountingType Integer
	Declare @SuspendAccountingType Integer

	Declare @PaymentRRRId Integer
	Declare @PaymentCOAAccountId Integer
	Declare @PaymentRRRCode varchar(10)
	Declare @PaymentRRCalcTypeTrigger Integer
	Declare @PaymentRRCalcTypeWhere Integer
	Declare @PaymentRRCalcTypeMethod Integer
	Declare @PaymentCOAAccountConfigId Integer
	Declare @PaymentCOAAccountTypeId Integer
	Declare @PaymentCOAAccountCode varchar(10)
	Declare @PaymentPercentage float
	Declare @PaymentDays Integer
	Declare @PaymentPrice float
	Declare @PaymentCOAAccount_Percentage Float
	Declare @PaymentRemainingValues Integer
	Declare @PaymentRRCOAAccountingType Integer
	Declare @PaymentAccountingType Integer


	Declare @TaxRRRId Integer
	Declare @TaxCOAAccountId Integer
	Declare @TaxRRRCode varchar(10)
	Declare @TaxRRCalcTypeTrigger Integer
	Declare @TaxRRCalcTypeWhere Integer
	Declare @TaxRRCalcTypeMethod Integer
	Declare @TaxCOAAccountConfigId Integer
	Declare @TaxCOAAccountTypeId Integer
	Declare @TaxCOAAccountCode varchar(10)
	Declare @TaxPercentage float
	Declare @TaxDays Integer
	Declare @TaxPrice float
	Declare @TaxCOAAccount_Percentage Float
	Declare @TaxRemainingValues Integer
	Declare @TaxRRCOAAccountingType Integer
	Declare @TaxAccountingType Integer


	Declare @DiscountRRRId Integer
	Declare @DiscountCOAAccountId Integer
	Declare @DiscountRRRCode varchar(10)
	Declare @DiscountRRCalcTypeTrigger Integer
	Declare @DiscountRRCalcTypeWhere Integer
	Declare @DiscountRRCalcTypeMethod Integer
	Declare @DiscountCOAAccountConfigId Integer
	Declare @DiscountCOAAccountTypeId Integer
	Declare @DiscountCOAAccountCode varchar(10)
	Declare @DiscountPercentage float
	Declare @DiscountDays Integer
	Declare @DiscountPrice float
	Declare @DiscountCOAAccount_Percentage Float
	Declare @DiscountRemainingValues Integer
	Declare @DiscountRRCOAAccountingType Integer
	Declare @DiscountAccountingType Integer

	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer

	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1

	delete from rr_data_revenue
	where fcalcdate = @BatchDate 


	select @RRTransDateType = RRTransDateType
      from cnf_system

--Begin Move Transactions to Suspend Account
	select TOP 1 @SuspendRRRId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
			@SuspendRRRCode = RR_CNF_RevenueRecognitionRule.code,
			@SuspendRRCalcTypeTrigger = RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
			@SuspendRRCalcTypeWhere = RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
			@SuspendRRCalcTypeMethod = RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
			@SuspendCOAAccountConfigId = COA_CNF_AccountConfig.COAAccountConfigId,
			@SuspendCOAAccountTypeId = COA_CNF_AccountType.COAAccountTypeId,
			@SuspendCOAAccountId = coa_cnf_account.COAAccountId,
			@SuspendPercentage = RR_CNF_RevenueRecognitionRule.Percentage,
			@SuspendDays = RR_CNF_RevenueRecognitionRule.Days,
			@SuspendPrice = COA_CNF_AccountConfig.Price,
			@SuspendCOAAccount_Percentage = COA_CNF_AccountConfig.Percentage,
			@SuspendRemainingValues = COA_CNF_AccountConfig.RemainingValues,
			@SuspendCOAAccountCode = coa_cnf_account.Code,
			@SuspendRRCOAAccountingType = COA_CNF_AccountConfig.AccountingType
	from coa_cnf_account
		INNER JOIN COA_CNF_AccountType				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
		INNER JOIN COA_CNF_AccountConfig			on COA_CNF_AccountConfig.COAAccountId = coa_cnf_account.COAAccountId
		INNER JOIN RR_CNF_RevenueRecognitionRule	on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId
	where coa_cnf_account.COAAccountID = @SuspendID
	 order by RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId

	select TOP 1 @PaymentRRRId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
			@PaymentRRRCode = RR_CNF_RevenueRecognitionRule.code,
			@PaymentRRCalcTypeTrigger = RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
			@PaymentRRCalcTypeWhere = RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
			@PaymentRRCalcTypeMethod = RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
			@PaymentCOAAccountConfigId = COA_CNF_AccountConfig.COAAccountConfigId,
			@PaymentCOAAccountTypeId = COA_CNF_AccountType.COAAccountTypeId,
			@PaymentCOAAccountId = coa_cnf_account.COAAccountId,
			@PaymentPercentage = RR_CNF_RevenueRecognitionRule.Percentage,
			@PaymentDays = RR_CNF_RevenueRecognitionRule.Days,
			@PaymentPrice = COA_CNF_AccountConfig.Price,
			@PaymentCOAAccount_Percentage = COA_CNF_AccountConfig.Percentage,
			@PaymentRemainingValues = COA_CNF_AccountConfig.RemainingValues,
			@PaymentCOAAccountCode = coa_cnf_account.Code,
			@PaymentRRCOAAccountingType = COA_CNF_AccountConfig.AccountingType
	from coa_cnf_account
		INNER JOIN COA_CNF_AccountType				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
		INNER JOIN COA_CNF_AccountConfig			on COA_CNF_AccountConfig.COAAccountId = coa_cnf_account.COAAccountId
		INNER JOIN RR_CNF_RevenueRecognitionRule	on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId
	where coa_cnf_account.COAAccountID = @ACCPaymentMethod
	 order by RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId

	select TOP 1 @TaxRRRId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
			@TaxRRRCode = RR_CNF_RevenueRecognitionRule.code,
			@TaxRRCalcTypeTrigger = RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
			@TaxRRCalcTypeWhere = RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
			@TaxRRCalcTypeMethod = RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
			@TaxCOAAccountConfigId = COA_CNF_AccountConfig.COAAccountConfigId,
			@TaxCOAAccountTypeId = COA_CNF_AccountType.COAAccountTypeId,
			@TaxCOAAccountId = coa_cnf_account.COAAccountId,
			@TaxPercentage = RR_CNF_RevenueRecognitionRule.Percentage,
			@TaxDays = RR_CNF_RevenueRecognitionRule.Days,
			@TaxPrice = COA_CNF_AccountConfig.Price,
			@TaxCOAAccount_Percentage = COA_CNF_AccountConfig.Percentage,
			@TaxRemainingValues = COA_CNF_AccountConfig.RemainingValues,
			@TaxCOAAccountCode = coa_cnf_account.Code,
			@TaxRRCOAAccountingType = COA_CNF_AccountConfig.AccountingType
	from coa_cnf_account
		INNER JOIN COA_CNF_AccountType				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
		INNER JOIN COA_CNF_AccountConfig			on COA_CNF_AccountConfig.COAAccountId = coa_cnf_account.COAAccountId
		INNER JOIN RR_CNF_RevenueRecognitionRule	on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId
	where coa_cnf_account.COAAccountID = @TaxAccountID
	 order by RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId

	select TOP 1 @DiscountRRRId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
			@DiscountRRRCode = RR_CNF_RevenueRecognitionRule.code,
			@DiscountRRCalcTypeTrigger = RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
			@DiscountRRCalcTypeWhere = RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
			@DiscountRRCalcTypeMethod = RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
			@DiscountCOAAccountConfigId = COA_CNF_AccountConfig.COAAccountConfigId,
			@DiscountCOAAccountTypeId = COA_CNF_AccountType.COAAccountTypeId,
			@DiscountCOAAccountId = coa_cnf_account.COAAccountId,
			@DiscountPercentage = RR_CNF_RevenueRecognitionRule.Percentage,
			@DiscountDays = RR_CNF_RevenueRecognitionRule.Days,
			@DiscountPrice = COA_CNF_AccountConfig.Price,
			@DiscountCOAAccount_Percentage = COA_CNF_AccountConfig.Percentage,
			@DiscountRemainingValues = COA_CNF_AccountConfig.RemainingValues,
			@DiscountCOAAccountCode = coa_cnf_account.Code,
			@DiscountRRCOAAccountingType = COA_CNF_AccountConfig.AccountingType
	from coa_cnf_account
		INNER JOIN COA_CNF_AccountType				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
		INNER JOIN COA_CNF_AccountConfig			on COA_CNF_AccountConfig.COAAccountId = coa_cnf_account.COAAccountId
		INNER JOIN RR_CNF_RevenueRecognitionRule	on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId
	where coa_cnf_account.COAAccountID = @DiscountAccountID
	 order by RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId

INSERT INTO [dbo].[RR_DATA_Revenue]
				([COAAccountId]
				,[RevenueRecognitionRuleId]
				,[RRCode]
				,[RRCalcTypeWhere]
				,[RRCalcTypeMethod]
				,[COAAccountConfigId]
				,[COAAccountType]
				,[COAAccountCode]
				,[TransactionId]
				,[SaleId]
				,[SaleItemId]
				,[MatrixCellId]
				,[MatrixCellCode]
				,[MatrixSheetID]
				,[SiteId]
				,[OperatingAreaId]
				,[WorkstationId]
				,[UserGroupId]
				,[UserId]
				,[FCalcDate]
				,[FRevenueDate]
				,[Quantity]
				,[UnitAmount]
				,[GrossAmount]
				,[NetAmount]
				,[Price]
				,[Percentage]
				,[RemaningValues]
				,[RevenueAmount]
				,[AccountingType]
				,[RRCalcTypeTrigger]
				,[RRPercentage]
				,[RRDays]
				,[AttributeIDS])
		select @SuspendCOAAccountId,
				@SuspendRRRId,
				@SuspendRRRCode,
				@SuspendRRCalcTypeWhere,
				@SuspendRRCalcTypeMethod,
				@SuspendCOAAccountConfigId,
				@SuspendCOAAccountTypeId,
				@SuspendCOAAccountCode,
				data_transaction.transactionid, 
				data_transaction.saleid,
				DATA_TransactionItem.saleitemid,
				DATA_SaleItem.Matrixcellid,
				CNF_MatrixCell.Code,
				CNF_MatrixCell.MatrixSheetid,
				data_transaction.Siteid,
				data_transaction.OperatingAreaId,
				data_transaction.Workstationid,
				data_transaction.UserGroupid,
				data_transaction.UserId,
				@BatchDate,
				CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
				     else data_transaction.TransactionDate
				end TransactionDate,
				Coalesce(DATA_TransactionItem.Quantity, 1),
				DATA_SaleItem.UnitPrice,
				case when isnull(DATA_TransactionItem.TotalAmount, 0) &lt;&gt; 0 then DATA_TransactionItem.TotalAmount
					when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
					else DATA_Sale.TotalAmount
				end,
				case when isnull((DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes)
					when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
					else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
				end as NetAmount,
				@SuspendPrice,
				@SuspendCOAAccount_Percentage,
				@SuspendRemainingValues,
				case    when (data_saleitem.ProductTaxType &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice ) * DATA_SaleItem.Quantity)
						when (data_saleitem.ProductTaxType = 1) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice - DATA_SaleItem.unittaxes) * DATA_SaleItem.Quantity)
						when (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 then 0				
						when isnull((data_transaction.TotalAmount), 0) &lt;&gt; 0 then data_transaction.TotalAmount
						when isnull((DATA_Sale.TotalAmount), 0) &lt;&gt; 0 then DATA_Sale.TotalAmount
						else (data_transaction.Revenue)
				end,
				case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
						when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
						when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 1
						when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 2
						else @SuspendRRCOAAccountingType
				end Accountingtype,
				@SuspendRRCalcTypeTrigger,
				@SuspendPercentage,
				@SuspendDays,
				CNF_AttributeSet.Attributeids
	   
		from DATA_Sale
			inner join data_transaction			on data_transaction.TransactionId = DATA_Sale.PaidTransactionId
			left join DATA_TransactionItem		on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
			left join DATA_SaleItem			    on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
			left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
			left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

		where DATA_Sale.Paid = 1
			and data_transaction.transactiontype in (14)
			and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
			   OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
			and data_transaction.transactionid in (select transactionid
													from data_payment
													where PaymentStatus = 1
													and PaymentAmount &lt;&gt; 0
												)

INSERT INTO [dbo].[RR_DATA_Revenue]
				([COAAccountId]
				,[RevenueRecognitionRuleId]
				,[RRCode]
				,[RRCalcTypeWhere]
				,[RRCalcTypeMethod]
				,[COAAccountConfigId]
				,[COAAccountType]
				,[COAAccountCode]
				,[TransactionId]
				,[SaleId]
				,[SaleItemId]
				,[MatrixCellId]
				,[MatrixCellCode]
				,[MatrixSheetID]
				,[SiteId]
				,[OperatingAreaId]
				,[WorkstationId]
				,[UserGroupId]
				,[UserId]
				,[FCalcDate]
				,[FRevenueDate]
				,[Quantity]
				,[UnitAmount]
				,[GrossAmount]
				,[NetAmount]
				,[Price]
				,[Percentage]
				,[RemaningValues]
				,[RevenueAmount]
				,[AccountingType]
				,[RRCalcTypeTrigger]
				,[RRPercentage]
				,[RRDays]
				,[AttributeIDS])
		select @SuspendCOAAccountId,
				@SuspendRRRId,
				@SuspendRRRCode,
				@SuspendRRCalcTypeWhere,
				@SuspendRRCalcTypeMethod,
				@SuspendCOAAccountConfigId,
				@SuspendCOAAccountTypeId,
				@SuspendCOAAccountCode,
				data_transaction.transactionid, 
				data_transaction.saleid,
				DATA_TransactionItem.saleitemid,
				DATA_SaleItem.Matrixcellid,
				CNF_MatrixCell.Code,
				CNF_MatrixCell.MatrixSheetid,
				data_transaction.Siteid,
				data_transaction.OperatingAreaId,
				data_transaction.Workstationid,
				data_transaction.UserGroupid,
				data_transaction.UserId,
				@BatchDate,
				CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
				     else data_transaction.TransactionDate
				end TransactionDate,
				Coalesce(DATA_TransactionItem.Quantity, 1),
				DATA_SaleItem.UnitPrice,
				case when isnull(DATA_TransactionItem.TotalAmount, 0) &lt;&gt; 0 then DATA_TransactionItem.TotalAmount
					when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
					else DATA_Sale.TotalAmount
				end,
				case when isnull((DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes)
					when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
					else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
				end as NetAmount,
				@SuspendPrice,
				@SuspendCOAAccount_Percentage,
				@SuspendRemainingValues,
				DATA_SaleItem.UnitRecharge * data_saleitem.Quantity,
				case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
						when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
						when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 1
						when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 2
						else @SuspendRRCOAAccountingType
				end Accountingtype,
				@SuspendRRCalcTypeTrigger,
				@SuspendPercentage,
				@SuspendDays,
				CNF_AttributeSet.Attributeids
	   
		from DATA_Sale
			inner join data_transaction			on data_transaction.TransactionId = DATA_Sale.PaidTransactionId
			left join DATA_TransactionItem		on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
			left join DATA_SaleItem			    on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
			left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
			left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

		where DATA_Sale.Paid = 1
			and data_transaction.transactiontype in (14, 39)
			and DATA_SaleItem.UnitRecharge &lt;&gt; 0
			and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
			   OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
			and data_transaction.transactionid in (select transactionid
													from data_payment
													where PaymentStatus = 1
													and PaymentAmount &lt;&gt; 0
												)

	INSERT INTO [dbo].[RR_DATA_Revenue]
				([COAAccountId]
				,[RevenueRecognitionRuleId]
				,[RRCode]
				,[RRCalcTypeWhere]
				,[RRCalcTypeMethod]
				,[COAAccountConfigId]
				,[COAAccountType]
				,[COAAccountCode]
				,[TransactionId]
				,[SaleId]
				,[SaleItemId]
				,[MatrixCellId]
				,[MatrixCellCode]
				,[MatrixSheetID]
				,[SiteId]
				,[OperatingAreaId]
				,[WorkstationId]
				,[UserGroupId]
				,[UserId]
				,[FCalcDate]
				,[FRevenueDate]
				,[Quantity]
				,[UnitAmount]
				,[GrossAmount]
				,[NetAmount]
				,[Price]
				,[Percentage]
				,[RemaningValues]
				,[RevenueAmount]
				,[AccountingType]
				,[RRCalcTypeTrigger]
				,[RRPercentage]
				,[RRDays]
				,[AttributeIDS])
		select @SuspendCOAAccountId,
				@SuspendRRRId,
				@SuspendRRRCode,
				@SuspendRRCalcTypeWhere,
				@SuspendRRCalcTypeMethod,
				@SuspendCOAAccountConfigId,
				@SuspendCOAAccountTypeId,
				@SuspendCOAAccountCode,
				data_transaction.transactionid, 
				data_transaction.saleid,
				DATA_TransactionItem.saleitemid,
				DATA_SaleItem.Matrixcellid,
				CNF_MatrixCell.Code,
				CNF_MatrixCell.MatrixSheetid,
				data_transaction.Siteid,
				data_transaction.OperatingAreaId,
				data_transaction.Workstationid,
				data_transaction.UserGroupid,
				data_transaction.UserId,
				@BatchDate,
				CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
				     else data_transaction.TransactionDate
				end TransactionDate,
				Coalesce(DATA_TransactionItem.Quantity, 1),
				DATA_SaleItem.UnitPrice,
				case when isnull(DATA_TransactionItem.TotalAmount, 0) &lt;&gt; 0 then DATA_TransactionItem.TotalAmount
					when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
					else DATA_Sale.TotalAmount
				end,
				case when isnull((DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes)
					when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
					else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
				end as NetAmount,
				@SuspendPrice,
				@SuspendCOAAccount_Percentage,
				@SuspendRemainingValues,
				case    when (data_saleitem.ProductTaxType &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) 
				                  and (isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0) 
								       and (((select discountamount from data_saleitemrule where saleitemid = DATA_SaleItem.saleitemid) &gt; 0) and (data_transaction.transactiontype in (7, 20, 22)))							
                            then ((DATA_SaleItem.UnitRawPrice + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)

				        when (data_saleitem.ProductTaxType &lt;&gt; 1) and (data_transaction.transactiontype in (18, 20, 22)) and (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitPrice  + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)
						when (data_saleitem.ProductTaxType = 1) and (data_transaction.transactiontype in (18, 20, 22)) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitPrice - DATA_SaleItem.unittaxes + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)

				        when (data_saleitem.ProductTaxType &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice  + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)
						when (data_saleitem.ProductTaxType = 1) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice - DATA_SaleItem.unittaxes + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)

						when (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 and data_saleitem.unitRecharge = 0 then 0
						when (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 and data_saleitem.unitRecharge &lt;&gt; 0 then data_saleitem.unitRecharge
						when isnull((data_transaction.TotalAmount), 0) &lt;&gt; 0 then data_transaction.TotalAmount
						when isnull((DATA_Sale.TotalAmount), 0) &lt;&gt; 0 then DATA_Sale.TotalAmount
						else (data_transaction.Revenue)
				end,
				case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
						when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
						when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 1
						when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 2
						else @SuspendRRCOAAccountingType
				end Accountingtype,
				@SuspendRRCalcTypeTrigger,
				@SuspendPercentage,
				@SuspendDays,
				CNF_AttributeSet.Attributeids
	   
		from DATA_Sale
			inner join data_transaction			on data_transaction.TransactionId = ISNULL(data_sale.voidtransactionid, DATA_Sale.PaidTransactionId)
			left join DATA_TransactionItem		on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
			left join DATA_SaleItem			    on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
			left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
			left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

		where DATA_Sale.Paid = 1
			and data_transaction.transactiontype not in (8, 10, 12, 14, 16, 42, 43, 31, 39, 48, 49, 52, 46, 47)
			and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
			   OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
			and data_transaction.transactionid in (select transactionid
													from data_payment
													where PaymentStatus = 1
													and PaymentAmount &lt;&gt; 0
												)

	INSERT INTO [dbo].[RR_DATA_Revenue]
				([COAAccountId]
				,[RevenueRecognitionRuleId]
				,[RRCode]
				,[RRCalcTypeWhere]
				,[RRCalcTypeMethod]
				,[COAAccountConfigId]
				,[COAAccountType]
				,[COAAccountCode]
				,[TransactionId]
				,[SaleId]
				,[SaleItemId]
				,[MatrixCellId]
				,[MatrixCellCode]
				,[MatrixSheetID]
				,[SiteId]
				,[OperatingAreaId]
				,[WorkstationId]
				,[UserGroupId]
				,[UserId]
				,[FCalcDate]
				,[FRevenueDate]
				,[Quantity]
				,[UnitAmount]
				,[GrossAmount]
				,[NetAmount]
				,[Price]
				,[Percentage]
				,[RemaningValues]
				,[RevenueAmount]
				,[AccountingType]
				,[RRCalcTypeTrigger]
				,[RRPercentage]
				,[RRDays]
				,[AttributeIDS])
		select @SuspendCOAAccountId,
				@SuspendRRRId,
				@SuspendRRRCode,
				@SuspendRRCalcTypeWhere,
				@SuspendRRCalcTypeMethod,
				@SuspendCOAAccountConfigId,
				@SuspendCOAAccountTypeId,
				@SuspendCOAAccountCode,
				data_transaction.transactionid, 
				data_transaction.saleid,
				DATA_SaleItem.saleitemid,
				DATA_SaleItem.Matrixcellid,
				CNF_MatrixCell.Code,
				CNF_MatrixCell.MatrixSheetid,
				data_transaction.Siteid,
				data_transaction.OperatingAreaId,
				data_transaction.Workstationid,
				data_transaction.UserGroupid,
				data_transaction.UserId,
				@BatchDate,
				CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
				     else data_transaction.TransactionDate
				end TransactionDate,
				Coalesce(DATA_SaleItem.Quantity, 1),
				DATA_SaleItem.UnitPrice,
				case when isnull(DATA_SaleItem.TotalAmount, 0) &lt;&gt; 0 then DATA_SaleItem.TotalAmount
					when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
					else DATA_Sale.TotalAmount
				end,
				case when isnull((DATA_SaleItem.TotalAmount - DATA_SaleItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_SaleItem.TotalAmount - DATA_SaleItem.TotalTaxes)
					when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
					else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
				end as NetAmount,
				@SuspendPrice,
				@SuspendCOAAccount_Percentage,
				@SuspendRemainingValues,
				case    when (data_saleitem.ProductTaxType &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) 
				                  and (isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0) 
								       and (((select discountamount from data_saleitemrule where saleitemid = DATA_SaleItem.saleitemid) &gt; 0) and (data_transaction.transactiontype in (7, 20, 22)))							
                            then ((DATA_SaleItem.UnitRawPrice + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)


				        when (data_saleitem.ProductTaxType &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice  + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)
						when (data_saleitem.ProductTaxType = 1) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice - DATA_SaleItem.unittaxes + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)
						when (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 then 0
						when (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 and data_saleitem.unitRecharge &lt;&gt; 0 then data_saleitem.unitRecharge
						when isnull((data_transaction.TotalAmount), 0) &lt;&gt; 0 then data_transaction.TotalAmount
						when isnull((DATA_Sale.TotalAmount), 0) &lt;&gt; 0 then DATA_Sale.TotalAmount
						else (data_transaction.Revenue)
				end,
				case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
						when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
						when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 1
						when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 2
						else @SuspendRRCOAAccountingType
				end Accountingtype,
				@SuspendRRCalcTypeTrigger,
				@SuspendPercentage,
				@SuspendDays,
				CNF_AttributeSet.Attributeids
	   
		from DATA_Sale
			inner join data_transaction			on data_transaction.saleid = data_sale.saleid
			left join DATA_SaleItem			    on DATA_SaleItem.saleid = DATA_Transaction.saleid
			left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
			left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

		where DATA_Sale.Paid = 1
			and data_transaction.transactiontype in (46, 47)
			and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
			   OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
			and data_transaction.transactionid in (select transactionid
													from data_payment
													where PaymentStatus = 1
													and PaymentAmount &lt;&gt; 0
												)


	INSERT INTO [dbo].[RR_DATA_Revenue]
				([COAAccountId]
				,[RevenueRecognitionRuleId]
				,[RRCode]
				,[RRCalcTypeWhere]
				,[RRCalcTypeMethod]
				,[COAAccountConfigId]
				,[COAAccountType]
				,[COAAccountCode]
				,[TransactionId]
				,[SaleId]
				,[SaleItemId]
				,[MatrixCellId]
				,[MatrixCellCode]
				,[MatrixSheetID]
				,[SiteId]
				,[OperatingAreaId]
				,[WorkstationId]
				,[UserGroupId]
				,[UserId]
				,[FCalcDate]
				,[FRevenueDate]
				,[Quantity]
				,[UnitAmount]
				,[GrossAmount]
				,[NetAmount]
				,[Price]
				,[Percentage]
				,[RemaningValues]
				,[RevenueAmount]
				,[AccountingType]
				,[RRCalcTypeTrigger]
				,[RRPercentage]
				,[RRDays]
				,[AttributeIDS])
		select @SuspendCOAAccountId,
				@SuspendRRRId,
				@SuspendRRRCode,
				@SuspendRRCalcTypeWhere,
				@SuspendRRCalcTypeMethod,
				@SuspendCOAAccountConfigId,
				@SuspendCOAAccountTypeId,
				@SuspendCOAAccountCode,
				data_transaction.transactionid, 
				data_transaction.saleid,
				DATA_TransactionItem.saleitemid,
				DATA_SaleItem.Matrixcellid,
				CNF_MatrixCell.Code,
				CNF_MatrixCell.MatrixSheetid,
				data_transaction.Siteid,
				data_transaction.OperatingAreaId,
				data_transaction.Workstationid,
				data_transaction.UserGroupid,
				data_transaction.UserId,
				@BatchDate,
				CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
				     else data_transaction.TransactionDate
				end TransactionDate,
				Coalesce(DATA_TransactionItem.Quantity, 1),
				DATA_SaleItem.UnitPrice,
				case when isnull(DATA_TransactionItem.TotalAmount, 0) &lt;&gt; 0 then DATA_TransactionItem.TotalAmount
					when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
					else DATA_Sale.TotalAmount
				end,
				case when isnull((DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes)
					when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
					else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
				end as NetAmount,
				@SuspendPrice,
				@SuspendCOAAccount_Percentage,
				@SuspendRemainingValues,
				DATA_SaleItem.Unitrecharge,
				case    when TransactionType in (5, 17, 8, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
						when TransactionType in (5, 17, 8, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
						when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 2
						when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 1
						else @SuspendRRCOAAccountingType
				end Accountingtype,
				@SuspendRRCalcTypeTrigger,
				@SuspendPercentage,
				@SuspendDays,
				CNF_AttributeSet.Attributeids
	   
		from DATA_Sale
			inner join data_transaction			on data_transaction.TransactionId = ISNULL(data_sale.voidtransactionid, DATA_Sale.PaidTransactionId)
			left join DATA_TransactionItem		on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
			left join DATA_SaleItem			    on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
			left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
			left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

		where DATA_Sale.Paid = 1
			and data_transaction.transactiontype in (10, 42, 43, 49)
			and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
			   OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
			and data_transaction.transactionid in (select transactionid
													from data_payment
													where PaymentStatus = 1
													and PaymentAmount &lt;&gt; 0
												)
			
INSERT INTO [dbo].[RR_DATA_Revenue]
				([COAAccountId]
				,[RevenueRecognitionRuleId]
				,[RRCode]
				,[RRCalcTypeWhere]
				,[RRCalcTypeMethod]
				,[COAAccountConfigId]
				,[COAAccountType]
				,[COAAccountCode]
				,[TransactionId]
				,[SaleId]
				,[SaleItemId]
				,[MatrixCellId]
				,[MatrixCellCode]
				,[MatrixSheetID]
				,[SiteId]
				,[OperatingAreaId]
				,[WorkstationId]
				,[UserGroupId]
				,[UserId]
				,[FCalcDate]
				,[FRevenueDate]
				,[Quantity]
				,[UnitAmount]
				,[GrossAmount]
				,[NetAmount]
				,[Price]
				,[Percentage]
				,[RemaningValues]
				,[RevenueAmount]
				,[AccountingType]
				,[RRCalcTypeTrigger]
				,[RRPercentage]
				,[RRDays]
				,[AttributeIDS])
		select @SuspendCOAAccountId,
				@SuspendRRRId,
				@SuspendRRRCode,
				@SuspendRRCalcTypeWhere,
				@SuspendRRCalcTypeMethod,
				@SuspendCOAAccountConfigId,
				@SuspendCOAAccountTypeId,
				@SuspendCOAAccountCode,
				data_transaction.transactionid, 
				data_transaction.saleid,
				DATA_TransactionItem.saleitemid,
				DATA_SaleItem.Matrixcellid,
				CNF_MatrixCell.Code,
				CNF_MatrixCell.MatrixSheetid,
				data_transaction.Siteid,
				data_transaction.OperatingAreaId,
				data_transaction.Workstationid,
				data_transaction.UserGroupid,
				data_transaction.UserId,
				@BatchDate,
				CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
				     else data_transaction.TransactionDate
				end TransactionDate,
				Coalesce(DATA_TransactionItem.Quantity, 1),
				DATA_SaleItem.UnitPrice,
				case when isnull(DATA_TransactionItem.TotalAmount, 0) &lt;&gt; 0 then DATA_TransactionItem.TotalAmount
					when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
					else DATA_Sale.TotalAmount
				end,
				case when isnull((DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes)
					when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
					else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
				end as NetAmount,
				@SuspendPrice,
				@SuspendCOAAccount_Percentage,
				@SuspendRemainingValues,
				ABS(DATA_SaleItem.Unitrecharge),
				case    when TransactionType in (5, 17, 8, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
						when TransactionType in (5, 17, 8, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
						when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 2
						when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 1
						else @SuspendRRCOAAccountingType
				end Accountingtype,
				@SuspendRRCalcTypeTrigger,
				@SuspendPercentage,
				@SuspendDays,
				CNF_AttributeSet.Attributeids
	   
		from DATA_Sale
			inner join data_transaction			on data_transaction.TransactionId = ISNULL(data_sale.voidtransactionid, DATA_Sale.PaidTransactionId)
			left join DATA_TransactionItem		on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
			left join DATA_SaleItem			    on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
			left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
			left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

		where DATA_Sale.Paid = 1
			and data_transaction.transactiontype in (31, 48, 52)
			and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
			   OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
			and data_transaction.transactionid in (select transactionid
													from data_payment
													where PaymentStatus = 1
													and PaymentAmount &lt;&gt; 0
												   )


	INSERT INTO [dbo].[RR_DATA_Revenue]
						([COAAccountId]
						,[RevenueRecognitionRuleId]
						,[RRCode]
						,[RRCalcTypeWhere]
						,[RRCalcTypeMethod]
						,[COAAccountConfigId]
						,[COAAccountType]
						,[COAAccountCode]
						,[TransactionId]
						,[SaleId]
						,[SaleItemId]
						,[MatrixCellId]
						,[MatrixCellCode]
						,[MatrixSheetID]
						,[SiteId]
						,[OperatingAreaId]
						,[WorkstationId]
						,[UserGroupId]
						,[UserId]
						,[FCalcDate]
						,[FRevenueDate]
						,[Quantity]
						,[UnitAmount]
						,[GrossAmount]
						,[NetAmount]
						,[Price]
						,[Percentage]
						,[RemaningValues]
						,[RevenueAmount]
						,[AccountingType]
						,[RRCalcTypeTrigger]
						,[RRPercentage]
						,[RRDays]
						,[AttributeIDS])
				select @SuspendCOAAccountId,
						@SuspendRRRId,
						@SuspendRRRCode,
						@SuspendRRCalcTypeWhere,
						@SuspendRRCalcTypeMethod,
						@SuspendCOAAccountConfigId,
						@SuspendCOAAccountTypeId,
						@SuspendCOAAccountCode,
						data_transaction.transactionid, 
						data_transaction.saleid,
						DATA_TransactionItem.saleitemid,
						DATA_SaleItem.Matrixcellid,
						CNF_MatrixCell.Code,
						CNF_MatrixCell.MatrixSheetid,
						data_transaction.Siteid,
						data_transaction.OperatingAreaId,
						data_transaction.Workstationid,
						data_transaction.UserGroupid,
						data_transaction.UserId,
						@BatchDate,
						CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
							 else data_transaction.TransactionDate
						end TransactionDate,
						Coalesce(DATA_TransactionItem.Quantity, 1),
						DATA_SaleItem.UnitPrice,
						case when isnull(DATA_TransactionItem.TotalAmount, 0) &lt;&gt; 0 then DATA_TransactionItem.TotalAmount
							when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
							else DATA_Sale.TotalAmount
						end,
						case when isnull((DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes)
							when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
							else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
						end as NetAmount,
						@SuspendPrice,
						@SuspendCOAAccount_Percentage,
						@SuspendRemainingValues,
						case when (data_saleitem.ProductTaxType &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice + DATA_SaleItem.unittaxes) * DATA_SaleItem.Quantity)
						     when (data_saleitem.ProductTaxType = 1) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice) * DATA_SaleItem.Quantity)
						     when (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 then 0
							 when isnull((data_transaction.TotalAmount), 0) &lt;&gt; 0 then data_transaction.TotalAmount
							 when isnull((DATA_Sale.TotalAmount), 0) &lt;&gt; 0 then DATA_Sale.TotalAmount
							 else (data_transaction.Revenue)
						end,
						case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
								when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
								when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 2
								when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 1
								else @SuspendRRCOAAccountingType
						end Accountingtype,
						@SuspendRRCalcTypeTrigger,
						@SuspendPercentage,
						@SuspendDays,
						CNF_AttributeSet.Attributeids
	   
				from DATA_Sale
					inner join data_transaction			on data_transaction.Saleid = DATA_Sale.Saleid
					left join DATA_TransactionItem		on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
					left join DATA_SaleItem			    on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
					left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
					left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

				where data_transaction.transactiontype in (8)
					and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
						OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
					and data_transaction.transactionid in (select transactionid
															from data_payment
															where PaymentStatus = 1
															and PaymentAmount &lt;&gt; 0
														)

			INSERT INTO [dbo].[RR_DATA_Revenue]
						([COAAccountId]
						,[RevenueRecognitionRuleId]
						,[RRCode]
						,[RRCalcTypeWhere]
						,[RRCalcTypeMethod]
						,[COAAccountConfigId]
						,[COAAccountType]
						,[COAAccountCode]
						,[TransactionId]
						,[SaleId]
						,[SiteId]
						,[OperatingAreaId]
						,[WorkstationId]
						,[UserGroupId]
						,[UserId]
						,[FCalcDate]
						,[FRevenueDate]
						,[Quantity]
						,[GrossAmount]
						,[NetAmount]
						,[Price]
						,[Percentage]
						,[RemaningValues]
						,[RevenueAmount]
						,[AccountingType]
						,[RRCalcTypeTrigger]
						,[RRPercentage]
						,[RRDays])
				select @SuspendCOAAccountId,
						@SuspendRRRId,
						@SuspendRRRCode,
						@SuspendRRCalcTypeWhere,
						@SuspendRRCalcTypeMethod,
						@SuspendCOAAccountConfigId,
						@SuspendCOAAccountTypeId,
						@SuspendCOAAccountCode,
						data_transaction.transactionid, 
						data_transaction.saleid,
						data_transaction.Siteid,
						data_transaction.OperatingAreaId,
						data_transaction.Workstationid,
						data_transaction.UserGroupid,
						data_transaction.UserId,
						@BatchDate,
						CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
							 else data_transaction.TransactionDate
						end TransactionDate,
						0 Quantity,
						data_transaction.revenue TotalAmount,
						data_transaction.revenue NetAmount,
						@SuspendPrice,
						@SuspendCOAAccount_Percentage,
						@SuspendRemainingValues,
						data_transaction.revenue,
						@SuspendRRCOAAccountingType,
						@SuspendRRCalcTypeTrigger,
						@SuspendPercentage,
						@SuspendDays
	   
				from DATA_Sale
					inner join data_transaction			on data_transaction.saleid = DATA_Sale.saleid
				where data_transaction.transactiontype = 12
					and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
						OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
					and data_transaction.transactionid in (select transactionid
															from data_payment
															where PaymentStatus = 1
															and PaymentAmount &lt;&gt; 0
														)



				INSERT INTO [dbo].[RR_DATA_Revenue]
						([COAAccountId]
						,[RevenueRecognitionRuleId]
						,[RRCode]
						,[RRCalcTypeWhere]
						,[RRCalcTypeMethod]
						,[COAAccountConfigId]
						,[COAAccountType]
						,[COAAccountCode]
						,[TransactionId]
						,[SaleId]
						,[SaleItemId]
						,[MatrixCellId]
						,[MatrixCellCode]
						,[MatrixSheetID]
						,[SiteId]
						,[OperatingAreaId]
						,[WorkstationId]
						,[UserGroupId]
						,[UserId]
						,[FCalcDate]
						,[FRevenueDate]
						,[Quantity]
						,[UnitAmount]
						,[GrossAmount]
						,[NetAmount]
						,[Price]
						,[Percentage]
						,[RemaningValues]
						,[RevenueAmount]
						,[AccountingType]
						,[RRCalcTypeTrigger]
						,[RRPercentage]
						,[RRDays]
						,[AttributeIDS])
						select *
						from (
				select @SuspendCOAAccountId as COAAccountId,
						@SuspendRRRId as RevenueRecognitionRuleId,
						@SuspendRRRCode as RRCode,
						@SuspendRRCalcTypeWhere as RRCalcTypeWhere,
						@SuspendRRCalcTypeMethod as RRCalcTypeMethod,
						@SuspendCOAAccountConfigId as COAAccountConfigId,
						@SuspendCOAAccountTypeId as COAAccountType,
						@SuspendCOAAccountCode as COAAccountCode,
						data_transaction.transactionid, 
						data_transaction.saleid,
						DATA_SaleItem.saleitemid,
						DATA_SaleItem.Matrixcellid,
						CNF_MatrixCell.Code,
						CNF_MatrixCell.MatrixSheetid,
						data_transaction.Siteid,
						data_transaction.OperatingAreaId,
						data_transaction.Workstationid,
						data_transaction.UserGroupid,
						data_transaction.UserId,
						@BatchDate as calcdate,
						CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
								else data_transaction.TransactionDate
						end TransactionDate,
						Coalesce(DATA_SaleItem.Quantity, 1) as quantity,
						DATA_SaleItem.UnitPrice,
						case when isnull(DATA_SaleItem.TotalAmount, 0) &lt;&gt; 0 then DATA_SaleItem.TotalAmount
							when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
							else DATA_Sale.TotalAmount
						end as totalamount,
						case when isnull((DATA_SaleItem.TotalAmount - DATA_SaleItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_SaleItem.TotalAmount - DATA_SaleItem.TotalTaxes)
							when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
							else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
						end as NetAmount,
						@SuspendPrice as suspendprice,
						@SuspendCOAAccount_Percentage as percentage,
						@SuspendRemainingValues as remainingValues,
						case when (data_saleitem.ProductTaxType &lt;&gt; 1) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice) * DATA_SaleItem.Quantity)
						     when (data_saleitem.ProductTaxType = 1) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice - DATA_SaleItem.unittaxes) * DATA_SaleItem.Quantity)
						     when isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 then 0
							 when isnull((data_transaction.TotalAmount), 0) &lt;&gt; 0 then data_transaction.TotalAmount
							 when isnull((DATA_Sale.TotalAmount), 0) &lt;&gt; 0 then DATA_Sale.TotalAmount
							 else (data_transaction.Revenue)
						end as Revenueamount,
						case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
								when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
								when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 2
								when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 1
								else @SuspendRRCOAAccountingType
						end Accountingtype,
						@SuspendRRCalcTypeTrigger as rrTrigger,
						@SuspendPercentage as suspercentage,
						@SuspendDays as suspendday,
						CNF_AttributeSet.Attributeids
	   
				from DATA_Sale
					inner join data_transaction			on data_transaction.TransactionId = DATA_Sale.PaidTransactionId
					left join DATA_SaleItem			    on DATA_SaleItem.SAleid = data_transaction.SAleid
					left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
					left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

				where DATA_Sale.Paid = 1
					and data_transaction.transactiontype in (16)
					and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
					 OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
					and data_transaction.transactionid in (select transactionid
															from data_payment
															where PaymentStatus = 1
															--and PaymentAmount &lt;&gt; 0
														)
					and data_transaction.transactionid not in (select distinct transactionid
																from rr_data_Revenue
																where transactionid is not null)
					and data_saleitem.saleitemid not in (select distinct data_saleitem.saleitemid
													from data_saleitem
															inner join data_transactionitem   on data_transactionitem.saleitemid = data_saleitem.saleitemid
															inner join data_transaction       on data_transaction.transactionid = data_transactionitem.transactionid
													where data_transaction.transactiontype in (5)
													)
					)p  where UnitPrice &lt;&gt; 0


				INSERT INTO [dbo].[RR_DATA_Revenue]
						([COAAccountId]
						,[RevenueRecognitionRuleId]
						,[RRCode]
						,[RRCalcTypeWhere]
						,[RRCalcTypeMethod]
						,[COAAccountConfigId]
						,[COAAccountType]
						,[COAAccountCode]
						,[TransactionId]
						,[SaleId]
						,[SaleItemId]
						,[MatrixCellId]
						,[MatrixCellCode]
						,[MatrixSheetID]
						,[SiteId]
						,[OperatingAreaId]
						,[WorkstationId]
						,[UserGroupId]
						,[UserId]
						,[FCalcDate]
						,[FRevenueDate]
						,[Quantity]
						,[UnitAmount]
						,[GrossAmount]
						,[NetAmount]
						,[Price]
						,[Percentage]
						,[RemaningValues]
						,[RevenueAmount]
						,[AccountingType]
						,[RRCalcTypeTrigger]
						,[RRPercentage]
						,[RRDays]
						,[AttributeIDS])
				select @SuspendCOAAccountId,
						@SuspendRRRId,
						@SuspendRRRCode,
						@SuspendRRCalcTypeWhere,
						@SuspendRRCalcTypeMethod,
						@SuspendCOAAccountConfigId,
						@SuspendCOAAccountTypeId,
						@SuspendCOAAccountCode,
						data_transaction.transactionid, 
						data_transaction.saleid,
						DATA_TransactionItem.saleitemid,
						DATA_SaleItem.Matrixcellid,
						CNF_MatrixCell.Code,
						CNF_MatrixCell.MatrixSheetid,
						data_transaction.Siteid,
						data_transaction.OperatingAreaId,
						data_transaction.Workstationid,
						data_transaction.UserGroupid,
						data_transaction.UserId,
						@BatchDate,
						CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
							 else data_transaction.TransactionDate
						end TransactionDate,
						Coalesce(DATA_TransactionItem.Quantity, 1),
						DATA_SaleItem.UnitPrice,
						case when isnull(DATA_TransactionItem.TotalAmount, 0) &lt;&gt; 0 then DATA_TransactionItem.TotalAmount
							when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
							else DATA_Sale.TotalAmount
						end,
						case when isnull((DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes)
							when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
							else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
						end as NetAmount,
						@SuspendPrice,
						@SuspendCOAAccount_Percentage,
						@SuspendRemainingValues,
						case when isnull((DATA_TransactionItem.UnitPrice *  DATA_TransactionItem.Quantity), 0) &lt;&gt; 0 then (DATA_TransactionItem.UnitPrice *  DATA_TransactionItem.Quantity)
							when isnull((data_transaction.TotalAmount), 0) &lt;&gt; 0 then data_transaction.TotalAmount
							when isnull((DATA_Sale.TotalAmount), 0) &lt;&gt; 0 then DATA_Sale.TotalAmount
							else (data_transaction.Revenue)
						end,
						case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 1 then 2
								when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @SuspendRRCOAAccountingType = 2 then 1
								when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 2
								when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 1
								else @SuspendRRCOAAccountingType
						end Accountingtype,
						@SuspendRRCalcTypeTrigger,
						@SuspendPercentage,
						@SuspendDays,
						CNF_AttributeSet.Attributeids
	   
				from DATA_Sale
					inner join data_transaction			on data_transaction.saleid = DATA_Sale.saleid
					inner join DATA_TransactionItem		on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
					left join DATA_SaleItem			    on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
					left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
					left join CNF_AttributeSet			on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

				where DATA_Sale.Paid = 1
					and data_transaction.transactiontype in (5)
					and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
					 OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
					
					and data_transaction.transactionid in (select transactionid
															from data_payment
															where PaymentStatus = 1
															and PaymentAmount &lt;&gt; 0
														)
					and data_transaction.transactionid not in (select distinct transactionid
																from rr_data_Revenue
																where transactionid is not null)

--PaymentMethod
				INSERT INTO [dbo].[RR_DATA_Revenue]
								([COAAccountId]
								,[RevenueRecognitionRuleId]
								,[RRCode]
								,[RRCalcTypeWhere]
								,[RRCalcTypeMethod]
								,[COAAccountConfigId]
								,[COAAccountType]
								,[COAAccountCode]
								,[TransactionId]
								,[SaleId]
								,[SiteId]
								,[OperatingAreaId]
								,[WorkstationId]
								,[UserGroupId]
								,[UserId]
								,[FCalcDate]
								,[FRevenueDate]
								,[Quantity]
								,[GrossAmount]
								,[NetAmount]
								,[Price]
								,[Percentage]
								,[RemaningValues]
								,[RevenueAmount]
								,[AccountingType]
								,[RRCalcTypeTrigger]
								,[RRPercentage]
								,[RRDays])
								select  coaaccountid,
										RRID,
										RRCode,
										TypeWhere,
										method,
										Configid,
										AccountType,
										AccountCode,
										transactionid, 
										saleid,
										Siteid,
										OperatingAreaId,
										WorkstationID,
										UserGroupid,
										UserId,
										BatchDate,
										TransactionDate,
										Qty,
										Gross,
										net,
										price,
										percentage,
										RemaningValue,
										sum(abs(RevenueAmount)),
										Accountingtype,
										TypeTrigger,
										PaymentPercentage,
										RRDays
								from (
								select  coaaccountid,
										RRID,
										RRCode,
										TypeWhere,
										method,
										Configid,
										AccountType,
										AccountCode,
										transactionid, 
										saleid,
										Siteid,
										OperatingAreaId,
										WorkstationID,
										UserGroupid,
										UserId,
										BatchDate,
										TransactionDate,
										Qty,
										Gross,
										net,
										price,
										percentage,
										RemaningValue,
										case when Rownumber = 1 then RevenueAmount + Change
										     else RevenueAmount
										 end RevenueAmount,
										Accountingtype,
										TypeTrigger,
										PaymentPercentage,
										RRDays
								from (
								select @PaymentCOAAccountId as coaaccountid,
										@PaymentRRRId as RRID,
										@PaymentRRRCode as RRCode,
										@PaymentRRCalcTypeWhere as TypeWhere,
										@PaymentRRCalcTypeMethod as method,
										@PaymentCOAAccountConfigId as Configid,
										@PaymentCOAAccountTypeId as AccountType,
										@PaymentCOAAccountCode as AccountCode,
										data_transaction.transactionid, 
										data_transaction.saleid,
										data_transaction.Siteid,
										data_transaction.OperatingAreaId,
										data_transaction.Workstationid,
										data_transaction.UserGroupid,
										data_transaction.UserId,
										@BatchDate as BatchDate,
										CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
											 else data_transaction.TransactionDate
										end TransactionDate,
										0 as Qty,
										0 as Gross,
										0 as net,
										0 as price,
										100 as percentage,
										0 as RemaningValue,
										(data_payment.PaymentAmount) as RevenueAmount,
										case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @PaymentRRCOAAccountingType = 1 then 2
												when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @PaymentRRCOAAccountingType = 2 then 1
												when TransactionType in (7) and (data_payment.PaymentAmount + data_Payment.PaymentFee) &lt;= 0  then 2
												when TransactionType in (7) and (data_payment.PaymentAmount + data_Payment.PaymentFee) &gt; 0  then 1
												else @PaymentRRCOAAccountingType
									    end Accountingtype,
										data_transaction.Change,
										@PaymentRRCalcTypeTrigger as TypeTrigger,
										@PaymentPercentage as PaymentPercentage,
										@PaymentDays as RRDays,
										Row_Number ()  OVER (PARTITION BY data_transaction.transactionid order by data_transaction.transactionid)  as Rownumber
		  
								from DATA_Sale
											INNER join data_transaction			on ((data_transaction.TransactionId = Isnull(data_sale.voidtransactionid, DATA_Sale.PaidTransactionId)) or 
											                                       (data_transaction.saleid = data_sale.saleid))
											INNER JOIN DATA_Payment				on data_payment.transactionid = data_transaction.transactionid
			
								where data_payment.PaymentStatus = 1
									and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
									 OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
							)p
							)r
							group by 	coaaccountid,
										RRID,
										RRCode,
										TypeWhere,
										method,
										Configid,
										AccountType,
										AccountCode,
										transactionid, 
										saleid,
										Siteid,
										OperatingAreaId,
										Workstationid,
										UserGroupid,
										UserId,
										BatchDate,
										TransactionDate,
										Qty,
										Gross,
										net,
										price,
										percentage,
										RemaningValue,
										Accountingtype,
										TypeTrigger,
										PaymentPercentage,
										RRDays
							Having sum(abs(RevenueAmount)) &lt;&gt; 0
						



--Tax
					INSERT INTO [dbo].[RR_DATA_Revenue]
								([COAAccountId]
								,[RevenueRecognitionRuleId]
								,[RRCode]
								,[RRCalcTypeWhere]
								,[RRCalcTypeMethod]
								,[COAAccountConfigId]
								,[COAAccountType]
								,[COAAccountCode]
								,[TransactionId]
								,[SaleId]
								,[SiteId]
								,[OperatingAreaId]
								,[WorkstationId]
								,[UserGroupId]
								,[UserId]
								,[FCalcDate]
								,[FRevenueDate]
								,[Quantity]
								,[GrossAmount]
								,[NetAmount]
								,[Price]
								,[Percentage]
								,[RemaningValues]
								,[RevenueAmount]
								,[AccountingType]
								,[RRCalcTypeTrigger]
								,[RRPercentage]
								,[RRDays])

								select  @TaxCOAAccountId,
										@TaxRRRId,
										@TaxRRRCode,
										@TaxRRCalcTypeWhere,
										@TaxRRCalcTypeMethod,
										@TaxCOAAccountConfigId,
										@TaxCOAAccountTypeId,
										@TaxCOAAccountCode,
										data_transaction.transactionid, 
										data_transaction.saleid,
										data_transaction.Siteid,
										data_transaction.OperatingAreaId,
										data_transaction.Workstationid,
										data_transaction.UserGroupid,
										data_transaction.UserId,
										@BatchDate,
										CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
											 else data_transaction.TransactionDate
										end TransactionDate,
										0,
										0,
										0,
										0,
										100,
										0,
										ABS(sum(taxamount)) RevenueAmount,
										case    when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @TaxRRCOAAccountingType = 1 then 2
												when TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) and @TaxRRCOAAccountingType = 2 then 1
											    when TransactionType in (7) and sum(taxamount) &lt;= 0  then 1
												when TransactionType in (7) and sum(taxamount) &gt; 0  then 2
												else @TaxRRCOAAccountingType
									    end Accountingtype,
										@TaxRRCalcTypeTrigger,
										@TaxPercentage,
										@TaxDays
		   
							from Data_Sale
								INNER JOIN DATA_Transaction						on data_transaction.Saleid = Data_Sale.Saleid
								INNER JOIN DATA_TransactionTax					on data_transactiontax.transactionid = data_transaction.transactionid
								INNER JOIN CNF_Tax								on cnf_tax.taxid = DATA_TransactionTax.taxid
								--INNER JOIN coa_cnf_account coa					on coa.coaaccountid = cnf_tax.coaaccountid


							where transactiontype NOT IN (33, 45, 46, 47)
							   and Data_Sale.paid = 1
								and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
								 OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
								  and data_transaction.transactionid in (select distinct transactionid
								                                           from data_payment
																		   where data_payment.paymentstatus = 1
																		)
							group by 			data_transaction.transactionid, 
												data_transaction.saleid,
												data_transaction.Siteid,
												data_transaction.OperatingAreaId,
												data_transaction.Workstationid,
												data_transaction.UserGroupid,
												data_transaction.UserId,
												Data_Transaction.TransactionDate,
												TransactionType,
												fTransactionDate


--Discount

						INSERT INTO [dbo].[RR_DATA_Revenue]
								([COAAccountId]
								,[RevenueRecognitionRuleId]
								,[RRCode]
								,[RRCalcTypeWhere]
								,[RRCalcTypeMethod]
								,[COAAccountConfigId]
								,[COAAccountType]
								,[COAAccountCode]
								,[TransactionId]
								,[SaleId]
								,[SiteId]
								,[OperatingAreaId]
								,[WorkstationId]
								,[UserGroupId]
								,[UserId]
								,[FCalcDate]
								,[FRevenueDate]
								,[Quantity]
								,[GrossAmount]
								,[NetAmount]
								,[Price]
								,[Percentage]
								,[RemaningValues]
								,[RevenueAmount]
								,[AccountingType]
								,[RRCalcTypeTrigger]
								,[RRPercentage]
								,[RRDays])

								select  @DiscountCOAAccountId,
										@DiscountRRRId,
										@DiscountRRRCode,
										@DiscountRRCalcTypeWhere,
										@DiscountRRCalcTypeMethod,
										@DiscountCOAAccountConfigId,
										@DiscountCOAAccountTypeId,
										@DiscountCOAAccountCode,
										data_transaction.transactionid, 
										data_transaction.saleid,
										data_transaction.Siteid,
										data_transaction.OperatingAreaId,
										data_transaction.Workstationid,
										data_transaction.UserGroupid,
										data_transaction.UserId,
										@BatchDate,
										CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
											 else data_transaction.TransactionDate
										end TransactionDate,
										0,
										0,
										0,
										0,
										100,
										0,
										ABS(p.GLAmount) RevenueAmount,
										case    when data_transaction.TransactionType in (5, 8, 17, 18, 20, 22, 30, 46, 47) then 2
											    when data_transaction.TransactionType in (7) and (GLAmount) &lt;= 0  then 2
												when data_transaction.TransactionType in (7) and (GLAmount) &gt; 0  then 1
												else @DiscountRRCOAAccountingType
									    end Accountingtype,

										@DiscountRRCalcTypeTrigger,
										@DiscountPercentage,
										@DiscountDays
							FROM
							(
								SELECT distinct DATA_SaleItem.Saleitemid,
												DATA_Sale.saleid AS SAleid,
      											DATA_Transaction.TransactionType,
      											( SELECT top 1 transactionid
													FROM data_transaction		WITH (NOLOCK)
												   WHERE saleid = DATA_Sale.saleid
													AND transactiontype in (14, 16)
													AND paid = 1
												) AS tester,

												CASE WHEN DATA_Transaction.TransactionId IN (
																							  SELECT TR.TransactionID
																								FROM DATA_Transaction TR			WITH (NOLOCK)
																									LEFT JOIN DATA_Payment DP		WITH (NOLOCK) ON TR.TransactionId = DP.TransactionId
																							  WHERE TR.SaleId = DATA_Sale.SaleId
																								AND TR.Paid = 1
																								AND DP.PaymentStatus NOT IN (0, 2, 3)
																							)
      
															THEN DATA_Transaction.Transactionid
													 ELSE (
															  SELECT MIN(TR.TransactionID)
																FROM DATA_Transaction TR				WITH (NOLOCK)
																	LEFT JOIN DATA_Payment DP			WITH (NOLOCK) ON TR.TransactionId = DP.TransactionId
															   WHERE TR.SaleId = DATA_Sale.saleid
																 AND TR.TransactionType = 16
																 AND TR.Paid = 1
																 AND DP.PaymentStatus NOT IN (0, 2, 3)
														  )
												END Transactionid, 
												 CASE WHEN CNF_Promotion.PromotionType = 1 AND CNF_PromotionItemRule.NewProduct = 1 THEN  (CNF_MatrixCell.Price - SUM(DATA_SaleItemRule.DiscountAmount))
													  ELSE  CASE WHEN sum(1*data_saleItemRule.DiscountAmount) &lt; 0 AND transactiontype IN(20, 22, 30, 7, 5, 46, 47) AND
																																								(SELECT Count(*) 
																																								   FROM data_transaction WITH (NOLOCK)
																																								  WHERE saleid = data_sale.saleid
																																								 ) = 1 					  					  					  										  
																	  THEN Sum(1 * DATA_SaleItemRule.DiscountAmount)
																 WHEN sum(1*data_saleItemRule.DiscountAmount) &lt; 0 THEN	Sum(-1 * DATA_SaleItemRule.DiscountAmount)
																 WHEN sum(1*data_saleItemRule.DiscountAmount) &gt; 0 AND transactiontype IN(20, 22, 30, 7, 5, 46, 47) THEN Sum(-1 * DATA_SaleItemRule.DiscountAmount)		            	                  
																 ELSE sum(1*Data_SaleItemRule.DiscountAmount)
															END
												END AS GLAmount


								FROM dbo.DATA_SaleItemRule				WITH (NOLOCK)
									LEFT JOIN dbo.CNF_PromotionItemRule WITH (NOLOCK) ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
									LEFT JOIN dbo.CNF_PromotionItem		WITH (NOLOCK) ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
									LEFT JOIN dbo.CNF_Promotion			WITH (NOLOCK) ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId
									LEFT JOIN dbo.CNF_DmgCategory		WITH (NOLOCK) ON CNF_DmgCategory.DmgCategoryId = CNF_Promotion.DmgCategoryId
									LEFT JOIN dbo.DATA_SaleItem			WITH (NOLOCK) ON DATA_SaleItem.SaleItemId = DATA_SaleItemRule.SaleItemId
									LEFT JOIN dbo.DATA_Sale				WITH (NOLOCK) ON DATA_Sale.SaleID = DATA_SaleItem.SaleID
									LEFT JOIN DATA_TransactionItem		WITH (NOLOCK) ON DATA_TransactionItem.SaleItemId = DATA_SaleItem.SaleItemId 
									LEFT JOIN DATA_Transaction			WITH (NOLOCK) ON  DATA_Transaction.TransactionId = DATA_TransactionItem.TransactionId
									LEFT JOIN CNF_MatrixCell			WITH (NOLOCK) ON CNF_MatrixCell.MatrixCellId =  DATA_SaleItem.MatrixCellId

 
								WHERE DATA_Transaction.saleid in (
																	SELECT ff.saleid 
																	  FROM DATA_Transaction ff WITH (NOLOCK) 
																		LEFT JOIN Data_Payment WITH (NOLOCK) on (ff.Transactionid = Data_Payment.Transactionid) 
																	 WHERE  ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
																		OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
																	   AND DATA_PAyment.PaymentStatus NOT in (0,2,3) 
																	   AND (TransactionType not in (12)) 
																	   AND ff.PAid = 1
																 )  

								 AND DATA_Sale.Paid = 1
								 and transactiontype NOT IN (33, 45, 46, 47)
								 AND ((DATA_SaleItem.quantity &gt; 0) OR ((DATA_SaleItem.quantity &lt; 0) AND (transactiontype IN (20, 22, 30, 7, 5, 46, 47))))

         
								group BY DATA_SaleItem.Saleitemid,
										 DATA_Sale.saleid,
										 Data_transaction.Paid,
										 Data_Transaction.Transactionid,
										 Data_Transaction.fTransactionDate,
										 Data_Saleitem.Matrixcellid,
										 CNF_DmgCategory.DmgCategoryCode,
										 PromotionType,
										 CNF_PromotionItemRule.NewProduct,
										 CNF_MatrixCell.Price,
										 transactiontype,
										 CNF_DmgCategory.Description
							)p
								LEFT JOIN data_transaction WITH (NOLOCK) on data_transaction.transactionid = p.transactionid

							WHERE ((p.TransactionType &lt;&gt; 5) or (Tester is not null))
							  AND data_transaction.transactionid is not null


					
		--End Move Transactions to Suspend Account

		exec otn_sp_RR_RevenueData_OnDepositTrigger @BatchDate, @RRTransDateType

		exec otn_sp_RR_RevenueData_OnSaleTrigger @BatchDate, @RRTransDateType
		
		exec otn_sp_RR_RevenueData_OnMoneyCardLoad @BatchDate, @RRTransDateType

		exec otn_sp_RR_RevenueData_OnMoneyCardCashOut @BatchDate, @RRTransDateType

		exec otn_sp_RR_RevenueData_OnExternalMoneyCardCashOut @BatchDate, @RRTransDateType

		exec otn_sp_RR_RevenueData_OnExternalMoneyCardLoad @BatchDate, @RRTransDateType

                exec otn_sp_RR_RevenueData_OnCreditWriteoff @BatchDate, @RRTransDateType

		exec otn_sp_RR_RevenueData_OnMoneyRefundTrigger @BatchDate, @RRTransDateType

		exec otn_sp_RR_RevenueData_OnAdvancedPaymentTrigger @BatchDate, @RRTransDateType
		
		--exec otn_sp_RR_RevenueData_OnFlexContractPayment @BatchDate, @RRTransDateType

		--exec otn_sp_RR_RevenueData_OnFlexContractCancelled @BatchDate, @RRTransDateType

		--exec otn_sp_RR_RevenueData_OnCreditSettlementTrigger @BatchDate, @RRTransDateType
		
		exec otn_sp_RR_RevenueData_SettleUpSuspendAccount @BatchDate, @RRTransDateType


	        exec otn_sp_RR_RevenueData_OnTicketUsageTrigger @BatchDate, @RRTransDateType

		exec otn_sp_RR_RevenueData_OnEventTrigger @BatchDate, @RRTransDateType

		exec otn_sp_RR_RevenueData_OnTimePeriodTrigger @BatchDate, @RRTransDateType

		exec otn_sp_RR_RevenueData_OnTicketExpiredTrigger @BatchDate, @RRTransDateType
		

End
</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>kdixon</ADDEDBY>
			<SQLVERSION>2303</SQLVERSION>
			<RMTRACKLINK>71133</RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_RR_RevenueData_OnMoneyCardLoad]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_RR_RevenueData_OnMoneyCardLoad
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'AccountingType' AND
                Object_ID  = Object_ID(N'RR_DATA_Revenue'))
BEGIN
  ALTER TABLE RR_DATA_Revenue ADD AccountingType Smallint NULL
END
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE Procedure dbo.otn_sp_RR_RevenueData_OnMoneyCardLoad
	@BatchDate Date,
	@RRTransDateType Integer
AS 
BEGIN
	
	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer
	Declare @OnMoneyCardCashOut Integer = 10

	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1


		BEGIN

			--Normal Transaction No Remaining Values
			INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[Saleitemid]
				   ,[MatrixCellid]
				   ,[MatrixCellCode]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])
				   select *
				   from(
						select distinct coa_cnf_account.COAAccountId, 
								   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
								   RR_CNF_RevenueRecognitionRule.code,		   
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
								   COA_CNF_AccountConfig.COAAccountConfigId,
								   coa_cnf_account.COAAccountTypeId,
								   coa_cnf_account.Code as AccountCode,
								   RR_DATA_REVENUE.Transactionid as Transactionid,
								   RR_DATA_REVENUE.saleid as Saleid,
								   RR_DATA_REVENUE.SaleitemID as SaleitemID,
								   RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								   RR_DATA_REVENUE.MatrixcellCode as MatrixCode,
								   RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								   RR_DATA_REVENUE.Siteid as SiteID,
								   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								   RR_DATA_REVENUE.Workstationid as Workstationid,
								   RR_DATA_REVENUE.UserGroupid as UserGroupID,
								   RR_DATA_REVENUE.UserId as userID,
								   @BatchDate as BatchDate,
								   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
								        else DATA_Transaction.transactiondate
								   end as TransDate,
								   RR_DATA_REVENUE.Quantity as Quantity,
								   RR_DATA_REVENUE.GrossAmount as GrossAmount,
								   RR_DATA_REVENUE.NetAmount as NetAmount,
								   COA_CNF_AccountConfig.Price as ConfigPrice,
								   COA_CNF_AccountConfig.Percentage as ConfigPercentage,
								   COA_CNF_AccountConfig.RemainingValues,																		
									Case when COA_CNF_AccountConfig.Price &gt; 0 then (COA_CNF_AccountConfig.Price * RR_DATA_REVENUE.Quantity) 
										 else (ISNULL(((ABS((select unitrecharge
															   from data_saleitem
															  where saleitemid = RR_DATA_REVENUE.saleitemid
										))) * COA_CNF_AccountConfig.Percentage/100), 0))																		                                                                                                                                                                                              
									end  as RevenueAmount,

								   case when TransactionType in (5, 17, 18, 20, 22, 30) and COA_CNF_AccountConfig.Accountingtype = 1 then 2
								        when TransactionType in (5, 17, 18, 20, 22, 30) and COA_CNF_AccountConfig.Accountingtype = 2 then 1
										when TransactionType in (7) and rr_data_revenue.RevenueAmount &lt; 0 and COA_CNF_AccountConfig.Accountingtype = 2 then 1
								        else COA_CNF_AccountConfig.Accountingtype
									end Accountingtype,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
								   RR_CNF_RevenueRecognitionRule.Percentage,
								   RR_CNF_RevenueRecognitionRule.Days
		   
							from RR_DATA_REVENUE
									inner join rr_cnf_Product						ON ((RR_DATA_REVENUE.MATRIXCELLID = rr_cnf_Product.MATRIXCELLID) or (RR_DATA_REVENUE.MatrixSheetId = rr_cnf_Product.MatrixSheetId)) and rr_cnf_Product.Enabled = 1
									inner join RR_CNF_RevenueRecognitionRule		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_cnf_Product.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  
									INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
									INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
									INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 
									INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid

							where RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger IN (@OnMoneyCardCashOut)

							  and RR_CNF_RevenueRecognitionRule.Enabled = 1
							  and coa_cnf_account.Enabled = 1
							  and COA_CNF_AccountConfig.Enabled = 1
							  and ((TransactionType in (10, 20, 18, 22)) or (RR_DATA_REVENUE.transactionid in (select transactionid
																									 from data_transaction
																										Inner join data_saleitem   on data_saleitem.saleid = data_transaction.saleid
																									where data_transaction.transactiontype in (14)
																									  and data_saleitem.unitrecharge &lt;&gt; 0
																								 )
																))
							  and ((coa_cnf_accountConfig.Siteid = RR_DATA_REVENUE.SiteId) or (coa_cnf_accountConfig.Siteid is null))
							  and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
							  and COA_CNF_AccountConfig.RemainingValues &lt;&gt; 1
							  and RR_DATA_REVENUE.fcalcdate = @BatchDate
							  and RR_DATA_REVENUE.coaaccountid = @suspendid
						
					)p
					where RevenueAmount &lt;&gt; 0

				--Normal Transaction with Remaining Values
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[Saleitemid]
				   ,[MatrixCellid]
				   ,[MatrixCellCode]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])
				   select *
				   from(
						select distinct coa_cnf_account.COAAccountId, 
								   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
								   RR_CNF_RevenueRecognitionRule.code,		   
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
								   COA_CNF_AccountConfig.COAAccountConfigId,
								   coa_cnf_account.COAAccountTypeId,
								   coa_cnf_account.Code as AccountCode,
								   RR_DATA_REVENUE.Transactionid as Transactionid,
								   RR_DATA_REVENUE.saleid as Saleid,
								   RR_DATA_REVENUE.SaleitemID as SaleitemID,
								   RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								   RR_DATA_REVENUE.MatrixcellCode as MatrixCode,
								   RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								   RR_DATA_REVENUE.Siteid as SiteID,
								   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								   RR_DATA_REVENUE.Workstationid as Workstationid,
								   RR_DATA_REVENUE.UserGroupid as UserGroupID,
								   RR_DATA_REVENUE.UserId as userID,
								   @BatchDate as BatchDate,
								   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
								        else DATA_Transaction.transactiondate
								   end as TransDate,
								   RR_DATA_REVENUE.Quantity as Quantity,
								   RR_DATA_REVENUE.GrossAmount as GrossAmount,
								   RR_DATA_REVENUE.NetAmount as NetAmount,
								   COA_CNF_AccountConfig.Price as ConfigPrice,
								   COA_CNF_AccountConfig.Percentage as ConfigPercentage,
								   COA_CNF_AccountConfig.RemainingValues,							 
								   ISNULL((RR_DATA_REVENUE.RevenueAmount - (select ISNULL(sum(revenueamount), 0)
								                            from RR_DATA_Revenue rr
												              where rr.saleitemid = RR_DATA_REVENUE.SaleitemID
												        and rr.COAAccountid not in (@SuspendID, @ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)
												 )
									), 0)
									as RevenueAmount,
								   case when TransactionType in (5, 17, 18, 20, 22, 30) and COA_CNF_AccountConfig.Accountingtype = 1 then 2
								        when TransactionType in (5, 17, 18, 20, 22, 30) and COA_CNF_AccountConfig.Accountingtype = 2 then 1
										when TransactionType in (7) and rr_data_revenue.RevenueAmount &lt; 0 and COA_CNF_AccountConfig.Accountingtype = 2 then 1
								        else COA_CNF_AccountConfig.Accountingtype
									end Accountingtype,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
								   RR_CNF_RevenueRecognitionRule.Percentage,
								   RR_CNF_RevenueRecognitionRule.Days

						from RR_DATA_REVENUE
								inner join rr_cnf_Product						ON ((RR_DATA_REVENUE.MATRIXCELLID = rr_cnf_Product.MATRIXCELLID) or (RR_DATA_REVENUE.MatrixSheetId = rr_cnf_Product.MatrixSheetId)) and rr_cnf_Product.Enabled = 1
								inner join RR_CNF_RevenueRecognitionRule		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_cnf_Product.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  
								INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
								INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
								INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 
								INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid

							where RR_CNF_RevenueRecognitionRule.Enabled = 1
							  and coa_cnf_account.Enabled = 1
							  and COA_CNF_AccountConfig.Enabled = 1
							  and TransactionType in (10, 20, 18, 22)
							  and ((coa_cnf_accountConfig.Siteid = RR_DATA_REVENUE.SiteId) or (coa_cnf_accountConfig.Siteid is null))
							  and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger IN (@OnMoneyCardCashOut)
							  and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
							  and COA_CNF_AccountConfig.RemainingValues = 1
							  and RR_DATA_REVENUE.fcalcdate = @BatchDate
							  and RR_DATA_REVENUE.coaaccountid = @suspendid
					)p
					where RevenueAmount &lt;&gt; 0

		
		exec otn_sp_RR_RevenueData_PaymentMethodTaxDiscounts @BatchDate, '10,', @OnMoneyCardCashOut, @RRTransDateType									

	end
	select '@OnMoneyCardLoad' as TriggerType, @BatchDate as RunDate
END
</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>jlaguardia</ADDEDBY>
			<SQLVERSION>2302</SQLVERSION>
			<RMTRACKLINK>70911</RMTRACKLINK>
			<REASON>Forgot ReservationId column from last patch.</REASON>
			<TABLENAMES>DATA_PaymentHotel=PaymentHotelId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'HotelReservationId' AND
                Object_ID  = Object_ID(N'DATA_PaymentHotel'))
BEGIN
	Alter Table DATA_PaymentHotel
	Add HotelReservationId nvarchar (1000) NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>jlaguardia</ADDEDBY>
			<SQLVERSION>2301</SQLVERSION>
			<RMTRACKLINK>70911</RMTRACKLINK>
			<REASON>+Add columns to DATA_PaymentHotel:
  +RoomNumber
  +GuestLastName
  +HotelReservationId
  ~Rename column ReferenceId to HotelTransactionId</REASON>
			<TABLENAMES>DATA_PaymentHotel=PaymentHotelId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS ( SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND  TABLE_NAME = 'DATA_PaymentHotel' )

BEGIN
  drop table DATA_PaymentHotel
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS ( SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND  TABLE_NAME = 'DATA_PaymentHotel' )

BEGIN
Create table DATA_PaymentHotel
(
	[PaymentHotelId] Integer Identity(1,1) NOT NULL,
	[PaymentId] Integer NOT NULL,
	[RawRequest] Varchar(1000) NULL,
	[RawAnswer] Varchar(1000) NULL,
	[HotelTransactionId] Integer NULL,
	[SequenceNumber] Integer NULL,
	[ResponseStatus] Ntext NULL,
	[ResponseText] Ntext NULL,
	[RoomNumber] Varchar(1000) NULL,
	[GuestLastName] Varchar(1000) NULL,
	[HotelReservationId] Varchar(1000) NULL,
	[PaymentStatus] Smallint NULL,
Primary Key ([PaymentHotelId])
) 
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'DATA_PaymentHotel'
	          AND CONSTRAINT_NAME = N'fk_DATA_PaymentHotel_PaymentId')          
BEGIN
  ALTER TABLE DATA_PaymentHotel WITH CHECK
  ADD CONSTRAINT [fk_DATA_PaymentHotel_PaymentId] FOREIGN KEY([PaymentId])
  REFERENCES [DATA_Payment] ([PaymentId])
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>kdixon</ADDEDBY>
			<SQLVERSION>2300</SQLVERSION>
			<RMTRACKLINK>71133</RMTRACKLINK>
			<REASON>Money Card Cash out Stored Procedure for COA</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_RR_RevenueData_OnMoneyCardLoad]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_RR_RevenueData_OnMoneyCardLoad
</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>marioarosio</ADDEDBY>
			<SQLVERSION>2299</SQLVERSION>
			<RMTRACKLINK>68273</RMTRACKLINK>
			<REASON>Add Column Note on STOCK_Movement</REASON>
			<TABLENAMES>STOCK_Movement=MovementId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Note' AND
                Object_ID  = Object_ID(N'STOCK_Movement'))
BEGIN
	Alter Table STOCK_Movement
	Add Note nvarchar (4000) NULL;
END
</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Federico Caramella</ADDEDBY>
			<SQLVERSION>2298</SQLVERSION>
			<RMTRACKLINK>IDBOS-308</RMTRACKLINK>
			<REASON>
 **  NEW SUGGESTIVE SELL FEATURE **

Script 0 ) CREATE TABLE CNF_SuggestiveSell
Script 1 ) CREATE TABLE CNF_SuggestiveSell_Permission
Script 2 ) CREATE fk_CNF_SuggestiveSell_Permission_SuggestiveSellId
Script 3 ) CREATE fk_CNF_SuggestiveSell_Permission_WorkstationId
Script 4 ) CREATE fk_CNF_SuggestiveSell_Permission_SiteId
Script 5 ) CREATE fk_CNF_SuggestiveSell_Permission_OperatingAreaId
Script 6 ) CREATE fk_CNF_SuggestiveSell_Permission_UserGroupId
Script 7 ) CREATE fk_CNF_SuggestiveSell_Permission_UserId
Script 8 ) CREATE TABLE CNF_SuggestiveSell2Event
Script 9 ) CREATE fk_CNF_SuggestiveSell2Event_SuggestiveSellId
Script 10 ) CREATE fk_CNF_SuggestiveSell2Event_EventId
Script 11 ) CREATE TABLE CNF_SuggestiveSell2MatrixCell
Script 12 ) CREATE fk_CNF_SuggestiveSell2MatrixCell_SuggestiveSellId
Script 13 ) CREATE fk_CNF_SuggestiveSell2MatrixCell_MatrixCellId
Script 14 ) CREATE TABLE CNF_SuggestiveSell2StatisticalGroup
Script 15 ) CREATE fk_CNF_SuggestiveSell2StatisticalGroup_SuggestiveSellId
Script 16 ) CREATE fk_CNF_SuggestiveSell2StatisticalGroup_StatisticalGroupId
Script 17 ) CREATE TABLE CNF_SuggestiveSell2EventCategory
Script 18 ) CREATE fk_CNF_SuggestiveSell2EventCategory_SuggestiveSellId
Script 19 ) CREATE fk_CNF_SuggestiveSell2EventCategory_PerformanceCategoryId
Script 20 ) CREATE fk_CNF_SuggestiveSell_DmgCategoryId</REASON>
			<TABLENAMES>CNF_SuggestiveSell=SuggestiveSellId
CNF_SuggestiveSell_Permission=SuggestiveSellPermissionId
CNF_SuggestiveSell2Event=SuggestiveSell2EventId
CNF_SuggestiveSell2MatrixCell=SuggestiveSell2MatrixCellId
CNF_SuggestiveSell2StatisticalGroup=SuggestiveSell2StatisticalGroupId
CNF_SuggestiveSell2EventCategory=SuggestiveSell2EventCategoryId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS ( SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND  TABLE_NAME = 'CNF_SuggestiveSell' )

BEGIN
Create table [CNF_SuggestiveSell]
(
	[SuggestiveSellId] Integer Identity(1,1) NOT NULL,
	[DmgCategoryId] Integer NULL,
	[SuggestiveSellAK] Nvarchar(32) NULL,
	[Code] Varchar(10) NULL,
	[Name] Varchar(50) NULL,
	[Description] Varchar(100) NULL,
	[Enabled] Smallint NULL,
	[Step] Integer NULL,
	[SortOrder] Integer NULL,
	[FixedQuantity] Smallint NULL,
	[SameDay] Smallint NULL,
Primary Key ([SuggestiveSellId])
) 
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS ( SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND  TABLE_NAME = 'CNF_SuggestiveSell_Permission' )

BEGIN
Create table [CNF_SuggestiveSell_Permission]
(
	[SuggestiveSellPermissionId] Integer Identity(1,1) NOT NULL,
	[SuggestiveSellId] Integer NOT NULL,
	[UserGroupId] Integer NULL,
	[UserId] Integer NULL,
	[WorkstationId] Integer NULL,
	[OperatingAreaId] Integer NULL,
	[SiteId] Integer NULL,
	[Allow] Smallint NOT NULL,
Primary Key ([SuggestiveSellPermissionId])
)
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_SuggestiveSell_Permission'
	          AND CONSTRAINT_NAME = N'fk_CNF_SuggestiveSell_Permission_SuggestiveSellId')          
BEGIN
  ALTER TABLE CNF_SuggestiveSell_Permission
  ADD CONSTRAINT [fk_CNF_SuggestiveSell_Permission_SuggestiveSellId] FOREIGN KEY([SuggestiveSellId])
  REFERENCES [CNF_SuggestiveSell] ([SuggestiveSellId])
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_SuggestiveSell_Permission'
	          AND CONSTRAINT_NAME = N'fk_CNF_SuggestiveSell_Permission_WorkstationId')          
BEGIN
  ALTER TABLE CNF_SuggestiveSell_Permission WITH CHECK
  ADD CONSTRAINT [fk_CNF_SuggestiveSell_Permission_WorkstationId] FOREIGN KEY([WorkstationId])
  REFERENCES [CNF_Workstation] ([WorkstationId])
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_SuggestiveSell_Permission'
	          AND CONSTRAINT_NAME = N'fk_CNF_SuggestiveSell_Permission_SiteId')          
BEGIN
  ALTER TABLE CNF_SuggestiveSell_Permission WITH CHECK
  ADD CONSTRAINT [fk_CNF_SuggestiveSell_Permission_SiteId] FOREIGN KEY([SiteId])
  REFERENCES [CNF_Site] ([SiteId])
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_SuggestiveSell_Permission'
	          AND CONSTRAINT_NAME = N'fk_CNF_SuggestiveSell_Permission_OperatingAreaId')          
BEGIN
  ALTER TABLE CNF_SuggestiveSell_Permission WITH CHECK
  ADD CONSTRAINT [fk_CNF_SuggestiveSell_Permission_OperatingAreaId] FOREIGN KEY([OperatingAreaId])
  REFERENCES [CNF_OperatingArea] ([OperatingAreaId])
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_SuggestiveSell_Permission'
	          AND CONSTRAINT_NAME = N'fk_CNF_SuggestiveSell_Permission_UserGroupId')          
BEGIN
  ALTER TABLE CNF_SuggestiveSell_Permission WITH CHECK
  ADD CONSTRAINT [fk_CNF_SuggestiveSell_Permission_UserGroupId] FOREIGN KEY([UserGroupId])
  REFERENCES [CNF_UserGroup] ([UserGroupId])
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_SuggestiveSell_Permission'
	          AND CONSTRAINT_NAME = N'fk_CNF_SuggestiveSell_Permission_UserGroupId')          
BEGIN
  ALTER TABLE CNF_SuggestiveSell_Permission WITH CHECK
  ADD CONSTRAINT [fk_CNF_SuggestiveSell_Permission_UserId] FOREIGN KEY([UserId])
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS ( SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND  TABLE_NAME = 'CNF_SuggestiveSell2Event' )

BEGIN
Create table [CNF_SuggestiveSell2Event]
(
	[SuggestiveSell2EventId] Integer Identity(1,1) NOT NULL,
	[SuggestiveSellId] Integer NOT NULL,
	[EventId] Integer NOT NULL,
	[Target] Smallint NULL,
Primary Key ([SuggestiveSell2EventId])
) 
END </SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_SuggestiveSell2Event'
	          AND CONSTRAINT_NAME = N'fk_CNF_SuggestiveSell2Event_SuggestiveSellId')          
BEGIN
  ALTER TABLE CNF_SuggestiveSell2Event WITH CHECK
  ADD CONSTRAINT [fk_CNF_SuggestiveSell2Event_SuggestiveSellId] FOREIGN KEY([SuggestiveSellId])
  REFERENCES [CNF_SuggestiveSell] ([SuggestiveSellId])
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_SuggestiveSell2Event'
	          AND CONSTRAINT_NAME = N'fk_CNF_SuggestiveSell2Event_EventId')          
BEGIN
  ALTER TABLE CNF_SuggestiveSell2Event WITH CHECK
  ADD CONSTRAINT [fk_CNF_SuggestiveSell2Event_EventId] FOREIGN KEY([EventId])
  REFERENCES [CNF_Event] ([EventId])
END </SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS ( SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND  TABLE_NAME = 'CNF_SuggestiveSell2MatrixCell' )

BEGIN
Create table [CNF_SuggestiveSell2MatrixCell]
(
	[SuggestiveSell2MatrixCellId] Integer Identity(1,1) NOT NULL,
	[SuggestiveSellId] Integer NOT NULL,
	[MatrixCellId] Integer NOT NULL,
	[Target] Smallint NULL,
Primary Key ([SuggestiveSell2MatrixCellId])
)
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_SuggestiveSell2MatrixCell'
	          AND CONSTRAINT_NAME = N'fk_CNF_SuggestiveSell2MatrixCell_SuggestiveSellId')          
BEGIN
  ALTER TABLE CNF_SuggestiveSell2MatrixCell WITH CHECK
  ADD CONSTRAINT [fk_CNF_SuggestiveSell2MatrixCell_SuggestiveSellId] FOREIGN KEY([SuggestiveSellId])
  REFERENCES [CNF_SuggestiveSell] ([SuggestiveSellId])
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_SuggestiveSell2MatrixCell'
	          AND CONSTRAINT_NAME = N'fk_CNF_SuggestiveSell2MatrixCell_MatrixCellId')          
BEGIN
  ALTER TABLE CNF_SuggestiveSell2MatrixCell WITH CHECK
  ADD CONSTRAINT [fk_CNF_SuggestiveSell2MatrixCell_MatrixCellId] FOREIGN KEY([MatrixCellId])
  REFERENCES [CNF_MatrixCell] ([MatrixCellId])
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS ( SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND  TABLE_NAME = 'CNF_SuggestiveSell2StatisticalGroup' )

BEGIN
Create table [CNF_SuggestiveSell2StatisticalGroup]
(
	[SuggestiveSell2StatisticalGroupId] Integer Identity(1,1) NOT NULL,
	[SuggestiveSellId] Integer NOT NULL,
	[StatisticalGroupId] Integer NOT NULL,
	[Target] Smallint NULL,
Primary Key ([SuggestiveSell2StatisticalGroupId])
)
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_SuggestiveSell2StatisticalGroup'
	          AND CONSTRAINT_NAME = N'fk_CNF_SuggestiveSell2StatisticalGroup_SuggestiveSellId')          
BEGIN
  ALTER TABLE CNF_SuggestiveSell2StatisticalGroup WITH CHECK
  ADD CONSTRAINT [fk_CNF_SuggestiveSell2StatisticalGroup_SuggestiveSellId] FOREIGN KEY([SuggestiveSellId])
  REFERENCES [CNF_SuggestiveSell] ([SuggestiveSellId])
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_SuggestiveSell2StatisticalGroup'
	          AND CONSTRAINT_NAME = N'fk_CNF_SuggestiveSell2StatisticalGroup_StatisticalGroupId')          
BEGIN
  ALTER TABLE CNF_SuggestiveSell2StatisticalGroup WITH CHECK
  ADD CONSTRAINT [fk_CNF_SuggestiveSell2StatisticalGroup_StatisticalGroupId] FOREIGN KEY([StatisticalGroupId])
  REFERENCES [CNF_StatisticalGroup] ([StatisticalGroupId])
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS ( SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND  TABLE_NAME = 'CNF_SuggestiveSell2EventCategory' )

BEGIN
Create table [CNF_SuggestiveSell2EventCategory]
(
	[SuggestiveSell2EventCategoryId] Integer Identity(1,1) NOT NULL,
	[Target] Smallint NULL,
	[SuggestiveSellId] Integer NOT NULL,
	[PerformanceCategoryId] Integer NOT NULL,
Primary Key ([SuggestiveSell2EventCategoryId])
) 
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_SuggestiveSell2EventCategory'
	          AND CONSTRAINT_NAME = N'fk_CNF_SuggestiveSell2EventCategory_SuggestiveSellId')          
BEGIN
  ALTER TABLE CNF_SuggestiveSell2EventCategory WITH CHECK
  ADD CONSTRAINT [fk_CNF_SuggestiveSell2EventCategory_SuggestiveSellId] FOREIGN KEY([SuggestiveSellId])
  REFERENCES [CNF_SuggestiveSell] ([SuggestiveSellId])
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_SuggestiveSell2EventCategory'
	          AND CONSTRAINT_NAME = N'fk_CNF_SuggestiveSell2EventCategory_PerformanceCategoryId')          
BEGIN
  ALTER TABLE CNF_SuggestiveSell2EventCategory WITH CHECK
  ADD CONSTRAINT [fk_CNF_SuggestiveSell2EventCategory_PerformanceCategoryId] FOREIGN KEY([PerformanceCategoryId])
  REFERENCES [CNF_PerformanceCategory] ([PerformanceCategoryId])
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_SuggestiveSell'
	          AND CONSTRAINT_NAME = N'fk_CNF_SuggestiveSell_DmgCategoryId')
BEGIN
  ALTER TABLE CNF_SuggestiveSell 
  ADD CONSTRAINT [fk_CNF_SuggestiveSell_DmgCategoryId] FOREIGN KEY([DmgCategoryId])
  REFERENCES [CNF_DmgCategory] ([DmgCategoryId])
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>pdalben</ADDEDBY>
			<SQLVERSION>2297</SQLVERSION>
			<RMTRACKLINK>65669</RMTRACKLINK>
			<REASON>-- Incremented size of  Params from 200 to 500</REASON>
			<TABLENAMES>CNF_Mask_Utility=MaskUtilityId
DATA_Account2CRM=Account2CRMId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
           WHERE Name = N'Params' AND
           Object_ID  = Object_ID(N'CNF_Mask_Utility'))
BEGIN
  ALTER TABLE CNF_Mask_Utility ALTER COLUMN [Params] nvarchar(500) NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST><SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'CRMGuid' AND
                Object_ID  = Object_ID(N'DATA_Account2CRM'))
BEGIN 
  ALTER TABLE DATA_Account2CRM ALTER COLUMN CRMGuid Varchar(38) NULL
END</SCRIPT></SQLSCRIPTLIST></SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>mkimball</ADDEDBY>
			<SQLVERSION>2296</SQLVERSION>
			<RMTRACKLINK>70657</RMTRACKLINK>
			<REASON>-- Change Account2CRM CRMGUID column to nullable</REASON>
			<TABLENAMES>DATA_Account2CRM=Account2CRMId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'CRMGuid' AND
                Object_ID  = Object_ID(N'DATA_Account2CRM'))
BEGIN 
  ALTER TABLE DATA_Account2CRM ALTER COLUMN CRMGuid Varchar(38) NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Federico Caramella</ADDEDBY>
			<SQLVERSION>2295</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.15.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************
			</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Federico Caramella</ADDEDBY>
			<SQLVERSION>2294</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.15.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************
			</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Federico Caramella</ADDEDBY>
			<SQLVERSION>2293</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Federico Caramella</ADDEDBY>
			<SQLVERSION>2292</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Federico Caramella</ADDEDBY>
			<SQLVERSION>2291</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Federico Caramella</ADDEDBY>
			<SQLVERSION>2290</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Federico Caramella</ADDEDBY>
			<SQLVERSION>2289</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Federico Caramella</ADDEDBY>
			<SQLVERSION>2288</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Federico Caramella</ADDEDBY>
			<SQLVERSION>2287</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Federico Caramella</ADDEDBY>
			<SQLVERSION>2286</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Federico Caramella</ADDEDBY>
			<SQLVERSION>2285</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Federico Caramella</ADDEDBY>
			<SQLVERSION>2284</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Federico Caramella</ADDEDBY>
			<SQLVERSION>2283</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Federico Caramella</ADDEDBY>
			<SQLVERSION>2282</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Federico Caramella</ADDEDBY>
			<SQLVERSION>2281</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Federico Caramella</ADDEDBY>
			<SQLVERSION>2280</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Federico Caramella</ADDEDBY>
			<SQLVERSION>2279</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Federico Caramella</ADDEDBY>
			<SQLVERSION>2278</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Federico Caramella</ADDEDBY>
			<SQLVERSION>2277</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.15.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************
			</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Federico Caramella</ADDEDBY>
			<SQLVERSION>2276</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.15.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************
			</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>jlaguardia</ADDEDBY>
			<SQLVERSION>2275</SQLVERSION>
			<RMTRACKLINK>70348</RMTRACKLINK>
			<REASON>+Added  table for notification job: DATA_Notification2Entitty</REASON>
			<TABLENAMES>DATA_Notification2Entity=Notification2EntityId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                WHERE TABLE_SCHEMA = 'dbo' 
                  AND  TABLE_NAME = 'DATA_Notification2Entity')

BEGIN
	create table [DATA_Notification2Entity]
(
		[Notification2EntityId] Integer Identity(1,1) NOT NULL, UNIQUE ([Notification2EntityId]),
		[NotificationId] Integer not null,
		[EntityTable] Integer not null,
		[EntityId] Integer not null,
		[Completed] Smallint,

		Primary Key ([Notification2EntityId]),
		Constraint FK_CNF_NotificationDATA_Notification2Entity Foreign Key ([NotificationId]) 
		References CNF_Notification([NotificationId])

)
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>kdixon</ADDEDBY>
			<SQLVERSION>2274</SQLVERSION>
			<RMTRACKLINK>64619</RMTRACKLINK>
			<REASON>Adding Stored Procedures used within RevenueRecogniition
</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_RR_RevenueData_PaymentMethodTaxDiscounts2]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_RR_RevenueData_PaymentMethodTaxDiscounts2



</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE Procedure dbo.otn_sp_RR_RevenueData_PaymentMethodTaxDiscounts2
	@BatchDate Date,
	@Transactions varchar(500),
	@Trigger int,
	@RRTransDateType Integer
AS 
BEGIN
	 
	Create Table #TransactionIDs(
	TransactionId Int NOT NULL)

	DECLARE @DelimPosition INT

    SET @DelimPosition = CHARINDEX(',', @Transactions)

    WHILE @DelimPosition &gt; 0
    BEGIN
        INSERT INTO #TransactionIDs(TransactionId)
            VALUES(CAST(RTRIM(LEFT(@Transactions, @DelimPosition - 1)) AS INT))
        SET @Transactions = right(@Transactions, len(@Transactions) - @DelimPosition)

        SET @DelimPosition = CHARINDEX(',', @Transactions)
    END


	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer

	Declare @OnCreditWriteoff Integer = 9
	Declare @StartTime DateTime

	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1
	

		--Normal Sale Split out the Payments to Smaller Subset.
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])				    
						select distinct COA.COAAccountId, 
								p.RevenueRecognitionRuleId,
								p.code,		   
								p.RRCalcTypeWhere,
								p.RRCalcTypeMethod,	   
								p.COAAccountConfigId,
								p.COAAccountTypeId,
								COA.Code,
								RR_DATA_REVENUE.Transactionid as Transactionid,
								RR_DATA_REVENUE.saleid as Saleid,
								RR_DATA_REVENUE.Siteid as SiteID,
								RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								RR_DATA_REVENUE.Workstationid as Workstationid,
								RR_DATA_REVENUE.UserGroupid as UserGroupID,
								RR_DATA_REVENUE.UserId as userID,
								@BatchDate as BatchDate,
							   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
									else DATA_Transaction.transactiondate
							   end as TransDate,
								0 as Quantity,
								0 as GrossAmount,
								0 as NetAmount,
								0 as ConfigPrice,
								100 as ConfigPercentage,
								0 RemainingValues,	
								ABS ((data_payment.PaymentAmount + data_payment.PaymentFee) - 
							   (case when data_payment.paymentid = (select top 1 paymentid
																	from data_payment
																	where transactionid = RR_DATA_REVENUE.Transactionid
																		and data_payment.paymentamount &gt; (select sum(Change) *-1
																									from data_transaction
																									where data_transaction.transactionid = RR_DATA_REVENUE.Transactionid))
									then (select sum(Change) *-1
																									from data_transaction
																									where data_transaction.transactionid = RR_DATA_REVENUE.Transactionid)
									else 0
								end ))
								as RevenueAmount,
							--	p.Accountingtype,		
								case    when DATA_Transaction.TransactionType in (5, 8, 17, 18, 20, 22, 30) and p.Accountingtype = 1 then 2
										when DATA_Transaction.TransactionType in (5, 8, 17, 18, 20, 22, 30) and p.Accountingtype = 2 then 1
										when DATA_Transaction.TransactionType in (7) and (RR_DATA_REVENUE.revenueAmount) &lt;= 0  then 1
										when DATA_Transaction.TransactionType in (7) and (RR_DATA_REVENUE.revenueAmount) &gt; 0  then 2
										else p.Accountingtype
								end Accountingtype,
							   p.RRCalcTypeTrigger,
							   p.RRPercentage,
							   p.Days
								from RR_DATA_REVENUE
									INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
									INNER JOIN (select '1' as PCOAAccountid, 
													   coa_cnf_accountConfig.Siteid, 
													   RR_CNF_RevenueRecognitionRule.Enabled, 
													   RR_CNF_RevenueRecognitionRule.FromDate, 
													   RR_CNF_RevenueRecognitionRule.ToDate,
													   COA_CNF_AccountConfig.RemainingValues,
													   coa_cnf_account.coaaccountid,
													   COA_CNF_AccountConfig.Price,
													   COA_CNF_AccountConfig.Percentage,
													   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
													   RR_CNF_RevenueRecognitionRule.code,		   
													   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
													   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
													   COA_CNF_AccountConfig.COAAccountConfigId,
													   coa_cnf_account.COAAccountTypeId,
													   coa_cnf_account.Code as accountcode,
													   coa_cnf_accountconfig.Accountingtype,
													   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
													   RR_CNF_RevenueRecognitionRule.Percentage rrPercentage,
													   RR_CNF_RevenueRecognitionRule.Days	

													from RR_CNF_RevenueRecognitionRule	
													INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
													INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid and coa_cnf_account.Enabled = 1
													INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
												where  RR_CNF_RevenueRecognitionRule.Enabled = 1
												and coa_cnf_account.coaaccountid in (@ACCPaymentMethod)) p				on p.PCOAAccountid = rr_data_revenue.coaaccountid 
							INNER JOIN data_payment							on data_payment.transactionid = rr_data_revenue.transactionid
							left  JOIN DATA_PaymentCard						on data_paymentcard.paymentid = data_payment.PaymentId
							left JOIN CNF_PaymentCard						on cnf_paymentcard.paymentcardid = data_paymentcard.paymentcardid
							INNER JOIN CNF_PaymentMethod					on CNF_PaymentMethod.PaymentMethodId = data_payment.PaymentMethodId
							INNER JOIN COA_CNF_Account COA					on COA.COAAccountid = ISNULL(cnf_paymentcard.coaaccountid, CNF_PaymentMethod.COAAccountid)


						where data_payment.paymentstatus = 1
					and DATA_Transaction.TransactionType in (select transactionid
																from #TransactionIDs)
						and RR_DATA_REVENUE.fcalcdate = @BatchDate
						and @BatchDate between p.FromDate and p.ToDate
						AND data_payment.Transactionid not in (select distinct transactionid
													from rr_Data_Revenue
													where coaaccountid in (select distinct coaaccountid
																				from cnf_paymentmethod CP
																				where coaaccountid is not null
																				union all
																				select distinct coaaccountid
																				from cnf_paymentcard pc
																				where coaaccountid is not null
																			)
													)
						AND data_payment.Transactionid in (select distinct transactionid
													from rr_Data_Revenue
													where coaaccountid in (@ACCPaymentMethod)
													)
						 AND RR_DATA_REVENUE.coaaccountid not in (@ACCPaymentMethod)


		----Normal Sale Split out the Payments to Payment Fees
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])				    
				select distinct COA.COAAccountId, 
						   p.RevenueRecognitionRuleId,
						   p.RRCode,		   
						   p.RRCalcTypeWhere,
						   p.RRCalcTypeMethod,	   
						   p.COAAccountConfigId,
						   COA.COAAccountTypeId,
						   COA.Code,
						   RR_DATA_REVENUE.Transactionid as Transactionid,
						   RR_DATA_REVENUE.saleid as Saleid,
						   RR_DATA_REVENUE.Siteid as SiteID,
						   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
						   RR_DATA_REVENUE.Workstationid as Workstationid,
						   RR_DATA_REVENUE.UserGroupid as UserGroupID,
						   RR_DATA_REVENUE.UserId as userID,
						   @BatchDate,
						   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
							    else DATA_Transaction.transactiondate
						   end as TransDate,
						   0,
						   0,
						   0,
						   0,
						   100,
						   0,  	
						   data_payment.paymentfee as RevenueAmount,
						   case when data_payment.paymentfee &gt;= 0 then 2
						        else 1
							end accountingtype,		
						   p.RRCalcTypeTrigger,
						   p.RRPercentage,
						   p.RRDays

						from RR_DATA_REVENUE
						inner join rr_cnf_Product						ON ((RR_DATA_REVENUE.MATRIXCELLID = rr_cnf_Product.MATRIXCELLID) or (RR_DATA_REVENUE.MatrixSheetId = rr_cnf_Product.MatrixSheetId)) and rr_cnf_Product.Enabled = 1
						inner join RR_CNF_RevenueRecognitionRule		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_cnf_Product.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  
						INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
						INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
						INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 
						INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
						INNER JOIN data_payment							on data_payment.transactionid = rr_data_revenue.transactionid
						left  JOIN DATA_PaymentCard						on data_paymentcard.paymentid = data_payment.PaymentId
						left JOIN CNF_PaymentCard						on cnf_paymentcard.paymentcardid = data_paymentcard.paymentcardid
						INNER JOIN CNF_PaymentMethod					on CNF_PaymentMethod.PaymentMethodId = data_payment.PaymentMethodId
						INNER JOIN COA_CNF_Account COA					on COA.COAAccountid = CNF_PaymentMethod.FeeCOAAccountId

						INNER JOIN (select transactionid, RevenueRecognitionRuleId, RR_DATA_Revenue.RRCode, RRCalcTypeWhere, 
											RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount,  Accountingtype
											from RR_DATA_Revenue
											INNER JOIN COA_CNF_Account		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
											where COA_CNF_Account.coaAccountID = @ACCPaymentMethod
										)p    on p.transactionid = 	data_payment.transactionid

					where data_payment.paymentstatus = 1
					and DATA_Transaction.TransactionType in (select transactionid
																from #TransactionIDs)
					and data_payment.paymentfee &lt;&gt; 0
					and RR_DATA_REVENUE.fcalcdate = @BatchDate
					and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
					AND data_payment.Transactionid not in (select distinct transactionid
												from rr_Data_Revenue
												where coaaccountid in (select distinct FeeCOAAccountId
																			from cnf_paymentmethod CP
																		)
												)
					AND data_payment.Transactionid in (select distinct transactionid
												from rr_Data_Revenue
												where coaaccountid in (@ACCPaymentMethod)
												)


							


		--	--Normal Transactions Reverse out of PaymentMethods
			INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])				    					
				   select COAAccountId, 
						   Max(RevenueRecognitionRuleId),
						   Max(RRCode),		   
						   RRCalcTypeWhere,
						   RRCalcTypeMethod,	   
						   Max(COAAccountConfigId),
						   COAAccountTypeId,
						   COAAccountCode,
						   Transactionid,
						   saleid,
						   Siteid,
						   OperatingAreaId,
						   Workstationid,
						   UserGroupid,
						   UserId,
						   batchdate,
						   TransDate,
						   0,
						   0,
						   0,						
						   0,
						   0,
						   0,
						   ABS(sum(RevenueAmount)) *-1 as RevenueAmount,
				           Accountingtype,		
						   RRCalcTypeTrigger,
						   RRPercentage,
						   RRDays
						   from (
							select distinct 
								       p.COAAccountId, 
									   p.RevenueRecognitionRuleId,
									   p.RRCode,		   
									   p.RRCalcTypeWhere,
									   p.RRCalcTypeMethod,	   
									   p.COAAccountConfigId,
									  p.COAAccountTypeId,
									   p.COAAccountCode,
									   rr_data_Revenue.Transactionid Transactionid,
									   rr_data_Revenue.saleid saleid,
									   rr_data_Revenue.Siteid siteid,
									   rr_data_Revenue.OperatingAreaId OperatingAreaid,
									   rr_data_Revenue.Workstationid workstationid,
									   rr_data_Revenue.UserGroupid usergroupid,
									   rr_data_Revenue.UserId userid,
									   @BatchDate batchdate,
									   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
											else DATA_Transaction.transactiondate
									   end as TransDate,
									   rr_data_Revenue.RevenueAmount *-1  as RevenueAmount,
								       p.Accountingtype,
									   transactiontype,		
									   p.RRCalcTypeTrigger,
									   p.RRPercentage,
									   p.RRDays
							FROM rr_data_Revenue   				        WITH (NOLOCK)
								   INNER JOIN (select saleid, transactionid, RevenueRecognitionRuleId, RR_DATA_Revenue.RRCode, RRCalcTypeWhere, Saleitemid, RR_DATA_Revenue.COAAccountId, 
													   RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount, COA_CNF_Account.COAAccountTypeId,  Accountingtype,
													   RR_DATA_Revenue.COAAccountCode
													  from RR_DATA_Revenue
														INNER JOIN COA_CNF_Account		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
													 where COA_CNF_Account.coaAccountID = @ACCPaymentMethod
													   --and rr_data_revenue.RRCalcTypeTrigger = @Trigger
													)p								ON p.transactionid = 	rr_data_Revenue.transactionid
									INNER JOIN DATA_Transaction			on data_transaction.transactionid = rr_data_revenue.transactionid
							where RR_DATA_REVENUE.fcalcdate = @BatchDate
							  and DATA_Transaction.TransactionType in (select transactionid
																from #TransactionIDs)
							  and rr_data_Revenue.coaaccountid in (select distinct coaaccountid
																	 from cnf_paymentmethod
																	 where coaaccountid is not null
																	union all
																   select distinct coaaccountid
																	 from cnf_paymentcard
																	 where coaaccountid is not null
																  )
						)r	
							group by	 COAAccountId, 		   
									   RRCalcTypeWhere,
									   RRCalcTypeMethod,	   
									   COAAccountTypeId,
									   COAAccountCode,
									   Transactionid,
									   saleid,
									   Siteid,
									   OperatingAreaId,
									   Workstationid,
									   UserGroupid,
									   UserId,
									   batchdate,
									   TransDate,					
									   Accountingtype,		
									   RRCalcTypeTrigger,
									   RRPercentage,
									   RRDays, TransactionType


----Normal Sale Split out the Payments to Payment Fees
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])				    
				select distinct COA.COAAccountId, 
						   p.RevenueRecognitionRuleId,
						   p.RRCode,		   
						   p.RRCalcTypeWhere,
						   p.RRCalcTypeMethod,	   
						   p.COAAccountConfigId,
						   COA.COAAccountTypeId,
						   COA.Code,
						   RR_DATA_REVENUE.Transactionid as Transactionid,
						   RR_DATA_REVENUE.saleid as Saleid,
						   RR_DATA_REVENUE.Siteid as SiteID,
						   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
						   RR_DATA_REVENUE.Workstationid as Workstationid,
						   RR_DATA_REVENUE.UserGroupid as UserGroupID,
						   RR_DATA_REVENUE.UserId as userID,
						   @BatchDate,
						   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
							    else DATA_Transaction.transactiondate
						   end as TransDate,
						   0,
						   0,
						   0,
						   0,
						   100,
						   0,  	
						  ABS(data_ledger.entryAmount) as RevenueAmount,
							case when data_ledger.entryAmount &gt;= 0 then 1
								else 2
							end accountingtype,		
							p.RRCalcTypeTrigger,
							p.RRPercentage,
							p.RRDays

						from RR_DATA_REVENUE
						inner join rr_cnf_Product						ON ((RR_DATA_REVENUE.MATRIXCELLID = rr_cnf_Product.MATRIXCELLID) or (RR_DATA_REVENUE.MatrixSheetId = rr_cnf_Product.MatrixSheetId)) and rr_cnf_Product.Enabled = 1
						inner join RR_CNF_RevenueRecognitionRule		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_cnf_Product.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  

						INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
						INNER JOIN data_payment							on data_payment.transactionid = rr_data_revenue.transactionid
						left  JOIN DATA_PaymentCard						on data_paymentcard.paymentid = data_payment.PaymentId
						left JOIN CNF_PaymentCard						on cnf_paymentcard.paymentcardid = data_paymentcard.paymentcardid
						INNER JOIN CNF_PaymentMethod					on CNF_PaymentMethod.PaymentMethodId = data_payment.PaymentMethodId
						INNER JOIN COA_CNF_Account COA					on COA.COAAccountid = CNF_PaymentMethod.returnedcheckcoaaccountid
						INNER JOIN data_ledger							ON data_ledger.transactionid = data_transaction.transactionid
						INNER JOIN cnf_ledgeraccount					ON cnf_ledgeraccount.LedgerAccountId = data_ledger.ledgeraccountid
												INNER JOIN (select transactionid, RevenueRecognitionRuleId, RR_DATA_Revenue.RRCode, RRCalcTypeWhere, 
																	RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount,  Accountingtype
																	from RR_DATA_Revenue
																	INNER JOIN COA_CNF_Account		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
																	where COA_CNF_Account.coaAccountID = @ACCPaymentMethod
																)p    on p.transactionid = 	data_payment.transactionid


						where data_payment.paymentstatus = 1
							and DATA_Transaction.TransactionType in (select transactionid
																from #TransactionIDs)
							and DATA_Transaction.tip &lt;&gt; 0
							and RR_DATA_REVENUE.fcalcdate = @BatchDate
							and systemaccounttable = 119
							and systemaccountid = 15
							and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
							
																			
		End
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_RR_RevenueData_PaymentMethodTaxDiscounts]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_RR_RevenueData_PaymentMethodTaxDiscounts
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE Procedure dbo.otn_sp_RR_RevenueData_PaymentMethodTaxDiscounts
	@BatchDate Date,
	@Transactions varchar(500),
	@Trigger int,
	@RRTransDateType integer
AS 
BEGIN
	 
	Create Table #TransactionIDs(
	TransactionId Int NOT NULL)

	DECLARE @DelimPosition INT

    SET @DelimPosition = CHARINDEX(',', @Transactions)

    WHILE @DelimPosition &gt; 0
    BEGIN
        INSERT INTO #TransactionIDs(TransactionId)
            VALUES(CAST(RTRIM(LEFT(@Transactions, @DelimPosition - 1)) AS INT))
        SET @Transactions = right(@Transactions, len(@Transactions) - @DelimPosition)

        SET @DelimPosition = CHARINDEX(',', @Transactions)
    END

	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer

	Declare @OnCreditWriteoff Integer = 9
	Declare @StartTime DateTime

	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1
	

		--	--	--Normal Sale Split out the Payments to Smaller Subset.
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])				    
						select distinct COA.COAAccountId, 
						   p.RevenueRecognitionRuleId,
						   p.RRCode,		   
						   p.RRCalcTypeWhere,
						   p.RRCalcTypeMethod,	   
						   p.COAAccountConfigId,
						   COA.COAAccountTypeId,
						   COA.Code,
						   RR_DATA_REVENUE.Transactionid as Transactionid,
						   RR_DATA_REVENUE.saleid as Saleid,
						   RR_DATA_REVENUE.Siteid as SiteID,
						   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
						   RR_DATA_REVENUE.Workstationid as Workstationid,
						   RR_DATA_REVENUE.UserGroupid as UserGroupID,
						   RR_DATA_REVENUE.UserId as userID,
						   @BatchDate,
						   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
							    else DATA_Transaction.transactiondate
						   end as TransDate,
						   0,
						   0,
						   0,
						   0,
						   100,
						   0, 	
						   ABS ((data_payment.PaymentAmount) -
						   (case when data_payment.paymentid = (select top 1 paymentid
																from data_payment
																where transactionid = RR_DATA_REVENUE.Transactionid
																	and data_payment.paymentamount &gt; (select sum(Change) *-1
																								from data_transaction
																								where data_transaction.transactionid = RR_DATA_REVENUE.Transactionid))
								then (select sum(Change) *-1
																								from data_transaction
																								where data_transaction.transactionid = RR_DATA_REVENUE.Transactionid)
								else 0
							end ))
							as RevenueAmount,
							p.Accountingtype,		
						    p.RRCalcTypeTrigger,
						    p.RRPercentage,
						    p.RRDays

						from RR_DATA_REVENUE
						inner join rr_cnf_Product						ON ((RR_DATA_REVENUE.MATRIXCELLID = rr_cnf_Product.MATRIXCELLID) or (RR_DATA_REVENUE.MatrixSheetId = rr_cnf_Product.MatrixSheetId)) and rr_cnf_Product.Enabled = 1
						inner join RR_CNF_RevenueRecognitionRule		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_cnf_Product.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  
						INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
						INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
						INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 
						INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
						INNER JOIN data_payment							on data_payment.transactionid = rr_data_revenue.transactionid
						left  JOIN DATA_PaymentCard						on data_paymentcard.paymentid = data_payment.PaymentId
						left JOIN CNF_PaymentCard						on cnf_paymentcard.paymentcardid = data_paymentcard.paymentcardid
						INNER JOIN CNF_PaymentMethod					on CNF_PaymentMethod.PaymentMethodId = data_payment.PaymentMethodId
						INNER JOIN COA_CNF_Account COA					on COA.COAAccountid = ISNULL(cnf_paymentcard.coaaccountid, CNF_PaymentMethod.COAAccountid)

						INNER JOIN (select transactionid, RevenueRecognitionRuleId, RR_DATA_Revenue.RRCode, RRCalcTypeWhere, 
											RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount,  Accountingtype
											from RR_DATA_Revenue
											INNER JOIN COA_CNF_Account		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
											where COA_CNF_Account.coaAccountID = @ACCPaymentMethod
											--and RR_DATA_Revenue.RRCalcTypeTrigger = @Trigger
											and RR_DATA_REVENUE.fcalcdate = @BatchDate
										)p    on p.transactionid = 	data_payment.transactionid

					where data_payment.paymentstatus = 1
					and DATA_Transaction.TransactionType in (select transactionid
																from #TransactionIDs)
					and RR_DATA_REVENUE.fcalcdate = @BatchDate
					and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
					AND data_payment.Transactionid not in (select distinct transactionid
												from rr_Data_Revenue
												where coaaccountid in (select distinct coaaccountid
																			from cnf_paymentmethod CP
																			where coaaccountid is not null
																			union all
																			select distinct coaaccountid
																			from cnf_paymentcard pc
																			where coaaccountid is not null
																		)
												)
					AND data_payment.Transactionid in (select distinct transactionid
												from rr_Data_Revenue
												where coaaccountid in (@ACCPaymentMethod)
												)
					 AND RR_DATA_REVENUE.coaaccountid not in (@ACCPaymentMethod)


		----Normal Sale Split out the Payments to Payment Fees
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])				    
				select distinct COA.COAAccountId, 
						   p.RevenueRecognitionRuleId,
						   p.RRCode,		   
						   p.RRCalcTypeWhere,
						   p.RRCalcTypeMethod,	   
						   p.COAAccountConfigId,
						   COA.COAAccountTypeId,
						   COA.Code,
						   RR_DATA_REVENUE.Transactionid as Transactionid,
						   RR_DATA_REVENUE.saleid as Saleid,
						   RR_DATA_REVENUE.Siteid as SiteID,
						   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
						   RR_DATA_REVENUE.Workstationid as Workstationid,
						   RR_DATA_REVENUE.UserGroupid as UserGroupID,
						   RR_DATA_REVENUE.UserId as userID,
						   @BatchDate,
						   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
							    else DATA_Transaction.transactiondate
						   end as TransDate,
						   0,
						   0,
						   0,
						   0,
						   100,
						   0,  	
						   data_payment.paymentfee as RevenueAmount,
						   case when data_payment.paymentfee &gt;= 0 then 2
						        else 1
							end accountingtype,		
						   p.RRCalcTypeTrigger,
						   p.RRPercentage,
						   p.RRDays

						from RR_DATA_REVENUE
						inner join rr_cnf_Product						ON ((RR_DATA_REVENUE.MATRIXCELLID = rr_cnf_Product.MATRIXCELLID) or (RR_DATA_REVENUE.MatrixSheetId = rr_cnf_Product.MatrixSheetId)) and rr_cnf_Product.Enabled = 1
						inner join RR_CNF_RevenueRecognitionRule		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_cnf_Product.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  
						INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
						INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
						INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 
						INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
						INNER JOIN data_payment							on data_payment.transactionid = rr_data_revenue.transactionid
						left  JOIN DATA_PaymentCard						on data_paymentcard.paymentid = data_payment.PaymentId
						left JOIN CNF_PaymentCard						on cnf_paymentcard.paymentcardid = data_paymentcard.paymentcardid
						INNER JOIN CNF_PaymentMethod					on CNF_PaymentMethod.PaymentMethodId = data_payment.PaymentMethodId
						INNER JOIN COA_CNF_Account COA					on COA.COAAccountid = CNF_PaymentMethod.FeeCOAAccountId

						INNER JOIN (select transactionid, RevenueRecognitionRuleId, RR_DATA_Revenue.RRCode, RRCalcTypeWhere, 
											RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount,  Accountingtype
											from RR_DATA_Revenue
											INNER JOIN COA_CNF_Account		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
											where COA_CNF_Account.coaAccountID = @ACCPaymentMethod
										)p    on p.transactionid = 	data_payment.transactionid

					where data_payment.paymentstatus = 1
					and DATA_Transaction.TransactionType in (select transactionid
																from #TransactionIDs)
					and data_payment.paymentfee &lt;&gt; 0
					and RR_DATA_REVENUE.fcalcdate = @BatchDate
					and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
					AND data_payment.Transactionid not in (select distinct transactionid
												from rr_Data_Revenue
												where coaaccountid in (select distinct FeeCOAAccountId
																			from cnf_paymentmethod CP
																		)
												)
					AND data_payment.Transactionid in (select distinct transactionid
												from rr_Data_Revenue
												where coaaccountid in (@ACCPaymentMethod)
												)


		--	--Normal Transactions Reverse out of PaymentMethods
			INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])				    					
					select COAAccountId, 
						   Max(RevenueRecognitionRuleId),
						   Max(RRCode),		   
						   RRCalcTypeWhere,
						   RRCalcTypeMethod,	   
						   Max(COAAccountConfigId),
						   COAAccountTypeId,
						   COAAccountCode,
						   Transactionid,
						   saleid,
						   Siteid,
						   OperatingAreaId,
						   Workstationid,
						   UserGroupid,
						   UserId,
						   batchdate,
						   TransDate,
						   0,
						   0,
						   0,						
						   0,
						   0,
						   0,
						   ABS(sum(RevenueAmount)) *-1 as RevenueAmount,
				           Accountingtype,		
						   RRCalcTypeTrigger,
						   RRPercentage,
						   RRDays
						   from (
			select distinct rr_data_Revenue.coaaccountid as rrcoaaccountid,
								       p.COAAccountId, 
									   p.RevenueRecognitionRuleId,
									   p.RRCode,		   
									   p.RRCalcTypeWhere,
									   p.RRCalcTypeMethod,	   
									   p.COAAccountConfigId,
									   p.COAAccountTypeId,
									   p.COAAccountCode,
									   rr_data_Revenue.Transactionid Transactionid,
									   rr_data_Revenue.saleid saleid,
									   rr_data_Revenue.Siteid siteid,
									   rr_data_Revenue.OperatingAreaId OperatingAreaid,
									   rr_data_Revenue.Workstationid workstationid,
									   rr_data_Revenue.UserGroupid usergroupid,
									   rr_data_Revenue.UserId userid,
									   @BatchDate batchdate,
									   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
											else DATA_Transaction.transactiondate
									   end as TransDate,
									   rr_data_Revenue.RevenueAmount *-1  as RevenueAmount,
								       p.Accountingtype,
									   transactiontype,		
									   p.RRCalcTypeTrigger,
									   p.RRPercentage,
									   p.RRDays
							FROM rr_data_Revenue   				        WITH (NOLOCK)
								   INNER JOIN (select saleid, transactionid, RevenueRecognitionRuleId, RR_DATA_Revenue.RRCode, RRCalcTypeWhere, Saleitemid, RR_DATA_Revenue.COAAccountId, 
													   RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount, COA_CNF_Account.COAAccountTypeId,  Accountingtype,
													   RR_DATA_Revenue.COAAccountCode
													  from RR_DATA_Revenue
														INNER JOIN COA_CNF_Account		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
													 where COA_CNF_Account.coaAccountID = @ACCPaymentMethod
													-- and rr_data_Revenue.RRCalcTypeTrigger = @Trigger
													)p								ON p.transactionid = 	rr_data_Revenue.transactionid
									INNER JOIN DATA_Transaction			on data_transaction.transactionid = rr_data_revenue.transactionid
							where RR_DATA_REVENUE.fcalcdate = @BatchDate
							  
							  and DATA_Transaction.TransactionType in (select transactionid
																from #TransactionIDs)
							  and rr_data_Revenue.coaaccountid in (select distinct coaaccountid
																	 from cnf_paymentmethod
																	 where coaaccountid is not null
																	union all
																   select distinct coaaccountid
																	 from cnf_paymentcard
																	 where coaaccountid is not null

																  )
						)r	
							group by	 COAAccountId, 		   
									   RRCalcTypeWhere,
									   RRCalcTypeMethod,	   
									   COAAccountTypeId,
									   COAAccountCode,
									   Transactionid,
									   saleid,
									   Siteid,
									   OperatingAreaId,
									   Workstationid,
									   UserGroupid,
									   UserId,
									   batchdate,
									   TransDate,					
									   Accountingtype,		
									   RRCalcTypeTrigger,
									   RRPercentage,
									   RRDays, TransactionType
							

----Normal Sale Split out the Payments to Payment Fees
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])				    
				select distinct COA.COAAccountId, 
						   p.RevenueRecognitionRuleId,
						   p.RRCode,		   
						   p.RRCalcTypeWhere,
						   p.RRCalcTypeMethod,	   
						   p.COAAccountConfigId,
						   COA.COAAccountTypeId,
						   COA.Code,
						   RR_DATA_REVENUE.Transactionid as Transactionid,
						   RR_DATA_REVENUE.saleid as Saleid,
						   RR_DATA_REVENUE.Siteid as SiteID,
						   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
						   RR_DATA_REVENUE.Workstationid as Workstationid,
						   RR_DATA_REVENUE.UserGroupid as UserGroupID,
						   RR_DATA_REVENUE.UserId as userID,
						   @BatchDate,
						   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
							    else DATA_Transaction.transactiondate
						   end as TransDate,
						   0,
						   0,
						   0,
						   0,
						   100,
						   0,  	
						  ABS(data_ledger.entryAmount) as RevenueAmount,
							case when data_ledger.entryAmount &gt;= 0 then 1
								else 2
							end accountingtype,		
							p.RRCalcTypeTrigger,
							p.RRPercentage,
							p.RRDays

						from RR_DATA_REVENUE
						inner join rr_cnf_Product						ON ((RR_DATA_REVENUE.MATRIXCELLID = rr_cnf_Product.MATRIXCELLID) or (RR_DATA_REVENUE.MatrixSheetId = rr_cnf_Product.MatrixSheetId)) and rr_cnf_Product.Enabled = 1
						inner join RR_CNF_RevenueRecognitionRule		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_cnf_Product.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  

						INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
						INNER JOIN data_payment							on data_payment.transactionid = rr_data_revenue.transactionid
						left  JOIN DATA_PaymentCard						on data_paymentcard.paymentid = data_payment.PaymentId
						left JOIN CNF_PaymentCard						on cnf_paymentcard.paymentcardid = data_paymentcard.paymentcardid
						INNER JOIN CNF_PaymentMethod					on CNF_PaymentMethod.PaymentMethodId = data_payment.PaymentMethodId
						INNER JOIN COA_CNF_Account COA					on COA.COAAccountid = CNF_PaymentMethod.returnedcheckcoaaccountid
						INNER JOIN data_ledger							ON data_ledger.transactionid = data_transaction.transactionid
						INNER JOIN cnf_ledgeraccount					ON cnf_ledgeraccount.LedgerAccountId = data_ledger.ledgeraccountid
												INNER JOIN (select transactionid, RevenueRecognitionRuleId, RR_DATA_Revenue.RRCode, RRCalcTypeWhere, 
																	RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount,  Accountingtype
																	from RR_DATA_Revenue
																	INNER JOIN COA_CNF_Account		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
																	where COA_CNF_Account.coaAccountID = @ACCPaymentMethod
																)p    on p.transactionid = 	data_payment.transactionid


						where data_payment.paymentstatus = 1
							and DATA_Transaction.TransactionType in (select transactionid
																from #TransactionIDs)
							and DATA_Transaction.tip &lt;&gt; 0
							and RR_DATA_REVENUE.fcalcdate = @BatchDate
							and systemaccounttable = 119
							and systemaccountid = 15
							and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate

				--Normal Transaction break out Tax
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])				    
						  select COAAccountId, 
						   Max(RevenueRecognitionRuleId),
						   Max(Code),		   
						   RRCalcTypeWhere,
						   RRCalcTypeMethod,	   
						   COAAccountConfigId,
						   COAAccountTypeId,
						   COACODE,
						   Transactionid,
						   saleid,
						   Siteid,
						   OperatingAreaId,
						   Workstationid,
						   UserGroupid,
						   UserId,
						   batchdate,
						   TransDate,
						   0,
						   0,
						   0,						
						   price,
						   percentage,
						   test,
						   ABS(sum(RevenueAmount)) as RevenueAmount,
				           case when TransactionType in (5, 17, 18, 20, 22, 30) and sum(RevenueAmount) &lt;= 0  then 1
						        when TransactionType in (5, 17, 18, 20, 22, 30) and sum(RevenueAmount) &lt;= 0  then 2
								when TransactionType in (7) and sum(RevenueAmount) &lt;= 0  then 1
								when TransactionType in (7) and sum(RevenueAmount) &gt; 0  then 2
								else Accountingtype
							end Accountingtype,		
						   RRCalcTypeTrigger,
						   RRPercentage,
						   RRDays
						   
						   from (
						  select distinct COA.COAAccountId, 
						   max(RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId) RevenueRecognitionRuleId,
						   max(RR_CNF_RevenueRecognitionRule.code) code,		   
						   RR_DATA_REVENUE.RRCalcTypeWhere,
						   RR_DATA_REVENUE.RRCalcTypeMethod,	   
						   RR_DATA_REVENUE.COAAccountConfigId,
						   COA.COAAccountTypeId,
						   COA.Code COACODE,
						   RR_DATA_REVENUE.Transactionid as Transactionid,
						   RR_DATA_REVENUE.saleid as Saleid,
						   RR_DATA_REVENUE.Siteid as SiteID,
						   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
						   RR_DATA_REVENUE.Workstationid as Workstationid,
						   RR_DATA_REVENUE.UserGroupid as UserGroupID,
						   RR_DATA_REVENUE.UserId as userID,
						   @BatchDate as batchdate,
						   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
							    else DATA_Transaction.transactiondate
						   end as TransDate,
						   0 as Quantity,
						   0 as GrossAmount,
						   0 as NetAmount,
						   0 as price,
						   100 as percentage,
						   0 as test, 	
						   taxamount RevenueAmount,
						   Transactiontype,
							p.Accountingtype,					   		
						   RR_DATA_REVENUE.RRCalcTypeTrigger,
						   RR_DATA_REVENUE.RRPercentage,
						   RR_DATA_REVENUE.RRDays

					from RR_DATA_REVENUE
						inner join rr_cnf_Product						ON ((RR_DATA_REVENUE.MATRIXCELLID = rr_cnf_Product.MATRIXCELLID) or (RR_DATA_REVENUE.MatrixSheetId = rr_cnf_Product.MatrixSheetId)) and rr_cnf_Product.Enabled = 1
						inner join RR_CNF_RevenueRecognitionRule		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_cnf_Product.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  
						INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
						INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
						INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 
						INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
						INNER JOIN DATA_TransactionTax					on data_transactiontax.transactionid = data_transaction.transactionid
						INNER JOIN CNF_Tax								on cnf_tax.taxid = DATA_TransactionTax.taxid
						INNER JOIN coa_cnf_account coa					on coa.coaaccountid = cnf_tax.coaaccountid
							INNER JOIN (select saleid, transactionid, RevenueRecognitionRuleId, RR_DATA_Revenue.RRCode, RRCalcTypeWhere, Saleitemid, RR_DATA_Revenue.coaaccountid,
												RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount,  Accountingtype
												from RR_DATA_Revenue
												INNER JOIN COA_CNF_Account		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
												where COA_CNF_Account.coaAccountID = @TaxAccountID
												--and rr_data_Revenue.RRCalcTypeTrigger = @Trigger
												and RR_DATA_REVENUE.fcalcdate = @BatchDate
											)p    on p.transactionid = 	data_transactiontax.transactionid
					where RR_DATA_REVENUE.coaaccountid = 1
					and RR_DATA_REVENUE.fcalcdate = @BatchDate
					and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @Trigger
					and TransactionType in (select transactionid
														from #TransactionIDs)
					and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
					AND DATA_Transaction.Transactionid not in (select distinct transactionid
																	from rr_Data_Revenue
																	where coaaccountid in (select distinct coaaccountid
																								from cnf_tax 
																							)
																	)
					group by COA.COAAccountId,    
						   RR_DATA_REVENUE.RRCalcTypeWhere,
						   RR_DATA_REVENUE.RRCalcTypeMethod,	   
						   RR_DATA_REVENUE.COAAccountConfigId,
						   COA.COAAccountTypeId,
						   COA.Code,
						   RR_DATA_REVENUE.Transactionid,
						   RR_DATA_REVENUE.saleid,
						   RR_DATA_REVENUE.Siteid,
						   RR_DATA_REVENUE.OperatingAreaId,
						   RR_DATA_REVENUE.Workstationid,
						   RR_DATA_REVENUE.UserGroupid,
						   RR_DATA_REVENUE.UserId,
						   DATA_Transaction.ftransactiondate, 
						   DATA_Transaction.transactiondate,
						   taxamount,
						   Transactiontype,
							p.Accountingtype,					   		
						   RR_DATA_REVENUE.RRCalcTypeTrigger,
						   RR_DATA_REVENUE.RRPercentage,
						   RR_DATA_REVENUE.RRDays

					)p
					where revenueamount &lt;&gt; 0
					group by COAAccountId, 	   
							RRCalcTypeWhere,
							RRCalcTypeMethod,	   
							COAAccountConfigId,
							COAAccountTypeId,
							COACODE,
							Transactionid,
							saleid,
							Siteid,
							OperatingAreaId,
							Workstationid,
							UserGroupid,
							UserId,
							TransDate,
							Accountingtype,		
							RRCalcTypeTrigger,
							RRPercentage,
							RRDays,
							price,
							percentage,
							test,
							batchdate,
							TransactionType


																									
		--	--------Reverse Tax Out
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])	
				      select  COAAccountId, 
									   RevenueRecognitionRuleId,
									   RRCode,		   
									   RRCalcTypeWhere,
									   RRCalcTypeMethod,	   
									   COAAccountConfigId,
									   COAAccountTypeId,
									   COAAccountCode,
									   Transactionid,
									   saleid,
									   siteid,
									   OperatingAreaid,
									   workstationid,
									   usergroupid,
									   userid,
									   batchdate,
									   TransDate,
									   Quantity,
									   grossamount,
									   netamount,
									   price,
									   percentage,
									   tax,
									   ABS(sum(RevenueAmount)) *-1  as RevenueAmount,
									 --  case when TransactionType in (5, 17, 18, 20, 22, 30) then Accountingtype
										--	when TransactionType in (7) and sum(RevenueAmount) &lt;= 0  then 1
										--	when TransactionType in (7) and sum(RevenueAmount) &gt; 0  then 2
										--	else Accountingtype
										--end Accountingtype,	
										p.Accountingtype,	
									   RRCalcTypeTrigger,
									   RRPercentage,
									   RRDays
					  from (		    
				             select distinct 
								       p.COAAccountId, 
									   p.RevenueRecognitionRuleId,
									   p.RRCode,		   
									   p.RRCalcTypeWhere,
									   p.RRCalcTypeMethod,	   
									   p.COAAccountConfigId,
									   p.COAAccountTypeId,
									   p.COAAccountCode,
									   rr_data_Revenue.Transactionid Transactionid,
									   rr_data_Revenue.saleid saleid,
									   rr_data_Revenue.Siteid siteid,
									   rr_data_Revenue.OperatingAreaId OperatingAreaid,
									   rr_data_Revenue.Workstationid workstationid,
									   rr_data_Revenue.UserGroupid usergroupid,
									   rr_data_Revenue.UserId userid,
									   @BatchDate batchdate,
									   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
											else DATA_Transaction.transactiondate
									   end as TransDate,
									   rr_data_Revenue.Quantity Quantity,
									   rr_data_Revenue.GrossAmount grossamount,
									   rr_data_Revenue.NetAmount netamount,
									   0 price,
									   100 percentage,
									   0 tax,
									   rr_data_Revenue.RevenueAmount  as RevenueAmount,
									   data_transaction.transactiontype,
								       p.Accountingtype,		
									   p.RRCalcTypeTrigger,
									   p.RRPercentage,
									   p.RRDays
							FROM rr_data_Revenue   				        WITH (NOLOCK)
								   INNER JOIN (select saleid, transactionid, RevenueRecognitionRuleId, RR_DATA_Revenue.RRCode, RRCalcTypeWhere, Saleitemid, RR_DATA_Revenue.COAAccountId, 
													   RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount, COA_CNF_Account.COAAccountTypeId,  Accountingtype,
													   RR_DATA_Revenue.COAAccountCode
													  from RR_DATA_Revenue
														INNER JOIN COA_CNF_Account		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
													 where COA_CNF_Account.coaAccountID = @TaxAccountID
													)p								ON p.Transactionid = 	rr_data_Revenue.Transactionid
									INNER JOIN data_transaction						on data_transaction.transactionid = rr_data_revenue.transactionid

							where RR_DATA_REVENUE.fcalcdate = @BatchDate
							  and rr_data_Revenue.RRCalcTypeTrigger = @Trigger
							  and DATA_Transaction.TransactionType in (select transactionid
																		from #TransactionIDs)
							  and rr_data_Revenue.coaaccountid in (select distinct coaaccountid
						                                             from cnf_tax
																    where coaaccountid is not null
															      )
							)p
							group by   COAAccountId, 
									   RevenueRecognitionRuleId,
									   RRCode,		   
									   RRCalcTypeWhere,
									   RRCalcTypeMethod,	   
									   COAAccountConfigId,
									   COAAccountTypeId,
									   COAAccountCode,
									   Transactionid,
									   saleid,
									   siteid,
									   OperatingAreaid,
									   workstationid,
									   usergroupid,
									   userid,
									   batchdate,
									   TransDate,
									   Quantity,
									   grossamount,
									   netamount,
									   price,
									   percentage,
									   tax,
								       Accountingtype,		
									   RRCalcTypeTrigger,
									   RRPercentage,
									   RRDays,
									   TransactionType


		----		--Normal Transaction Break out the discounts
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])
				   select *
				   from (				    
						select distinct COA.COAAccountId, 
						   RR_DATA_REVENUE.RevenueRecognitionRuleId,
						   RR_DATA_REVENUE.RRCode,		   
						   RR_DATA_REVENUE.RRCalcTypeWhere,
						   RR_DATA_REVENUE.RRCalcTypeMethod,	   
						   RR_DATA_REVENUE.COAAccountConfigId,
						   COA.COAAccountTypeId,
						   COA.Code,
						   RR_DATA_REVENUE.Transactionid as Transactionid,
						   RR_DATA_REVENUE.saleid as Saleid,
						   RR_DATA_REVENUE.Siteid as SiteID,
						   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
						   RR_DATA_REVENUE.Workstationid as Workstationid,
						   RR_DATA_REVENUE.UserGroupid as UserGroupID,
						   RR_DATA_REVENUE.UserId as userID,
						   @BatchDate as batchdate,
						   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
							    else DATA_Transaction.transactiondate
						   end as TransDate,
						   0 as quantity,
						   0 as grossamount,
						   0 as netamount,
						   0 as price,
						   100 as percentage,
						   0 as remaningValues, 	
						   abs(DATA_SaleItemRule.discountamount)
							as RevenueAmount,
						   p.Accountingtype,		
						   RR_DATA_REVENUE.RRCalcTypeTrigger,
						   RR_DATA_REVENUE.RRPercentage,
						   RR_DATA_REVENUE.RRDays


					from RR_DATA_REVENUE
						inner join rr_cnf_Product						ON ((RR_DATA_REVENUE.MATRIXCELLID = rr_cnf_Product.MATRIXCELLID) or (RR_DATA_REVENUE.MatrixSheetId = rr_cnf_Product.MatrixSheetId)) and rr_cnf_Product.Enabled = 1
						inner join RR_CNF_RevenueRecognitionRule		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_cnf_Product.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  
						INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
						INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
						INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 
						INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
						LEFT  JOIN DATA_Sale				            ON DATA_Sale.SaleID = data_transaction.SaleID
						LEFT  JOIN DATA_SaleItem			            ON DATA_SaleItem.saleitemid = RR_DATA_REVENUE.saleitemid
						LEFT JOIN DATA_SaleItemRule						ON data_saleitemrule.saleitemid = DATA_SaleItem.saleitemid	 
						LEFT JOIN CNF_PromotionItemRule					ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
						LEFT JOIN CNF_PromotionItem						ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
						LEFT JOIN CNF_Promotion							ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId	
						LEFT JOIN COA_CNF_Account	COA			        ON COA.coaaccountid = CNF_Promotion.coaaccountid
						
						
						INNER JOIN (select transactionid, RevenueRecognitionRuleId, RR_DATA_Revenue.RRCode, RRCalcTypeWhere, 
											RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount,  Accountingtype
											from RR_DATA_Revenue
											INNER JOIN COA_CNF_Account		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
											where COA_CNF_Account.coaAccountID = @DiscountAccountID
										)p    on p.transactionid = 	DATA_Transaction.transactionid



					where COA_CNF_AccountConfig.coaaccountid in (@DiscountAccountID)
					and RR_DATA_REVENUE.coaaccountid = 1
					and DATA_Transaction.TransactionType in (select transactionid
																from #TransactionIDs)
					and RR_DATA_REVENUE.fcalcdate = @BatchDate
					and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
					AND DATA_Transaction.Transactionid not in (select distinct transactionid
																	from rr_Data_Revenue
																	where coaaccountid in (select distinct coaaccountid
																								from CNF_Promotion
																								where coaaccountid is not null 
																							)
																	)	
					)p
					where revenueamount &lt;&gt; 0	
					  and coaaccountid is not null													
																																								
		--		--Reverse out Discounts														
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[Saleitemid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])			    
				select distinct p.COAAccountId, 
						   p.RevenueRecognitionRuleId,
						   p.RRCode,		   
						   p.RRCalcTypeWhere,
						   p.RRCalcTypeMethod,	   
						   p.COAAccountConfigId,
						   p.COAAccountTypeId,
						   p.COAAccountCode,
						   rr_data_Revenue.Transactionid,
						   rr_data_Revenue.saleid,
						   rr_data_Revenue.saleitemid,
						   rr_data_Revenue.Siteid,
						   rr_data_Revenue.OperatingAreaId,
						   rr_data_Revenue.Workstationid,
						   rr_data_Revenue.UserGroupid,
						   rr_data_Revenue.UserId,
						   @BatchDate,
						   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
							    else DATA_Transaction.transactiondate
						   end as TransDate,
						   0,
						   0,
						   0,
						   0,
						   100,
						   0,
						   rr_data_Revenue.RevenueAmount*-1  as RevenueAmount,
						   p.Accountingtype,
						   p.RRCalcTypeTrigger,
						   p.RRPercentage,
						   p.RRDays

						  FROM rr_data_Revenue   				        WITH (NOLOCK)
								   INNER JOIN (select saleid, transactionid, RevenueRecognitionRuleId, RR_DATA_Revenue.RRCode, RRCalcTypeWhere, Saleitemid, RR_DATA_Revenue.COAAccountId, 
													   RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount, COA_CNF_Account.COAAccountTypeId,  Accountingtype,
													   RR_DATA_Revenue.COAAccountCode
													  from RR_DATA_Revenue
														INNER JOIN COA_CNF_Account		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
													 where COA_CNF_Account.coaAccountID = @DiscountAccountID
													)p								ON p.saleid = 	rr_data_Revenue.saleid
								INNER JOIN data_transaction        on data_transaction.transactionid = rr_data_revenue.transactionid

						where  rr_data_Revenue.coaaccountid in (select distinct coaaccountid
						                                         from CNF_Promotion
															  )
						 and RR_DATA_REVENUE.fcalcdate = @BatchDate
						 and DATA_Transaction.TransactionType in (select transactionid
															from #TransactionIDs)
																																																																																											

		
		End

</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_RR_RevenueData_OnTimePeriodTrigger]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_RR_RevenueData_OnTimePeriodTrigger
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE Procedure dbo.otn_sp_RR_RevenueData_OnTimePeriodTrigger
	@BatchDate Date,
	@RRTransDateType Integer
AS 
BEGIN
	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer
	Declare @OnTimePeriodTrigger Integer = 4	

	create table #RulesToRun
	(
		RRID int
	)

	Declare @TodayDayofWeek Int
	Declare @TodaySpecificDay Int
	Declare @TodayMonthlyWeek Int
	Declare @TodayMonth Int
	Declare @TodayDay Int
	Declare @TodayDaysofWeek Int

	select @TodayDayofWeek   = datePart(weekday, cast(@BatchDate as date)),
		   @TodayMonth       = datePart(mm, cast(@BatchDate as date)),
		   @TodaySpecificDay = datePart(dd, cast(@BatchDate as date)),
		   @TodayMonthlyWeek = datediff(week, dateadd(week, datediff(week, 0, dateadd(month, datediff(month, 0, cast(@BatchDate as date)), 0)), 0), getdate() - 1) + 1

	if @TodayDaysofWeek = 6 
	   SET @TodayDaysofWeek = 1

	insert into #RulesToRun
	select	distinct RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
		from RR_CNF_RevenueRecognitionRuleSchedule
			INNER JOIN RR_CNF_RevenueRecognitionRule					ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRuleSchedule.RevenueRecognitionRuleId

	where RR_CNF_RevenueRecognitionRule.Enabled = 1
	  and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
	  and ((PeriodOption = 1)
			  or ((PeriodOption = 2) and (((@TodayDayofWeek = 1) and (ActiveSunday = 1))
											or ((@TodayDayofWeek = 2) and (ActiveMonday = 1))
											or ((@TodayDayofWeek = 3) and (ActiveTuesday = 1))
											or ((@TodayDayofWeek = 4) and (ActiveWednesday = 1))
											or ((@TodayDayofWeek = 5) and (ActiveThursday = 1))
											or ((@TodayDayofWeek = 6) and (ActiveFriday = 1))
											or ((@TodayDayofWeek = 6) and (ActiveFriday = 1))
											or ((@TodayDayofWeek = 7) and (ActiveSaturday = 1))
										)))
			 or ((PeriodOption = 3) and ((SpecificDay = @TodaySpecificDay) 
										  or ((WeekOption = @TodayMonthlyWeek and (((@TodayDayofWeek = 1) and (ActiveSunday = 1))
																					or ((@TodayDayofWeek = 2) and (ActiveMonday = 1))
																					or ((@TodayDayofWeek = 3) and (ActiveTuesday = 1))
																					or ((@TodayDayofWeek = 4) and (ActiveWednesday = 1))
																					or ((@TodayDayofWeek = 5) and (ActiveThursday = 1))
																					or ((@TodayDayofWeek = 6) and (ActiveFriday = 1))
																					or ((@TodayDayofWeek = 6) and (ActiveFriday = 1))
																					or ((@TodayDayofWeek = 7) and (ActiveSaturday = 1))
																					or (LastDayOptionWeek = 1))
																				))))  
			 or ((PeriodOption = 4) and (((SpecificDay = @TodaySpecificDay) and (MonthOption = @TodayMonth))  
										   or ((WeekOption = @TodayMonthlyWeek and (((@TodayDayofWeek = 1) and (ActiveSunday = 1))
																					or ((@TodayDayofWeek = 2) and (ActiveMonday = 1))
																					or ((@TodayDayofWeek = 3) and (ActiveTuesday = 1))
																					or ((@TodayDayofWeek = 4) and (ActiveWednesday = 1))
																					or ((@TodayDayofWeek = 5) and (ActiveThursday = 1))
																					or ((@TodayDayofWeek = 6) and (ActiveFriday = 1))
																					or ((@TodayDayofWeek = 6) and (ActiveFriday = 1))
																					or ((@TodayDayofWeek = 7) and (ActiveSaturday = 1))
																					or (LastDayOptionWeek = 1))
																				)))
																				and (MonthOption = @TodayMonth))



			INSERT INTO [dbo].[RR_DATA_Revenue]
						   ([COAAccountId]
						   ,[RevenueRecognitionRuleId]
						   ,[RRCode]
						   ,[RRCalcTypeWhere]
						   ,[RRCalcTypeMethod]
						   ,[COAAccountConfigId]
						   ,[COAAccountType]
						   ,[COAAccountCode]
						   ,[SaleId]
						   ,[Ticketid]
						   ,[MatrixCellid]
						   ,[MatrixCellCode]
						   ,[MatrixSheetid]
						   ,[SiteId]
						   ,[OperatingAreaId]
						   ,[WorkstationId]
						   ,[Usergroupid]
						   ,[UserId]
						   ,[FCalcDate]
						   ,[FRevenueDate]
						   ,[Quantity]
						   ,[GrossAmount]
						   ,[NetAmount]
						   ,[Price]
						   ,[Percentage]
						   ,[RemaningValues]
						   ,[RevenueAmount]
						   ,[AccountingType]
						   ,[RRCalcTypeTrigger]
						   ,[RRPercentage]			
						   ,[RRDays])
							select distinct p.COAAccountId, 
								   p.RevenueRecognitionRuleId,
								   p.RRcode,		   
								   p.RRCalcTypeWhere,
								   p.RRCalcTypeMethod,	   
								   p.COAAccountConfigId,
								   p.COAAccountTypeId,
								   p.AccountCode as AccountCode,
								   RR_DATA_REVENUE.saleid as Saleid,
								   ISNULL(rdata.Ticketid, DATA_SaleItem2Ticket.Ticketid) , 
								   RR_DATA_REVENUE.Matrixcellid,
								   RR_DATA_REVENUE.MatrixcellCode,
								   RR_DATA_REVENUE.MatrixSheetId,
								   RR_DATA_REVENUE.Siteid,
								   RR_DATA_REVENUE.OperatingAreaId,
								   RR_DATA_REVENUE.Workstationid,
								   RR_DATA_REVENUE.UserGroupid,
								   RR_DATA_REVENUE.UserId as userID,
								   @BatchDate as BatchDate,
								   @BatchDate as TransDate,
								   RR_DATA_REVENUE.Quantity as Quantity,
								   RR_DATA_REVENUE.GrossAmount as GrossAmount,
								   RR_DATA_REVENUE.NetAmount as NetAmount,
								   p.Price as ConfigPrice,
								   p.Percentage as ConfigPercentage,
								   p.RemainingValues,																		
								  Case when p.Price &gt; 0 then (p.Price) 
									   else case when ((((DATA_Ticket.Price - DATA_Ticket.taxes) - ISNULL(rdata.TotalUsed, 0)) &gt; 0) and ((DATA_Ticket.Price - DATA_Ticket.taxes) - ISNULL(rdata.TotalUsed, 0)) &gt;= ((((DATA_Ticket.Price - DATA_Ticket.taxes) * p.RRPercentage)/100 * p.Percentage)/100)) 
										              then ((((DATA_Ticket.Price - DATA_Ticket.taxes) * p.RRPercentage)/100 * p.Percentage)/100)
									              else (((DATA_Ticket.Price - DATA_Ticket.taxes) - ISNULL(rdata.TotalUsed, 0)) * p.Percentage)/100
								            end
							       end as RevenueAmount,
								   p.Accountingtype,
								   p.RRCalcTypeTrigger,
								   p.RRPercentage,
								   p.Days

							from RR_DATA_REVENUE
								INNER JOIN DATA_SaleItem							ON data_saleitem.SaleItemId		   = rr_data_revenue.saleitemid
								INNER JOIN DATA_SaleItem2Ticket						on data_saleitem2ticket.Saleitemid = data_saleitem.saleitemid
								INNER JOIN DATA_Ticket								on data_ticket.ticketid = data_saleitem2ticket.ticketid
								INNER JOIN (  
										select  RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleid, 
										RR_CNF_RevenueRecognitionRule.Code as RRCode,
										RR_CNF_RevenueRecognitionRule.Days,
										RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
										RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,
										FromDate,
										ToDate,
										RR_CNF_RevenueRecognitionRule.rrCalcTypeTrigger,
										RR_CNF_RevenueRecognitionRule.Percentage as RRPercentage,
										COA_CNF_AccountConfig.CoaAccountid,
										COA_CNF_AccountConfig.AccountingType,
										COA_CNF_AccountConfig.Price,
										COA_CNF_AccountConfig.Percentage,
										COA_CNF_AccountConfig.RemainingValues,
										COA_CNF_AccountConfig.SiteID,
										coa_cnf_account.code as AccountCode,
										COA_CNF_AccountType.Code as AccountTypeCode,
										COA_CNF_AccountType.COAAccountTypeId,
										rr_cnf_Product.MatrixcellID,
										rr_cnf_Product.matrixsheetID,
										COA_CNF_AccountConfig.COAAccountConfigId

								from RR_CNF_RevenueRecognitionRule
									inner join rr_cnf_Product						ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_cnf_product.RevenueRecognitionRuleId and rr_cnf_Product.Enabled = 1		
									INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
									INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
									INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 

								where COA_CNF_AccountConfig.RemainingValues &lt;&gt; 1
								  and RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId in (select RRID 
								                                                                   from #RulesToRun)

									)p   ON ((RR_DATA_REVENUE.MATRIXCELLID = p.MATRIXCELLID) or (RR_DATA_REVENUE.MatrixSheetId = p.MatrixSheetId)) 
                                   LEFT JOIN (select ticketid, AccountingType, sum(revenueamount) as TotalUsed
												from rr_data_revenue
												where rr_data_revenue.RRCalcTypeTrigger = @OnTimePeriodTrigger
												group by ticketid, AccountingType
												)rdata									ON rdata.ticketid = ISNULL(RR_DATA_REVENUE.ticketid, DATA_SaleItem2Ticket.ticketid)	and rdata.AccountingType = RR_DATA_REVENUE.AccountingType




					INSERT INTO [dbo].[RR_DATA_Revenue]
						   ([COAAccountId]
						   ,[RevenueRecognitionRuleId]
						   ,[RRCode]
						   ,[RRCalcTypeWhere]
						   ,[RRCalcTypeMethod]
						   ,[COAAccountConfigId]
						   ,[COAAccountType]
						   ,[COAAccountCode]
						   ,[SaleId]
						   ,[Ticketid]
						   ,[MatrixCellid]
						   ,[MatrixCellCode]
						   ,[MatrixSheetid]
						   ,[SiteId]
						   ,[OperatingAreaId]
						   ,[WorkstationId]
						   ,[Usergroupid]
						   ,[UserId]
						   ,[FCalcDate]
						   ,[FRevenueDate]
						   ,[Quantity]
						   ,[GrossAmount]
						   ,[NetAmount]
						   ,[Price]
						   ,[Percentage]
						   ,[RemaningValues]
						   ,[RevenueAmount]
						   ,[AccountingType]
						   ,[RRCalcTypeTrigger]
						   ,[RRPercentage]			
						   ,[RRDays])
							select distinct p.COAAccountId, 
								   p.RevenueRecognitionRuleId,
								   p.RRcode,		   
								   p.RRCalcTypeWhere,
								   p.RRCalcTypeMethod,	   
								   p.COAAccountConfigId,
								   p.COAAccountTypeId,
								   p.AccountCode as AccountCode,
								   RR_DATA_REVENUE.saleid as Saleid,
								   ISNULL(rdata.Ticketid, DATA_SaleItem2Ticket.Ticketid) , 
								   RR_DATA_REVENUE.Matrixcellid,
								   RR_DATA_REVENUE.MatrixcellCode,
								   RR_DATA_REVENUE.MatrixSheetId,
								   RR_DATA_REVENUE.Siteid,
								   RR_DATA_REVENUE.OperatingAreaId,
								   RR_DATA_REVENUE.Workstationid,
								   RR_DATA_REVENUE.UserGroupid,
								   RR_DATA_REVENUE.UserId as userID,
								   @BatchDate as BatchDate,
								   @BatchDate as TransDate,
								   RR_DATA_REVENUE.Quantity as Quantity,
								   RR_DATA_REVENUE.GrossAmount as GrossAmount,
								   RR_DATA_REVENUE.NetAmount as NetAmount,
								   p.Price as ConfigPrice,
								   p.Percentage as ConfigPercentage,
								   p.RemainingValues,																		
								  case when ((((DATA_Ticket.Price - DATA_Ticket.taxes) - ISNULL(TotalUsed, 0)) &gt; 0) and ((
																					(((DATA_Ticket.Price - DATA_Ticket.taxes) *  p.rrPercentage)/100) -  
																						((
																						(((DATA_Ticket.Price - DATA_Ticket.taxes) *  p.rrPercentage)/100) * (select sum(percentage)
																																							from coa_cnf_accountconfig AC
																																							where AC.revenuerecognitionruleid = p.RevenueRecognitionRuleId
																																							and ac.accountingtype = p.accountingtype
																																							)
																						)/100)) &lt;= ((DATA_Ticket.Price - DATA_Ticket.taxes) - ISNULL(TotalUsed, 0))))

														then 
														((((DATA_Ticket.Price - DATA_Ticket.taxes) *  p.rrPercentage)/100) -  ((((DATA_Ticket.Price - DATA_Ticket.taxes) *  p.RRPercentage)/100) * (select sum(percentage)
																																from coa_cnf_accountconfig AC
																																where AC.revenuerecognitionruleid = p.RevenueRecognitionRuleId
																																and ac.accountingtype = p.accountingtype
																																))/100)
													else (DATA_Ticket.Price - DATA_Ticket.taxes) - TotalUsed
												end as RevenueAmount,
								   p.Accountingtype,
								   p.RRCalcTypeTrigger,
								   p.RRPercentage,
								   p.Days

							from RR_DATA_REVENUE
								INNER JOIN DATA_SaleItem							ON data_saleitem.SaleItemId		   = rr_data_revenue.saleitemid
								INNER JOIN DATA_SaleItem2Ticket						on data_saleitem2ticket.Saleitemid = data_saleitem.saleitemid
								INNER JOIN DATA_Ticket								on data_ticket.ticketid = data_saleitem2ticket.ticketid
								INNER JOIN (  
										select  RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleid, 
										RR_CNF_RevenueRecognitionRule.Code as RRCode,
										RR_CNF_RevenueRecognitionRule.Days,
										RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
										RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,
										FromDate,
										ToDate,
										RR_CNF_RevenueRecognitionRule.rrCalcTypeTrigger,
										RR_CNF_RevenueRecognitionRule.Percentage as RRPercentage,
										COA_CNF_AccountConfig.CoaAccountid,
										COA_CNF_AccountConfig.AccountingType,
										COA_CNF_AccountConfig.Price,
										COA_CNF_AccountConfig.Percentage,
										COA_CNF_AccountConfig.RemainingValues,
										COA_CNF_AccountConfig.SiteID,
										coa_cnf_account.code as AccountCode,
										COA_CNF_AccountType.Code as AccountTypeCode,
										COA_CNF_AccountType.COAAccountTypeId,
										rr_cnf_Product.MatrixcellID,
										rr_cnf_Product.matrixsheetID,
										COA_CNF_AccountConfig.COAAccountConfigId

								from RR_CNF_RevenueRecognitionRule
									inner join rr_cnf_Product						ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_cnf_product.RevenueRecognitionRuleId and rr_cnf_Product.Enabled = 1		
									INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
									INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
									INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 

								where COA_CNF_AccountConfig.RemainingValues = 1
								  and RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId in (select RRID 
								                                                                   from #RulesToRun)

									)p   ON ((RR_DATA_REVENUE.MATRIXCELLID = p.MATRIXCELLID) or (RR_DATA_REVENUE.MatrixSheetId = p.MatrixSheetId)) 
                                   LEFT JOIN (select ticketid, AccountingType, sum(revenueamount) as TotalUsed
												from rr_data_revenue
												where rr_data_revenue.RRCalcTypeTrigger = @OnTimePeriodTrigger
												group by ticketid, AccountingType
												)rdata									ON rdata.ticketid = ISNULL(RR_DATA_REVENUE.ticketid, DATA_SaleItem2Ticket.ticketid)	and rdata.AccountingType = RR_DATA_REVENUE.AccountingType


    select 'OnTimePeriodTrigger' as TriggerType, @BatchDate as RunDate
END

</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_RR_RevenueData_OnTicketUsageTrigger]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_RR_RevenueData_OnTicketUsageTrigger
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE Procedure dbo.otn_sp_RR_RevenueData_OnTicketUsageTrigger
	@BatchDate Date,
	@RRTransDateType Integer
AS 
BEGIN
	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer
	Declare @TicketUsageTrigger Integer = 2	

	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1



	BEGIN

		--Normal TicketExpired No Remaining Value
			INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[SaleId]
				   ,[UsageID]
				   ,[Ticketid]
				   ,[MatrixCellid]
				   ,[MatrixCellCode]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				   ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]			
				   ,[RRDays])
				   select *
				   from (
				     select coa_cnf_account.COAAccountId, 
							RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
							RR_CNF_RevenueRecognitionRule.code,		   
							RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
							RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
							COA_CNF_AccountConfig.COAAccountConfigId,
							coa_cnf_account.COAAccountTypeId,
							coa_cnf_account.Code as AccountCode,
							p.saleid as Saleid,
							p.Usageid,
							p.Ticketid as SaleitemID,
							p.Matrixcellid as Matrixcell,
							p.Code as MatrixCode,
							p.MatrixSheetId as MatrixSheetID,
							CASE When RR_CNF_RevenueRecognitionRule.rrCalcTypeWhere = 1 then p.AdmSiteid 
							else p.SaleSite
							end as SiteID,
							p.OperatingAreaId as OperatingAreaID,
							p.Workstationid as Workstationid,
							p.UserId as userID,
							@BatchDate as BatchDate,
							@BatchDate as TransDate,
							1 as Quantity,
							p.GrossAmount as GrossAmount,
							p.NetPrice as NetAmount,
							COA_CNF_AccountConfig.Price as ConfigPrice,
							COA_CNF_AccountConfig.Percentage as ConfigPercentage,
							COA_CNF_AccountConfig.RemainingValues,															   
							Case when COA_CNF_AccountConfig.Price &gt; 0 then (COA_CNF_AccountConfig.Price) 
								 else case when (((p.TicketPrice - ISNULL(TotalUsed, 0)) &gt; 0) and (p.TicketPrice - ISNULL(TotalUsed, 0)) &gt;= (((p.TicketPrice * RR_CNF_RevenueRecognitionRule.Percentage)/100 * COA_CNF_AccountConfig.Percentage)/100)) 
												then (((p.TicketPrice * RR_CNF_RevenueRecognitionRule.Percentage)/100 * COA_CNF_AccountConfig.Percentage)/100)
										   else 0
									   end
							end as RevenueAmount,
							COA_CNF_AccountConfig.AccountingType,
							RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
							RR_CNF_RevenueRecognitionRule.Percentage,
							RR_CNF_RevenueRecognitionRule.Days
						from (			
								select  data_ticketusage.ticketid,
								        data_ticketusage.UsageID,
										1 as Quantity, 
										(DATA_Ticket.Price - Data_Ticket.Taxes) NetPrice,
										DATA_Ticket.Price as GrossAmount,
										CNF_MatrixCell.matrixcellid, 
										CNF_MatrixCell.code,
										CNF_MatrixCell.matrixsheetid, 
										DATA_Ticket.Siteid SaleSite,	  
										cnf_workstation.OperatingAreaId,
										cnf_workstation.workstationid,
										(select top 1 DATA_Sale.userid
											from data_saleitem
											INNER JOIN DATA_Sale		on data_sale.saleid = data_saleitem.saleid
											where data_saleitem.saleitemid = data_ticket.saleitemid
										) as userid,
										(select top 1 data_saleitem.saleid
											from data_saleitem
											where data_saleitem.saleitemid = data_ticket.saleitemid
										) as Saleid,
										(DATA_Ticket.RawPrice) as TicketPrice,
										CNF_Location.Siteid as AdmSiteid
								from data_ticketusage
									INNER JOIN DATA_Ticket											on DATA_Ticket.ticketid = data_ticketusage.ticketid
									INNER JOIN CNF_MatrixCell										on cnf_matrixcell.matrixcellid = data_ticket.matrixcellid
									INNER JOIN CNF_Workstation										on cnf_workstation.workstationid = data_ticket.WorkstationId
									INNER JOIN ADM_Gate												on ADM_Gate.gateid = data_ticketusage.gateid
									INNER JOIN CNF_Location											on CNF_Location.locationid = ADM_Gate.locationid
								where data_ticketusage.validateResult &lt;=99
								and fusagedate = @batchdate
								and VoidType = 0
						)p 
						INNER JOIN rr_cnf_product							ON ((RR_CNF_Product.matrixcellid = p.matrixcellid) or (RR_CNF_Product.matrixsheetid = p.matrixsheetid))
						INNER JOIN RR_CNF_RevenueRecognitionRule			ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_cnf_product.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @TicketUsageTrigger
						INNER JOIN COA_CNF_AccountConfig					ON COA_CNF_AccountConfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
						INNER JOIN COA_CNF_Account							ON COA_CNF_Account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
						LEFT JOIN (select ticketid, AccountingType, sum(revenueamount) as TotalUsed
									from rr_data_revenue
									where rr_data_revenue.RRCalcTypeTrigger = @TicketUsageTrigger
									group by ticketid, AccountingType
									)rdata									ON rdata.ticketid = p.ticketid	and rdata.AccountingType = coa_cnf_accountconfig.AccountingType
						where p.TicketPrice &lt;&gt; 0
							and RR_CNF_RevenueRecognitionRule.Enabled = 1
							and coa_cnf_account.Enabled = 1
							and COA_CNF_AccountConfig.Enabled = 1
							and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
							and COA_CNF_AccountConfig.RemainingValues &lt;&gt; 1
							and (((RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere = 1) and ((coa_cnf_accountConfig.Siteid = p.AdmSiteid) or (coa_cnf_accountConfig.Siteid is null)))
							or (RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere = 2) and ((coa_cnf_accountConfig.Siteid = p.SaleSite) or (coa_cnf_accountConfig.Siteid is null))) 
						)k
						where RevenueAmount &lt;&gt; 0




		--Normal TicketExpired with Remaining Value
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[SaleId]
				   ,[UsageID]
				   ,[Ticketid]
				   ,[MatrixCellid]
				   ,[MatrixCellCode]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				   ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])
				   select *
				   from (
						select   	coa_cnf_account.COAAccountId, 
									RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
									RR_CNF_RevenueRecognitionRule.code,		   
									RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
									RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
									COA_CNF_AccountConfig.COAAccountConfigId,
									coa_cnf_account.COAAccountTypeId,
									coa_cnf_account.Code as AccountCode,
									p.saleid as Saleid,
									p.Usageid,
									p.Ticketid as SaleitemID,
									p.Matrixcellid as Matrixcell,
									p.Code as MatrixCode,
									p.MatrixSheetId as MatrixSheetID,
									CASE When RR_CNF_RevenueRecognitionRule.rrCalcTypeWhere = 1 then p.AdmSiteid 
									else p.SaleSite
									end as SiteID,
									p.OperatingAreaId as OperatingAreaID,
									p.Workstationid as Workstationid,
									p.UserId as userID,
									@BatchDate as BatchDate,
									@BatchDate as TransDate,
									1 as Quantity,
									p.GrossAmount as GrossAmount,
									p.NetPrice as NetAmount,
									COA_CNF_AccountConfig.Price as ConfigPrice,
									COA_CNF_AccountConfig.Percentage as ConfigPercentage,
									COA_CNF_AccountConfig.RemainingValues,															   
										case when (((p.TicketPrice - ISNULL(TotalUsed, 0)) &gt; 0) and ((
																					((p.ticketprice *  RR_CNF_RevenueRecognitionRule.Percentage)/100) -  
																						((
																						((p.ticketprice *  RR_CNF_RevenueRecognitionRule.Percentage)/100) * (select sum(percentage)
																																							from coa_cnf_accountconfig AC
																																							where AC.revenuerecognitionruleid = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																																							and ac.accountingtype = coa_cnf_accountconfig.accountingtype
																																							)
																						)/100)) &lt;= (p.TicketPrice - ISNULL(TotalUsed, 0))))







														then 
														(((p.ticketprice *  RR_CNF_RevenueRecognitionRule.Percentage)/100) -  (((p.ticketprice *  RR_CNF_RevenueRecognitionRule.Percentage)/100) * (select sum(percentage)
																																from coa_cnf_accountconfig AC
																																where AC.revenuerecognitionruleid = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																																and ac.accountingtype = coa_cnf_accountconfig.accountingtype
																																))/100)
													else 0
												end as RevenueAmount,
									COA_CNF_AccountConfig.AccountingType,
									RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
									RR_CNF_RevenueRecognitionRule.Percentage,
									RR_CNF_RevenueRecognitionRule.Days
								from (			
										select  data_ticketusage.ticketid,
										data_ticketusage.UsageID,
												1 as Quantity, 
												(DATA_Ticket.Price - Data_Ticket.Taxes) NetPrice,
												DATA_Ticket.Price as GrossAmount,
												CNF_MatrixCell.matrixcellid, 
												CNF_MatrixCell.code,
												CNF_MatrixCell.matrixsheetid, 
												DATA_Ticket.Siteid SaleSite,	  
												cnf_workstation.OperatingAreaId,
												cnf_workstation.workstationid,
												(select top 1 DATA_Sale.userid
													from data_saleitem
													INNER JOIN DATA_Sale		on data_sale.saleid = data_saleitem.saleid
													where data_saleitem.saleitemid = data_ticket.saleitemid
												) as userid,
												(select top 1 data_saleitem.saleid
													from data_saleitem
													where data_saleitem.saleitemid = data_ticket.saleitemid
												) as Saleid,
												(DATA_Ticket.RawPrice) as TicketPrice,
												CNF_Location.Siteid as AdmSiteid
										from data_ticketusage
											INNER JOIN DATA_Ticket											on DATA_Ticket.ticketid = data_ticketusage.ticketid
											INNER JOIN CNF_MatrixCell										on cnf_matrixcell.matrixcellid = data_ticket.matrixcellid
											INNER JOIN CNF_Workstation										on cnf_workstation.workstationid = data_ticket.WorkstationId
											INNER JOIN ADM_Gate												on ADM_Gate.gateid = data_ticketusage.gateid
											INNER JOIN CNF_Location											on CNF_Location.locationid = ADM_Gate.locationid
										where data_ticketusage.validateResult &lt;=99
										and fusagedate = @batchdate
										and VoidType = 0
								)p 
								INNER JOIN rr_cnf_product							ON ((RR_CNF_Product.matrixcellid = p.matrixcellid) or (RR_CNF_Product.matrixsheetid = p.matrixsheetid))
								INNER JOIN RR_CNF_RevenueRecognitionRule			ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_cnf_product.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @TicketUsageTrigger
								INNER JOIN COA_CNF_AccountConfig					ON COA_CNF_AccountConfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
								INNER JOIN COA_CNF_Account							ON COA_CNF_Account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
								LEFT JOIN (select ticketid, accountingtype, sum(revenueamount) as TotalUsed
											from rr_data_revenue
											where rr_data_revenue.RRCalcTypeTrigger = @TicketUsageTrigger
											group by ticketid, accountingtype
											)rdata									ON rdata.ticketid = p.ticketid	and rdata.accountingtype = COA_CNF_AccountConfig.accountingtype
								where p.TicketPrice &lt;&gt; 0
									and RR_CNF_RevenueRecognitionRule.Enabled = 1
									and coa_cnf_account.Enabled = 1
									and COA_CNF_AccountConfig.Enabled = 1
									and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
									and COA_CNF_AccountConfig.RemainingValues = 1
									and (((RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere = 1) and ((coa_cnf_accountConfig.Siteid = p.AdmSiteid) or (coa_cnf_accountConfig.Siteid is null)))
									or (RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere = 2) and ((coa_cnf_accountConfig.Siteid = p.SaleSite) or (coa_cnf_accountConfig.Siteid is null))) 
						)k
						where RevenueAmount &lt;&gt; 0

	end

	select 'OnTicketUsageTrigger' as TriggerType, @BatchDate as RunDate

END

</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_RR_RevenueData_OnTicketExpiredTrigger]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_RR_RevenueData_OnTicketExpiredTrigger
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE Procedure dbo.otn_sp_RR_RevenueData_OnTicketExpiredTrigger
	@BatchDate Date,
	@RRTransDateType Integer
AS 
BEGIN

	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer
	Declare @TicketExpiredTrigger Integer = 3	

	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1

	BEGIN
		--Normal TicketExpired No Remaining Value
			INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[Ticketid]
				   ,[MatrixCellid]
				   ,[MatrixCellCode]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				   ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])
				   select *
				   from(
				   select COA_CNF_AccountConfig.COAAccountId, 
												   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
												   RR_CNF_RevenueRecognitionRule.code,		   
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
												   COA_CNF_AccountConfig.COAAccountConfigId,
												   coa_cnf_account.COAAccountTypeId,
												   coa_cnf_account.Code as AccountCode,
												   p.Ticketid as Ticketid,
												   p.Matrixcellid as Matrixcell,
												   p.Code as MatrixCode,
												   p.MatrixSheetId as MatrixSheetID,
												   p.Siteid as SiteID,
												   @BatchDate as BatchDate,
												   p.ActiveTo,
												   1 as Quantity,
												   0 as GrossAmount,
												   0 as NetAmount,
												   COA_CNF_AccountConfig.Price as ConfigPrice,
												   COA_CNF_AccountConfig.Percentage as ConfigPercentage,
												   COA_CNF_AccountConfig.RemainingValues,									   
													Case when COA_CNF_AccountConfig.Price &gt; 0 then (COA_CNF_AccountConfig.Price)
														 else (p.price - ISNULL((select sum(revenueamount)
																															  from rr_data_revenue 
																															 where rr_data_revenue.ticketid = p.Ticketid
																															   and rr_data_revenue.coaaccountid in (select coa_cnf_accountconfig.COAAccountId
																																									  from coa_cnf_accountconfig
																																									  where coa_cnf_accountconfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId)
																															), 0)) * COA_CNF_AccountConfig.Percentage/100
																	                                                                                                                                                                                              
													END as RevenueAmount,
												   COA_CNF_AccountConfig.AccountingType,
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
												   RR_CNF_RevenueRecognitionRule.Percentage,
												   RR_CNF_RevenueRecognitionRule.Days

				  from RR_CNF_RevenueRecognitionRule
					   INNER JOIN RR_CNF_Product						ON RR_CNF_Product.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
					   INNER JOIN COA_CNF_AccountConfig					ON COA_CNF_AccountConfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId 
					   INNER JOIN COA_CNF_Account						on coa_cnf_account.COAAccountId = COA_CNF_AccountConfig.coaaccountid and  COA_CNF_Account.enabled = 1
					   INNER JOIN (select	distinct CNF_MatrixCell.matrixcellid, DATA_Ticket.price, DATA_Ticket.rawprice, DATA_Ticket.ticketid, 
					                                 CNF_MatrixCell.Code, MatrixSheetId, DATA_Ticket.siteid, DAta_Ticket.ActiveTo
														from DATA_Ticket
															INNER JOIN CNF_MatrixCell					on cnf_matrixcell.matrixcellid = data_ticket.matrixcellid
										
														where VoidType = 0
															and data_ticket.activeto = @batchdate
									)p  on						((p.matrixcellid   = rr_cnf_product.matrixcellid) or(p.matrixsheetid = rr_cnf_product.matrixsheetid))

				where RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @TicketExpiredTrigger
				  and rr_cnf_revenuerecognitionRule.Enabled = 1
				  and COA_CNF_AccountConfig.Enabled = 1
				  and COA_CNF_AccountConfig.RemainingValues &lt;&gt; 1
				)p
				where RevenueAmount &lt;&gt; 0 



		--Normal TicketExpired with Remaining Value
			INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[Ticketid]
				   ,[MatrixCellid]
				   ,[MatrixCellCode]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				   ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])
				   select *
				   from(
				   select COA_CNF_AccountConfig.COAAccountId, 
												   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
												   RR_CNF_RevenueRecognitionRule.code,		   
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
												   COA_CNF_AccountConfig.COAAccountConfigId,
												   coa_cnf_account.COAAccountTypeId,
												   coa_cnf_account.Code as AccountCode,
												   p.Ticketid as Ticketid,
												   p.Matrixcellid as Matrixcell,
												   p.Code as MatrixCode,
												   p.MatrixSheetId as MatrixSheetID,
												   p.Siteid as SiteID,
												   @BatchDate as BatchDate,
												   p.ActiveTo,
												   1 as Quantity,
												   0 as GrossAmount,
												   0 as NetAmount,
												   COA_CNF_AccountConfig.Price as ConfigPrice,
												   COA_CNF_AccountConfig.Percentage as ConfigPercentage,
												   COA_CNF_AccountConfig.RemainingValues,									   
													(select sum(revenueamount)
														from rr_data_revenue 
														where rr_data_revenue.ticketid = p.Ticketid
														  and rr_data_revenue.RevenueRecognitionRuleId =  RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
														  and rr_data_revenue.Accountingtype &lt;&gt; COA_CNF_AccountConfig.Accountingtype) -
														   (ISNULL((select sum(revenueamount)
																			from rr_data_revenue 
																			where rr_data_revenue.ticketid = p.Ticketid
																			and rr_data_revenue.accountingtype = COA_CNF_AccountConfig.accountingtype
																			and rr_data_revenue.coaaccountid in (select coa_cnf_accountconfig.COAAccountId
																													from coa_cnf_accountconfig
																													where coa_cnf_accountconfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId)
																		), 0)) as RevenueAmount,
												   COA_CNF_AccountConfig.AccountingType,
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
												   RR_CNF_RevenueRecognitionRule.Percentage,
												   RR_CNF_RevenueRecognitionRule.Days

				  from RR_CNF_RevenueRecognitionRule
					   INNER JOIN RR_CNF_Product						ON RR_CNF_Product.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
					   INNER JOIN COA_CNF_AccountConfig					ON COA_CNF_AccountConfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId 
					   INNER JOIN COA_CNF_Account						on coa_cnf_account.COAAccountId = COA_CNF_AccountConfig.coaaccountid and  COA_CNF_Account.enabled = 1
					   INNER JOIN (select	distinct CNF_MatrixCell.matrixcellid, DATA_Ticket.price, DATA_Ticket.rawprice, DATA_Ticket.ticketid, 
					                                 CNF_MatrixCell.Code, MatrixSheetId, DATA_Ticket.siteid, DAta_Ticket.ActiveTo
														from DATA_Ticket
															INNER JOIN CNF_MatrixCell					on cnf_matrixcell.matrixcellid = data_ticket.matrixcellid
										
														where VoidType = 0
															and data_ticket.activeto = @batchdate
									)p  on						((p.matrixcellid   = rr_cnf_product.matrixcellid) or(p.matrixsheetid = rr_cnf_product.matrixsheetid))

				where RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @TicketExpiredTrigger
				  and rr_cnf_revenuerecognitionRule.Enabled = 1
				  and COA_CNF_AccountConfig.Enabled = 1
				  and COA_CNF_AccountConfig.RemainingValues = 1
				)p


	end

    select 'OnTicketExpiredTrigger' as TriggerType, @BatchDate as RunDate
END

</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_RR_RevenueData_OnSaleTrigger]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_RR_RevenueData_OnSaleTrigger
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE Procedure dbo.otn_sp_RR_RevenueData_OnSaleTrigger
	@BatchDate Date,
	@RRTransDateType Integer
AS 
BEGIN

	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer
	Declare @OnSaleTrigger Integer = 1

	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1

	BEGIN
																		  
			--Normal Transaction No Remaining Values
			INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[Saleitemid]
				   ,[MatrixCellid]
				   ,[MatrixCellCode]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])
				   select *
				   from(
							select distinct coa_cnf_account.COAAccountId, 
								   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
								   RR_CNF_RevenueRecognitionRule.code,		   
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
								   COA_CNF_AccountConfig.COAAccountConfigId,
								   coa_cnf_account.COAAccountTypeId,
								   coa_cnf_account.Code as AccountCode,
								   RR_DATA_REVENUE.Transactionid as Transactionid,
								   RR_DATA_REVENUE.saleid as Saleid,
								   RR_DATA_REVENUE.SaleitemID as SaleitemID,
								   RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								   RR_DATA_REVENUE.MatrixcellCode as MatrixCode,
								   RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								   RR_DATA_REVENUE.Siteid as SiteID,
								   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								   RR_DATA_REVENUE.Workstationid as Workstationid,
								   RR_DATA_REVENUE.UserGroupid as UserGroupID,
								   RR_DATA_REVENUE.UserId as userID,
								   @BatchDate as BatchDate,
								   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
								        else DATA_Transaction.transactiondate
								   end as TransDate,
								   RR_DATA_REVENUE.Quantity as Quantity,
								   RR_DATA_REVENUE.GrossAmount as GrossAmount,
								   RR_DATA_REVENUE.NetAmount as NetAmount,
								   COA_CNF_AccountConfig.Price as ConfigPrice,
								   COA_CNF_AccountConfig.Percentage as ConfigPercentage,
								   COA_CNF_AccountConfig.RemainingValues,								
									Case when COA_CNF_AccountConfig.Price &gt; 0 then (COA_CNF_AccountConfig.Price * RR_DATA_REVENUE.Quantity) 
											else ISNULL(ABS(RR_DATA_REVENUE.RevenueAmount), 0)
									end 																		                                                                                                                                                                                              
									as RevenueAmount,

								   case when TransactionType in (5, 17, 18, 20, 22, 30) and COA_CNF_AccountConfig.Accountingtype = 1 then 2
								        when TransactionType in (5, 17, 18, 20, 22, 30) and COA_CNF_AccountConfig.Accountingtype = 2 then 1
									--	when TransactionType in (7) and rr_data_revenue.RevenueAmount &gt; 0 and COA_CNF_AccountConfig.Accountingtype = 1 then 2
										when TransactionType in (7) and rr_data_revenue.RevenueAmount &lt; 0 and COA_CNF_AccountConfig.Accountingtype = 2 then 1
								        else COA_CNF_AccountConfig.Accountingtype
									end Accountingtype,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
								   RR_CNF_RevenueRecognitionRule.Percentage,
								   RR_CNF_RevenueRecognitionRule.Days
		   
							from RR_DATA_REVENUE
									inner join rr_cnf_Product						ON ((RR_DATA_REVENUE.MATRIXCELLID = rr_cnf_Product.MATRIXCELLID) or (RR_DATA_REVENUE.MatrixSheetId = rr_cnf_Product.MatrixSheetId)) and rr_cnf_Product.Enabled = 1
									inner join RR_CNF_RevenueRecognitionRule		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_cnf_Product.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  
									INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
									INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
									INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 
									INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid

							where RR_CNF_RevenueRecognitionRule.Enabled = 1
							  and coa_cnf_account.Enabled = 1
							  and COA_CNF_AccountConfig.Enabled = 1
							  and TransactionType in (5, 7, 9, 14, 18, 20, 22, 16, 30, 101, 102, 103, 104, 105)
							  and ((coa_cnf_accountConfig.Siteid = RR_Data_Revenue.SiteId) or (coa_cnf_accountConfig.Siteid is null))
							  and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger IN (@OnSaleTrigger)
							  and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
							  and COA_CNF_AccountConfig.RemainingValues &lt;&gt; 1
							  and RR_DATA_REVENUE.fcalcdate = @BatchDate
							  and RR_DATA_REVENUE.coaaccountid = @suspendid
					)p
					where RevenueAmount &lt;&gt; 0

				----Normal Transaction with Remaining Values
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[Saleitemid]
				   ,[MatrixCellid]
				   ,[MatrixCellCode]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])
				   select *
				   from(
						select distinct coa_cnf_account.COAAccountId, 
								   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
								   RR_CNF_RevenueRecognitionRule.code,		   
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
								   COA_CNF_AccountConfig.COAAccountConfigId,
								   coa_cnf_account.COAAccountTypeId,
								   coa_cnf_account.Code as AccountCode,
								   RR_DATA_REVENUE.Transactionid as Transactionid,
								   RR_DATA_REVENUE.saleid as Saleid,
								   RR_DATA_REVENUE.SaleitemID as SaleitemID,
								   RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								   RR_DATA_REVENUE.MatrixcellCode as MatrixCode,
								   RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								   RR_DATA_REVENUE.Siteid as SiteID,
								   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								   RR_DATA_REVENUE.Workstationid as Workstationid,
								   RR_DATA_REVENUE.UserGroupid as UserGroupID,
								   RR_DATA_REVENUE.UserId as userID,
								   @BatchDate as BatchDate,
								   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
								        else DATA_Transaction.transactiondate
								   end as TransDate,
								   RR_DATA_REVENUE.Quantity as Quantity,
								   RR_DATA_REVENUE.GrossAmount as GrossAmount,
								   RR_DATA_REVENUE.NetAmount as NetAmount,
								   COA_CNF_AccountConfig.Price as ConfigPrice,
								   COA_CNF_AccountConfig.Percentage as ConfigPercentage,
								   COA_CNF_AccountConfig.RemainingValues,							 
								   ISNULL((case when (select producttaxtype 
													from data_saleitem si
												where SI.saleitemid = RR_DATA_REVENUE.Saleitemid) &lt;&gt; 1 then
																							(select ABS(sum(unitrawprice * Quantity))
																								from data_saleitem SI
																								where SI.saleitemid = RR_DATA_REVENUE.Saleitemid
																							) 
										else  (select ABS(sum((unitrawprice) * Quantity))
												from data_saleitem SI
												where SI.saleitemid = RR_DATA_REVENUE.Saleitemid)
									end
									-																		  								  								  					
									ISNULL((select ABS(sum(RevenueAmount))
												from RR_Data_Revenue rdr
												where rdr.saleitemid = RR_DATA_REVENUE.Saleitemid
													and rdr.COAAccountid NOT in (@SuspendID, @ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)
											), 0)
									), RR_DATA_REVENUE.revenueamount)
									as RevenueAmount,
								   case when TransactionType in (5, 17, 18, 20, 22, 30) and COA_CNF_AccountConfig.Accountingtype = 1 then 2
								        when TransactionType in (5, 17, 18, 20, 22, 30) and COA_CNF_AccountConfig.Accountingtype = 2 then 1
									--	when TransactionType in (7) and rr_data_revenue.RevenueAmount &gt; 0 and COA_CNF_AccountConfig.Accountingtype = 1 then 2
										when TransactionType in (7) and rr_data_revenue.RevenueAmount &lt; 0 and COA_CNF_AccountConfig.Accountingtype = 2 then 1
								        else COA_CNF_AccountConfig.Accountingtype
									end Accountingtype,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
								   RR_CNF_RevenueRecognitionRule.Percentage,
								   RR_CNF_RevenueRecognitionRule.Days

						from RR_DATA_REVENUE
								inner join rr_cnf_Product						ON ((RR_DATA_REVENUE.MATRIXCELLID = rr_cnf_Product.MATRIXCELLID) or (RR_DATA_REVENUE.MatrixSheetId = rr_cnf_Product.MatrixSheetId)) and rr_cnf_Product.Enabled = 1
								inner join RR_CNF_RevenueRecognitionRule		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_cnf_Product.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  
								INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
								INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
								INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 
								INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid

							where RR_CNF_RevenueRecognitionRule.Enabled = 1
							  and coa_cnf_account.Enabled = 1
							  and COA_CNF_AccountConfig.Enabled = 1
							  and TransactionType in (5, 7, 9, 14, 18, 20, 22, 16, 30, 101, 102, 103, 104, 105)
							  and ((coa_cnf_accountConfig.Siteid = RR_Data_Revenue.SiteId) or (coa_cnf_accountConfig.Siteid is null))
							  and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger IN (@OnSaleTrigger)
							  and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
							  and COA_CNF_AccountConfig.RemainingValues = 1
							  and RR_DATA_REVENUE.fcalcdate = @BatchDate
							  and RR_DATA_REVENUE.coaaccountid = @suspendid
					)p
					where RevenueAmount &lt;&gt; 0


--Reverse of a Deposit 
			INSERT INTO [dbo].[RR_DATA_Revenue]
					   ([COAAccountId]
					   ,[RevenueRecognitionRuleId]
					   ,[RRCode]
					   ,[RRCalcTypeWhere]
					   ,[RRCalcTypeMethod]
					   ,[COAAccountConfigId]
					   ,[COAAccountType]
					   ,[COAAccountCode]
					   ,[TransactionId]
					   ,[SaleId]
					   ,[SiteId]
					   ,[OperatingAreaId]
					   ,[WorkstationId]
					   ,[UserGroupId]
					   ,[UserId]
					   ,[FCalcDate]
					   ,[FRevenueDate]
					   ,[Quantity]
					   ,[GrossAmount]
					   ,[NetAmount]
					   ,[Price]
					   ,[Percentage]
					   ,[RemaningValues]
					   ,[RevenueAmount]
					   ,[AccountingType]
					   ,[RRCalcTypeTrigger]
					   ,[RRPercentage]
					   ,[RRDays])
			select distinct RR_DATA_REVENUE.COAAccountId, 
								RR_DATA_REVENUE.RevenueRecognitionRuleId,
								RR_DATA_REVENUE.rrcode,		   
								RR_DATA_REVENUE.RRCalcTypeWhere,
								RR_DATA_REVENUE.RRCalcTypeMethod,	   
								RR_DATA_REVENUE.COAAccountConfigId,
								RR_DATA_REVENUE.COAAccountType,
								RR_DATA_REVENUE.COAAccountCode,
								p.Transactionid as Transactionid,					
								ISNULL(p.saleid, RR_DATA_REVENUE.saleid) as Saleid,
								p.Siteid as SiteID,
								p.OperatingAreaId as OperatingAreaID,
								p.Workstationid as Workstationid,
								p.UserGroupid as UserGroupID,
								p.UserId as userID,
								@BatchDate as BatchDate,
								case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
								     else DATA_Transaction.transactiondate
								end as TransDate,
								RR_DATA_REVENUE.Quantity as Quantity,
								RR_DATA_REVENUE.GrossAmount as GrossAmount,
								RR_DATA_REVENUE.NetAmount as NetAmount,
								RR_DATA_REVENUE.Price as ConfigPrice,
								RR_DATA_REVENUE.Percentage as ConfigPercentage,
								RR_DATA_REVENUE.RemaningValues, 
								RR_DATA_REVENUE.revenueamount  as RevenueAmount,
								case when RR_DATA_REVENUE.accountingtype = 1 then 2
								     else 1
								end as Accountingtype,
								RR_DATA_REVENUE.RRCalcTypeTrigger,
								RR_DATA_REVENUE.rrPercentage,
								RR_DATA_REVENUE.rrDays			
							from RR_DATA_REVENUE
									INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
									INNER JOIN (select distinct RR_DATA_REVENUE.Accountingtype, rr_data_revenue.siteid, rr_data_revenue.transactionid, rr_data_revenue.saleid, rr_data_revenue.Operatingareaid, rr_data_revenue.workstationid, rr_data_revenue.usergroupid, rr_data_revenue.userid
												  from rr_data_revenue
														INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
												  where  DATA_Transaction.transactiontype = 16 and data_transaction.paid = 1
												  and RR_DATA_REVENUE.FCalcDate = @BatchDate
												  and rr_data_revenue.coaaccountid = @suspendid
												  and rr_data_revenue.usergroupid is not null
											   )p    on p.saleid = rr_data_revenue.saleid

							where transactiontype in (12)	
							and rr_data_revenue.coaaccountid not in (select coaaccountid
																	   from cnf_paymentMethod
																	  where coaaccountid is not null
																	  Union all
																	  select coaaccountid
																	   from cnf_paymentcard
																	  where coaaccountid is not null
																	  Union all 
																	  select coaaccountid
																	   from cnf_tax
																	  where coaaccountid is not null
																	  Union all 
																	  select coaaccountid
																	   from cnf_promotion
																	  where coaaccountid is not null
																	 )											  										
									and RR_DATA_REVENUE.fcalcdate = @BatchDate
									and RR_DATA_REVENUE.coaaccountid not in  (@suspendid, @ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)



				
		exec otn_sp_RR_RevenueData_PaymentMethodTaxDiscounts @BatchDate, '5, 7, 9, 14, 18, 20, 22, 16, 30, 101, 102, 103, 104, 105,',   @OnSaleTrigger, @RRTransDateType
																																																																																													
		End

	select 'OnSalePaidTrigger' as TriggerType, @BatchDate as RunDate
END

</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_RR_RevenueData_OnMoneyRefundTrigger]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_RR_RevenueData_OnMoneyRefundTrigger
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE Procedure dbo.otn_sp_RR_RevenueData_OnMoneyRefundTrigger
	@BatchDate Date,
	@RRTransDateType Integer
AS 
BEGIN

	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer
	Declare @MoneyRefund Integer = 6

	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1

	
		BEGIN

			--Normal Transaction No Remaining Values
			INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[Saleitemid]
				   ,[MatrixCellid]
				   ,[MatrixCellCode]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				   ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])
				   select *
				   from (
					select distinct p.COAAccountId, 
								p.RevenueRecognitionRuleId,
								p.code,		   
								p.RRCalcTypeWhere,
								p.RRCalcTypeMethod,	   
								p.COAAccountConfigId,
								p.COAAccountTypeId,
								p.AccountCode,
								RR_DATA_REVENUE.Transactionid as Transactionid,
								RR_DATA_REVENUE.saleid as Saleid,
								RR_DATA_REVENUE.SaleitemID as SaleitemID,
								RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								RR_DATA_REVENUE.MatrixcellCode as MatrixCode,
								RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								RR_DATA_REVENUE.Siteid as SiteID,
								RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								RR_DATA_REVENUE.Workstationid as Workstationid,
								RR_DATA_REVENUE.UserGroupid as UserGroupID,
								RR_DATA_REVENUE.UserId as userID,
								@BatchDate as BatchDate,
								case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
								     else DATA_Transaction.transactiondate
								end as TransDate,
								RR_DATA_REVENUE.Quantity as Quantity,
								RR_DATA_REVENUE.GrossAmount as GrossAmount,
								RR_DATA_REVENUE.NetAmount as NetAmount,
								p.Price as ConfigPrice,
								p.Percentage as ConfigPercentage,
								p.RemainingValues,
								(CASE WHEN p.coaaccountid not in (@ACCPaymentMethod, @TaxAccountID, @DiscountAccountID) then   --Accounts not Tax not PaymentMethods 
									Case when p.Price &gt; 0 then (p.Price * RR_DATA_REVENUE.Quantity) 
											else (ISNULL((((ABS(RR_DATA_REVENUE.RevenueAmount)) - ISNULL((select (ABS((sum(TaxAmount) * RR_DATA_REVENUE.Quantity)))
																									from data_saleitemTax
																									where saleitemid = RR_DATA_REVENUE.SaleitemID), 0)) * p.Percentage/100), 0))
									end 																		                                                                                                                                                                                              
								end)  as RevenueAmount,
								case when TransactionType in (5, 13, 17, 18, 20, 22, 30) and p.Accountingtype = 1 then 2
										when TransactionType in (5, 13, 17, 18, 20, 22, 30) and p.Accountingtype = 2 then 1
										when TransactionType in (7) and rr_data_revenue.RevenueAmount &lt; 0 and p.Accountingtype = 1 then 2
										when TransactionType in (7) and rr_data_revenue.RevenueAmount &lt; 0 and p.Accountingtype = 2 then 1
										else p.Accountingtype
									end Accountingtype,
									p.RRCalcTypeTrigger,
									p.rrPercentage,
									p.Days						
						
						
							from RR_DATA_REVENUE
								INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
								INNER JOIN (select '1' as PCOAAccountid, 
												   coa_cnf_accountConfig.Siteid, 
												   RR_CNF_RevenueRecognitionRule.Enabled, 
												   RR_CNF_RevenueRecognitionRule.FromDate, 
												   RR_CNF_RevenueRecognitionRule.ToDate,
												   COA_CNF_AccountConfig.RemainingValues,
												   coa_cnf_account.coaaccountid,
												   COA_CNF_AccountConfig.Price,
												   COA_CNF_AccountConfig.Percentage,
												   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
												   RR_CNF_RevenueRecognitionRule.code,		   
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
												   COA_CNF_AccountConfig.COAAccountConfigId,
												   coa_cnf_account.COAAccountTypeId,
												   coa_cnf_account.Code as accountcode,
												   coa_cnf_accountconfig.Accountingtype,
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
												   RR_CNF_RevenueRecognitionRule.Percentage rrPercentage,
												   RR_CNF_RevenueRecognitionRule.Days	

												from RR_CNF_RevenueRecognitionRule	
												INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
												INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid and coa_cnf_account.Enabled = 1
												INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
											where  RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @MoneyRefund
											and RR_CNF_RevenueRecognitionRule.Enabled = 1
											and coa_cnf_account.coaaccountid not in (@ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)) p				on p.PCOAAccountid = rr_data_revenue.coaaccountid 

							where transactiontype in (13)													 
								and p.Enabled = 1
								and ((p.Siteid = RR_DATA_REVENUE.Siteid) or (p.Siteid is null))
								and @BatchDate between p.FromDate and p.ToDate
								and p.RemainingValues &lt;&gt; 1
								and RR_DATA_REVENUE.fcalcdate = @BatchDate
					)r 
					where r.revenueAmount &lt;&gt; 0


				--Normal Transaction with Remaining Values
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[Saleitemid]
				   ,[MatrixCellid]
				   ,[MatrixCellCode]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])
				   select *
				   from (
					select distinct p.COAAccountId, 
								p.RevenueRecognitionRuleId,
								p.code,		   
								p.RRCalcTypeWhere,
								p.RRCalcTypeMethod,	   
								p.COAAccountConfigId,
								p.COAAccountTypeId,
								p.AccountCode,
								RR_DATA_REVENUE.Transactionid as Transactionid,
								RR_DATA_REVENUE.saleid as Saleid,
								RR_DATA_REVENUE.SaleitemID as SaleitemID,
								RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								RR_DATA_REVENUE.MatrixcellCode as MatrixCode,
								RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								RR_DATA_REVENUE.Siteid as SiteID,
								RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								RR_DATA_REVENUE.Workstationid as Workstationid,
								RR_DATA_REVENUE.UserGroupid as UserGroupID,
								RR_DATA_REVENUE.UserId as userID,
								@BatchDate as BatchDate,
								case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
								     else DATA_Transaction.transactiondate
								  end as TransDate,
								RR_DATA_REVENUE.Quantity as Quantity,
								RR_DATA_REVENUE.GrossAmount as GrossAmount,
								RR_DATA_REVENUE.NetAmount as NetAmount,
								p.Price as ConfigPrice,
								p.Percentage as ConfigPercentage,
								p.RemainingValues,
								CASE WHEN p.coaaccountid not in (@ACCPaymentMethod, @TaxAccountID, @DiscountAccountID) then																																													 
							    ABS(ABS(RR_DATA_REVENUE.RevenueAmount) -					 
								ISNULL((select ABS(sum(RevenueAmount))
										from RR_DATA_Revenue rrd
									    where rrd.RevenueRecognitionRuleId = p.RevenueRecognitionRuleId
										and rrd.RevenueRecognitionRuleId not in (@SuspendID, @ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)
										and rrd.transactionid = RR_DATA_REVENUE.transactionid
								), 0)) 
								else 0
								end RevenueAmount,
								case when TransactionType in (5, 13, 17, 18, 20, 22, 30) and p.Accountingtype = 1 then 2
										when TransactionType in (5, 13, 17, 18, 20, 22, 30) and p.Accountingtype = 2 then 1
										when TransactionType in (7) and rr_data_revenue.RevenueAmount &lt; 0 and p.Accountingtype = 1 then 2
										when TransactionType in (7) and rr_data_revenue.RevenueAmount &lt; 0 and p.Accountingtype = 2 then 1
										else p.Accountingtype
									end Accountingtype,
									p.RRCalcTypeTrigger,
									p.rrPercentage,
									p.Days						
						
						
							from RR_DATA_REVENUE
								INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
								INNER JOIN (select '1' as PCOAAccountid, 
												   coa_cnf_accountConfig.Siteid, 
												   RR_CNF_RevenueRecognitionRule.Enabled, 
												   RR_CNF_RevenueRecognitionRule.FromDate, 
												   RR_CNF_RevenueRecognitionRule.ToDate,
												   COA_CNF_AccountConfig.RemainingValues,
												   coa_cnf_account.coaaccountid,
												   COA_CNF_AccountConfig.Price,
												   COA_CNF_AccountConfig.Percentage,
												   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
												   RR_CNF_RevenueRecognitionRule.code,		   
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
												   COA_CNF_AccountConfig.COAAccountConfigId,
												   coa_cnf_account.COAAccountTypeId,
												   coa_cnf_account.Code as accountcode,
												   coa_cnf_accountconfig.Accountingtype,
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
												   RR_CNF_RevenueRecognitionRule.Percentage rrPercentage,
												   RR_CNF_RevenueRecognitionRule.Days	

												from RR_CNF_RevenueRecognitionRule	
												INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
												INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid and coa_cnf_account.Enabled = 1
												INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
											where  RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @MoneyRefund
											and RR_CNF_RevenueRecognitionRule.Enabled = 1
											and coa_cnf_account.coaaccountid not in (@ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)) p				on p.PCOAAccountid = rr_data_revenue.coaaccountid 

							where transactiontype in (13)													 
								and p.Enabled = 1
								and ((p.Siteid = RR_DATA_REVENUE.Siteid) or (p.Siteid is null))
								and @BatchDate between p.FromDate and p.ToDate
								and p.RemainingValues = 1
								and RR_DATA_REVENUE.fcalcdate = @BatchDate		
					)r 
					where r.revenueAmount &lt;&gt; 0

				exec otn_sp_RR_RevenueData_PaymentMethodTaxDiscounts2 @BatchDate, '13,',   @MoneyRefund, @RRTransDateType
	end

	select 'OnMoneyRefundTrigger' as TriggerType, @BatchDate as RunDate

END

</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_RR_RevenueData_OnMoneyCardLoad]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_RR_RevenueData_OnMoneyCardLoad
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE Procedure dbo.otn_sp_RR_RevenueData_OnMoneyCardLoad
	@BatchDate Date,
	@RRTransDateType Integer
AS 
BEGIN
	
	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer
	Declare @OnMoneyCardCashOut Integer = 10

	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1


		BEGIN

			--Normal Transaction No Remaining Values
			INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[Saleitemid]
				   ,[MatrixCellid]
				   ,[MatrixCellCode]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])
				   select *
				   from(
							select coa_cnf_account.COAAccountId, 
								   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
								   RR_CNF_RevenueRecognitionRule.code,		   
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
								   COA_CNF_AccountConfig.COAAccountConfigId,
								   coa_cnf_account.COAAccountTypeId,
								   coa_cnf_account.Code as AccountCode,
								   RR_DATA_REVENUE.Transactionid as Transactionid,
								   RR_DATA_REVENUE.saleid as Saleid,
								   RR_DATA_REVENUE.SaleitemID as SaleitemID,
								   RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								   RR_DATA_REVENUE.MatrixcellCode as MatrixCode,
								   RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								   RR_DATA_REVENUE.Siteid as SiteID,
								   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								   RR_DATA_REVENUE.Workstationid as Workstationid,
								   RR_DATA_REVENUE.UserGroupid as UserGroupID,
								   RR_DATA_REVENUE.UserId as userID,
								   @BatchDate as BatchDate,
								   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
								        else DATA_Transaction.transactiondate
								   end as TransDate,
								   RR_DATA_REVENUE.Quantity as Quantity,
								   RR_DATA_REVENUE.GrossAmount as GrossAmount,
								   RR_DATA_REVENUE.NetAmount as NetAmount,
								   COA_CNF_AccountConfig.Price as ConfigPrice,
								   COA_CNF_AccountConfig.Percentage as ConfigPercentage,
								   COA_CNF_AccountConfig.RemainingValues,																		
									(CASE WHEN coa_cnf_account.coaaccountid not in (@ACCPaymentMethod, @TaxAccountID, @DiscountAccountID) then   --Accounts not Tax not PaymentMethods 
										Case when COA_CNF_AccountConfig.Price &gt; 0 then (COA_CNF_AccountConfig.Price * RR_DATA_REVENUE.Quantity) 
												else (ISNULL(((ABS((select unitrecharge
											   from data_saleitem
											   where saleid = RR_DATA_REVENUE.saleid
											))) * COA_CNF_AccountConfig.Percentage/100), 0))
										end 																		                                                                                                                                                                                              
									end)  as RevenueAmount,

								   COA_CNF_AccountConfig.Accountingtype,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
								   RR_CNF_RevenueRecognitionRule.Percentage,
								   RR_CNF_RevenueRecognitionRule.Days
		   
							from RR_DATA_REVENUE
									inner join rr_cnf_Product						ON ((RR_DATA_REVENUE.MATRIXCELLID = rr_cnf_Product.MATRIXCELLID) or (RR_DATA_REVENUE.MatrixSheetId = rr_cnf_Product.MatrixSheetId)) and rr_cnf_Product.Enabled = 1
									inner join RR_CNF_RevenueRecognitionRule		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_cnf_Product.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  
									INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
									INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
									INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 
									INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid

							where RR_CNF_RevenueRecognitionRule.Enabled = 1
							  and coa_cnf_account.Enabled = 1
							  and COA_CNF_AccountConfig.Enabled = 1
							  and ((TransactionType in (10)) or (RR_DATA_REVENUE.transactionid in (select transactionid
																									 from data_transaction
																										Inner join data_saleitem   on data_saleitem.saleid = data_transaction.saleid
																									where data_transaction.transactiontype in (14)
																									  and data_saleitem.unitrecharge &lt;&gt; 0
																								 )
																))
							  and ((coa_cnf_accountConfig.Siteid = RR_DATA_REVENUE.SiteId) or (coa_cnf_accountConfig.Siteid is null))
							  and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger IN (@OnMoneyCardCashOut)
							  and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
							  and COA_CNF_AccountConfig.RemainingValues &lt;&gt; 1
							  and RR_DATA_REVENUE.fcalcdate = @BatchDate
							  and RR_DATA_REVENUE.coaaccountid = @suspendid
						
					)p
					where RevenueAmount &lt;&gt; 0

				--Normal Transaction with Remaining Values
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[Saleitemid]
				   ,[MatrixCellid]
				   ,[MatrixCellCode]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])
				   select *
				   from(
						select distinct coa_cnf_account.COAAccountId, 
								   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
								   RR_CNF_RevenueRecognitionRule.code,		   
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
								   COA_CNF_AccountConfig.COAAccountConfigId,
								   coa_cnf_account.COAAccountTypeId,
								   coa_cnf_account.Code as AccountCode,
								   RR_DATA_REVENUE.Transactionid as Transactionid,
								   RR_DATA_REVENUE.saleid as Saleid,
								   RR_DATA_REVENUE.SaleitemID as SaleitemID,
								   RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								   RR_DATA_REVENUE.MatrixcellCode as MatrixCode,
								   RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								   RR_DATA_REVENUE.Siteid as SiteID,
								   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								   RR_DATA_REVENUE.Workstationid as Workstationid,
								   RR_DATA_REVENUE.UserGroupid as UserGroupID,
								   RR_DATA_REVENUE.UserId as userID,
								   @BatchDate as BatchDate,
								   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
								        else DATA_Transaction.transactiondate
								   end as TransDate,
								   RR_DATA_REVENUE.Quantity as Quantity,
								   RR_DATA_REVENUE.GrossAmount as GrossAmount,
								   RR_DATA_REVENUE.NetAmount as NetAmount,
								   COA_CNF_AccountConfig.Price as ConfigPrice,
								   COA_CNF_AccountConfig.Percentage as ConfigPercentage,
								   COA_CNF_AccountConfig.RemainingValues,							 
								   ISNULL((RR_DATA_REVENUE.RevenueAmount - (select ISNULL(sum(revenueamount), 0)
								                            from RR_DATA_Revenue rr
												              where rr.saleitemid = RR_DATA_REVENUE.SaleitemID
												        and rr.COAAccountid not in (@SuspendID, @ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)
												 )
									), 0)
									as RevenueAmount,
								   case when TransactionType in (5, 17, 18, 20, 22, 30) and COA_CNF_AccountConfig.Accountingtype = 1 then 2
								        when TransactionType in (5, 17, 18, 20, 22, 30) and COA_CNF_AccountConfig.Accountingtype = 2 then 1
								        else COA_CNF_AccountConfig.Accountingtype
									end Accountingtype,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
								   RR_CNF_RevenueRecognitionRule.Percentage,
								   RR_CNF_RevenueRecognitionRule.Days

						from RR_DATA_REVENUE
								inner join rr_cnf_Product						ON ((RR_DATA_REVENUE.MATRIXCELLID = rr_cnf_Product.MATRIXCELLID) or (RR_DATA_REVENUE.MatrixSheetId = rr_cnf_Product.MatrixSheetId)) and rr_cnf_Product.Enabled = 1
								inner join RR_CNF_RevenueRecognitionRule		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_cnf_Product.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  
								INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
								INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
								INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 
								INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid

							where RR_CNF_RevenueRecognitionRule.Enabled = 1
							  and coa_cnf_account.Enabled = 1
							  and COA_CNF_AccountConfig.Enabled = 1
							  and TransactionType in (10)
							  and ((coa_cnf_accountConfig.Siteid = RR_DATA_REVENUE.SiteId) or (coa_cnf_accountConfig.Siteid is null))
							  and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger IN (@OnMoneyCardCashOut)
							  and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
							  and COA_CNF_AccountConfig.RemainingValues = 1
							  and RR_DATA_REVENUE.fcalcdate = @BatchDate
							  and RR_DATA_REVENUE.coaaccountid = @suspendid
					)p
					where RevenueAmount &lt;&gt; 0

		
		exec otn_sp_RR_RevenueData_PaymentMethodTaxDiscounts @BatchDate, '10,', @OnMoneyCardCashOut, @RRTransDateType									

	end
	select '@OnMoneyCardLoad' as TriggerType, @BatchDate as RunDate
END

</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_RR_RevenueData_OnMoneyCardCashOut]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_RR_RevenueData_OnMoneyCardCashOut
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE Procedure dbo.otn_sp_RR_RevenueData_OnMoneyCardCashOut
	@BatchDate Date,
	@RRTransDateType Integer
AS 
BEGIN
	
	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer
	Declare @OnMoneyCardCashOut Integer = 11

	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1


		BEGIN

			--Normal Transaction No Remaining Values
			INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[Saleitemid]
				   ,[MatrixCellid]
				   ,[MatrixCellCode]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])
				   select *
				   from(
							select coa_cnf_account.COAAccountId, 
								   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
								   RR_CNF_RevenueRecognitionRule.code,		   
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
								   COA_CNF_AccountConfig.COAAccountConfigId,
								   coa_cnf_account.COAAccountTypeId,
								   coa_cnf_account.Code as AccountCode,
								   RR_DATA_REVENUE.Transactionid as Transactionid,
								   RR_DATA_REVENUE.saleid as Saleid,
								   RR_DATA_REVENUE.SaleitemID as SaleitemID,
								   RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								   RR_DATA_REVENUE.MatrixcellCode as MatrixCode,
								   RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								   RR_DATA_REVENUE.Siteid as SiteID,
								   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								   RR_DATA_REVENUE.Workstationid as Workstationid,
								   RR_DATA_REVENUE.UserGroupid as UserGroupID,
								   RR_DATA_REVENUE.UserId as userID,
								   @BatchDate as BatchDate,
								   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
								        else DATA_Transaction.transactiondate
								   end as TransDate,
								   RR_DATA_REVENUE.Quantity as Quantity,
								   RR_DATA_REVENUE.GrossAmount as GrossAmount,
								   RR_DATA_REVENUE.NetAmount as NetAmount,
								   COA_CNF_AccountConfig.Price as ConfigPrice,
								   COA_CNF_AccountConfig.Percentage as ConfigPercentage,
								   COA_CNF_AccountConfig.RemainingValues,																		
									(CASE WHEN coa_cnf_account.coaaccountid not in (@ACCPaymentMethod, @TaxAccountID, @DiscountAccountID) then   --Accounts not Tax not PaymentMethods 
										Case when COA_CNF_AccountConfig.Price &gt; 0 then (COA_CNF_AccountConfig.Price * RR_DATA_REVENUE.Quantity) 
												else (ISNULL((((ABS(RR_DATA_REVENUE.RevenueAmount)) - ISNULL((select (ABS((sum(TaxAmount) * RR_DATA_REVENUE.Quantity)))
																										from data_saleitemTax
																										where saleitemid = RR_DATA_REVENUE.SaleitemID), 0)) * COA_CNF_AccountConfig.Percentage/100), 0))
										end 																		                                                                                                                                                                                              
									end)  as RevenueAmount,

								   COA_CNF_AccountConfig.Accountingtype,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
								   RR_CNF_RevenueRecognitionRule.Percentage,
								   RR_CNF_RevenueRecognitionRule.Days
		   
							from RR_DATA_REVENUE
									inner join rr_cnf_Product						ON ((RR_DATA_REVENUE.MATRIXCELLID = rr_cnf_Product.MATRIXCELLID) or (RR_DATA_REVENUE.MatrixSheetId = rr_cnf_Product.MatrixSheetId)) and rr_cnf_Product.Enabled = 1
									inner join RR_CNF_RevenueRecognitionRule		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_cnf_Product.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  
									INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
									INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
									INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 
									INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid

							where RR_CNF_RevenueRecognitionRule.Enabled = 1
							  and coa_cnf_account.Enabled = 1
							  and COA_CNF_AccountConfig.Enabled = 1
							  and TransactionType in (31)
							  and ((coa_cnf_accountConfig.Siteid = RR_DATA_REVENUE.SiteId) or (coa_cnf_accountConfig.Siteid is null))
							  and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger IN (@OnMoneyCardCashOut)
							  and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
							  and COA_CNF_AccountConfig.RemainingValues &lt;&gt; 1
							  and RR_DATA_REVENUE.fcalcdate = @BatchDate
							  and RR_DATA_REVENUE.coaaccountid = @suspendid
						
					)p
					where RevenueAmount &lt;&gt; 0

				--Normal Transaction with Remaining Values
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[Saleitemid]
				   ,[MatrixCellid]
				   ,[MatrixCellCode]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])
				   select *
				   from(
						select distinct coa_cnf_account.COAAccountId, 
								   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
								   RR_CNF_RevenueRecognitionRule.code,		   
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
								   COA_CNF_AccountConfig.COAAccountConfigId,
								   coa_cnf_account.COAAccountTypeId,
								   coa_cnf_account.Code as AccountCode,
								   RR_DATA_REVENUE.Transactionid as Transactionid,
								   RR_DATA_REVENUE.saleid as Saleid,
								   RR_DATA_REVENUE.SaleitemID as SaleitemID,
								   RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								   RR_DATA_REVENUE.MatrixcellCode as MatrixCode,
								   RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								   RR_DATA_REVENUE.Siteid as SiteID,
								   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								   RR_DATA_REVENUE.Workstationid as Workstationid,
								   RR_DATA_REVENUE.UserGroupid as UserGroupID,
								   RR_DATA_REVENUE.UserId as userID,
								   @BatchDate as BatchDate,
								   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
								        else DATA_Transaction.transactiondate
								   end as TransDate,
								   RR_DATA_REVENUE.Quantity as Quantity,
								   RR_DATA_REVENUE.GrossAmount as GrossAmount,
								   RR_DATA_REVENUE.NetAmount as NetAmount,
								   COA_CNF_AccountConfig.Price as ConfigPrice,
								   COA_CNF_AccountConfig.Percentage as ConfigPercentage,
								   COA_CNF_AccountConfig.RemainingValues,							 
								   ISNULL((RR_DATA_REVENUE.RevenueAmount - (select ISNULL(sum(revenueamount), 0)
								                            from RR_DATA_Revenue rr
												              where rr.saleitemid = RR_DATA_REVENUE.SaleitemID
												        and rr.COAAccountid not in (@SuspendID, @ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)
												 )
									), 0)
									as RevenueAmount,
								   case when TransactionType in (5, 17, 18, 20, 22, 30) and COA_CNF_AccountConfig.Accountingtype = 1 then 2
								        when TransactionType in (5, 17, 18, 20, 22, 30) and COA_CNF_AccountConfig.Accountingtype = 2 then 1
								        else COA_CNF_AccountConfig.Accountingtype
									end Accountingtype,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
								   RR_CNF_RevenueRecognitionRule.Percentage,
								   RR_CNF_RevenueRecognitionRule.Days

						from RR_DATA_REVENUE
								inner join rr_cnf_Product						ON ((RR_DATA_REVENUE.MATRIXCELLID = rr_cnf_Product.MATRIXCELLID) or (RR_DATA_REVENUE.MatrixSheetId = rr_cnf_Product.MatrixSheetId)) and rr_cnf_Product.Enabled = 1
								inner join RR_CNF_RevenueRecognitionRule		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_cnf_Product.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  
								INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
								INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
								INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 
								INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid

							where RR_CNF_RevenueRecognitionRule.Enabled = 1
							  and coa_cnf_account.Enabled = 1
							  and COA_CNF_AccountConfig.Enabled = 1
							  and TransactionType in (31)
							  and ((coa_cnf_accountConfig.Siteid = RR_DATA_REVENUE.SiteId) or (coa_cnf_accountConfig.Siteid is null))
							  and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger IN (@OnMoneyCardCashOut)
							  and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
							  and COA_CNF_AccountConfig.RemainingValues = 1
							  and RR_DATA_REVENUE.fcalcdate = @BatchDate
							  and RR_DATA_REVENUE.coaaccountid = @suspendid
					)p
					where RevenueAmount &lt;&gt; 0

		
		exec otn_sp_RR_RevenueData_PaymentMethodTaxDiscounts @BatchDate, '31,', @OnMoneyCardCashOut, @RRTransDateType									

	end
	select '@OnMoneyCardCashOut' as TriggerType, @BatchDate as RunDate
END

</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_RR_RevenueData_OnFlexContractPayment]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_RR_RevenueData_OnFlexContractPayment
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE Procedure dbo.otn_sp_RR_RevenueData_OnFlexContractPayment
	@BatchDate Date,
	@RRTransDateType Integer
AS 
BEGIN

	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer
	Declare @OnFlexPaymentTrigger Integer = 14


	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1

 
		BEGIN

			--Normal Transaction No Remaining Values
			INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[Saleitemid]
				   ,[MatrixCellid]
				   ,[MatrixCellCode]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])
				   select *
				   from(
								select distinct coa_cnf_account.COAAccountId, 
								   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
								   RR_CNF_RevenueRecognitionRule.code,		   
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
								   COA_CNF_AccountConfig.COAAccountConfigId,
								   coa_cnf_account.COAAccountTypeId,
								   coa_cnf_account.Code as AccountCode,
								   RR_DATA_REVENUE.Transactionid as Transactionid,
								   RR_DATA_REVENUE.saleid as Saleid,
								   RR_DATA_REVENUE.SaleitemID as SaleitemID,
								   RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								   RR_DATA_REVENUE.MatrixcellCode as MatrixCode,
								   RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								   RR_DATA_REVENUE.Siteid as SiteID,
								   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								   RR_DATA_REVENUE.Workstationid as Workstationid,
								   RR_DATA_REVENUE.UserGroupid as UserGroupID,
								   RR_DATA_REVENUE.UserId as userID,
								   @BatchDate as BatchDate,
								   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
								        else DATA_Transaction.transactiondate
								   end as TransDate,
								   RR_DATA_REVENUE.Quantity as Quantity,
								   RR_DATA_REVENUE.GrossAmount as GrossAmount,
								   RR_DATA_REVENUE.NetAmount as NetAmount,
								   COA_CNF_AccountConfig.Price as ConfigPrice,
								   COA_CNF_AccountConfig.Percentage as ConfigPercentage,
								   COA_CNF_AccountConfig.RemainingValues,								
								   (CASE WHEN coa_cnf_account.coaaccountid not in (@ACCPaymentMethod, @TaxAccountID, @DiscountAccountID) then   --Accounts not Tax not PaymentMethods 
										Case when COA_CNF_AccountConfig.Price &gt; 0 then (COA_CNF_AccountConfig.Price * RR_DATA_REVENUE.Quantity) 
												else (ISNULL((((ABS(RR_DATA_REVENUE.RevenueAmount)) - ISNULL((select (ABS((sum(TaxAmount) * RR_DATA_REVENUE.Quantity)))
																										from data_saleitemTax
																										where saleitemid = RR_DATA_REVENUE.SaleitemID), 0)) * COA_CNF_AccountConfig.Percentage/100), 0))
										end 																		                                                                                                                                                                                              
									end)  as RevenueAmount,

										case when DATA_Transaction.TransactionType in (46, 47) and COA_CNF_AccountConfig.Accountingtype = 1 then 2
								        when DATA_Transaction.TransactionType in (46, 47) and COA_CNF_AccountConfig.Accountingtype = 2 then 1
								        else COA_CNF_AccountConfig.Accountingtype
									end Accountingtype,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
								   RR_CNF_RevenueRecognitionRule.Percentage,
								   RR_CNF_RevenueRecognitionRule.Days
		   
							from RR_DATA_REVENUE
									inner join rr_cnf_Product						ON ((RR_DATA_REVENUE.MATRIXCELLID = rr_cnf_Product.MATRIXCELLID) or (RR_DATA_REVENUE.MatrixSheetId = rr_cnf_Product.MatrixSheetId)) and rr_cnf_Product.Enabled = 1
									inner join RR_CNF_RevenueRecognitionRule		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_cnf_Product.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  
									INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
									INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
									INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 
									INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid

							where RR_CNF_RevenueRecognitionRule.Enabled = 1
							  and coa_cnf_account.Enabled = 1
							  and COA_CNF_AccountConfig.Enabled = 1
							  and TransactionType in (33, 34, 44, 45, 46, 47, 53)
							  and ((coa_cnf_accountConfig.Siteid = RR_Data_Revenue.SiteId) or (coa_cnf_accountConfig.Siteid is null))
							  and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger IN (@OnFlexPaymentTrigger)
							  and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
							  and COA_CNF_AccountConfig.RemainingValues &lt;&gt; 1
							  and RR_DATA_REVENUE.fcalcdate = @BatchDate
							  and RR_DATA_REVENUE.coaaccountid = @suspendid
					)p
					where RevenueAmount &lt;&gt; 0


			----Normal Transaction with Remaining Values
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[Saleitemid]
				   ,[MatrixCellid]
				   ,[MatrixCellCode]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])
				   select *
				   from(
						select distinct coa_cnf_account.COAAccountId, 
								   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
								   RR_CNF_RevenueRecognitionRule.code,		   
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
								   COA_CNF_AccountConfig.COAAccountConfigId,
								   coa_cnf_account.COAAccountTypeId,
								   coa_cnf_account.Code as AccountCode,
								   RR_DATA_REVENUE.Transactionid as Transactionid,
								   RR_DATA_REVENUE.saleid as Saleid,
								   RR_DATA_REVENUE.SaleitemID as SaleitemID,
								   RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								   RR_DATA_REVENUE.MatrixcellCode as MatrixCode,
								   RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								   RR_DATA_REVENUE.Siteid as SiteID,
								   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								   RR_DATA_REVENUE.Workstationid as Workstationid,
								   RR_DATA_REVENUE.UserGroupid as UserGroupID,
								   RR_DATA_REVENUE.UserId as userID,
								   @BatchDate as BatchDate,
								   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
								        else DATA_Transaction.transactiondate
								   end as TransDate,
								   RR_DATA_REVENUE.Quantity as Quantity,
								   RR_DATA_REVENUE.GrossAmount as GrossAmount,
								   RR_DATA_REVENUE.NetAmount as NetAmount,
								   COA_CNF_AccountConfig.Price as ConfigPrice,
								   COA_CNF_AccountConfig.Percentage as ConfigPercentage,
								   COA_CNF_AccountConfig.RemainingValues,							 
								   ISNULL((case when (select producttaxtype 
													from data_saleitem si
												where SI.saleitemid = RR_DATA_REVENUE.Saleitemid) &lt;&gt; 1 then
																							(select ABS(sum(unitrawprice * Quantity))
																								from data_saleitem SI
																								where SI.saleitemid = RR_DATA_REVENUE.Saleitemid
																							) 
										else  (select ABS(sum((unitrawprice - UnitTaxes) * Quantity))
												from data_saleitem SI
												where SI.saleitemid = RR_DATA_REVENUE.Saleitemid)
									end
									-																		  								  								  					
									ISNULL((select ABS(sum(RevenueAmount))
												from RR_Data_Revenue rdr
												where rdr.saleitemid = RR_DATA_REVENUE.Saleitemid
													and rdr.COAAccountid NOT in (@SuspendID, @ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)
											), 0)
									), RR_DATA_REVENUE.revenueamount)
									as RevenueAmount,
									case when DATA_Transaction.TransactionType in (46, 47) and COA_CNF_AccountConfig.Accountingtype = 1 then 2
								        when DATA_Transaction.TransactionType in (46, 47) and COA_CNF_AccountConfig.Accountingtype = 2 then 1
								        else COA_CNF_AccountConfig.Accountingtype
									end Accountingtype,	
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
								   RR_CNF_RevenueRecognitionRule.Percentage,
								   RR_CNF_RevenueRecognitionRule.Days

						from RR_DATA_REVENUE
								inner join rr_cnf_Product						ON ((RR_DATA_REVENUE.MATRIXCELLID = rr_cnf_Product.MATRIXCELLID) or (RR_DATA_REVENUE.MatrixSheetId = rr_cnf_Product.MatrixSheetId)) and rr_cnf_Product.Enabled = 1
								inner join RR_CNF_RevenueRecognitionRule		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_cnf_Product.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  
								INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
								INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
								INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 
								INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid

							where RR_CNF_RevenueRecognitionRule.Enabled = 1
							  and coa_cnf_account.Enabled = 1
							  and COA_CNF_AccountConfig.Enabled = 1
							  and TransactionType in (33, 34, 44, 45, 46, 47, 53)
							  and ((coa_cnf_accountConfig.Siteid = RR_DATA_REVENUE.SiteId) or (coa_cnf_accountConfig.Siteid is null))
							  and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger IN (@OnFlexPaymentTrigger)
							  and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
							  and COA_CNF_AccountConfig.RemainingValues = 1
							  and RR_DATA_REVENUE.fcalcdate = @BatchDate
							  and RR_DATA_REVENUE.coaaccountid = @suspendid
					)p
					where RevenueAmount &lt;&gt; 0
			
		exec otn_sp_RR_RevenueData_PaymentMethodTaxDiscounts @BatchDate, '33, 34, 44, 45, 46, 47, 53,',   @OnFlexPaymentTrigger, @RRTransDateType

	end
	select '_OnFlexContractPayment' as TriggerType, @BatchDate as RunDate
END

</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_RR_RevenueData_OnExternalMoneyCardLoad]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_RR_RevenueData_OnExternalMoneyCardLoad
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE Procedure dbo.otn_sp_RR_RevenueData_OnExternalMoneyCardLoad
	@BatchDate Date,
	@RRTransDateType Integer
AS 
BEGIN
	
	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer
	Declare @OnMoneyCardCashOut Integer = 15

	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1


		BEGIN

			--Normal Transaction No Remaining Values
			INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[Saleitemid]
				   ,[MatrixCellid]
				   ,[MatrixCellCode]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])
				   select *
				   from(
							select coa_cnf_account.COAAccountId, 
								   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
								   RR_CNF_RevenueRecognitionRule.code,		   
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
								   COA_CNF_AccountConfig.COAAccountConfigId,
								   coa_cnf_account.COAAccountTypeId,
								   coa_cnf_account.Code as AccountCode,
								   RR_DATA_REVENUE.Transactionid as Transactionid,
								   RR_DATA_REVENUE.saleid as Saleid,
								   RR_DATA_REVENUE.SaleitemID as SaleitemID,
								   RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								   RR_DATA_REVENUE.MatrixcellCode as MatrixCode,
								   RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								   RR_DATA_REVENUE.Siteid as SiteID,
								   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								   RR_DATA_REVENUE.Workstationid as Workstationid,
								   RR_DATA_REVENUE.UserGroupid as UserGroupID,
								   RR_DATA_REVENUE.UserId as userID,
								   @BatchDate as BatchDate,
								   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
								        else DATA_Transaction.transactiondate
								   end as TransDate,
								   RR_DATA_REVENUE.Quantity as Quantity,
								   RR_DATA_REVENUE.GrossAmount as GrossAmount,
								   RR_DATA_REVENUE.NetAmount as NetAmount,
								   COA_CNF_AccountConfig.Price as ConfigPrice,
								   COA_CNF_AccountConfig.Percentage as ConfigPercentage,
								   COA_CNF_AccountConfig.RemainingValues,																		
									(CASE WHEN coa_cnf_account.coaaccountid not in (@ACCPaymentMethod, @TaxAccountID, @DiscountAccountID) then   --Accounts not Tax not PaymentMethods 
										Case when COA_CNF_AccountConfig.Price &gt; 0 then (COA_CNF_AccountConfig.Price * RR_DATA_REVENUE.Quantity) 
												else (ISNULL((((ABS(RR_DATA_REVENUE.RevenueAmount)) - ISNULL((select (ABS((sum(TaxAmount) * RR_DATA_REVENUE.Quantity)))
																										from data_saleitemTax
																										where saleitemid = RR_DATA_REVENUE.SaleitemID), 0)) * COA_CNF_AccountConfig.Percentage/100), 0))
										end 																		                                                                                                                                                                                              
									end)  as RevenueAmount,

								   COA_CNF_AccountConfig.Accountingtype,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
								   RR_CNF_RevenueRecognitionRule.Percentage,
								   RR_CNF_RevenueRecognitionRule.Days
		   
							from RR_DATA_REVENUE
									inner join rr_cnf_Product						ON ((RR_DATA_REVENUE.MATRIXCELLID = rr_cnf_Product.MATRIXCELLID) or (RR_DATA_REVENUE.MatrixSheetId = rr_cnf_Product.MatrixSheetId)) and rr_cnf_Product.Enabled = 1
									inner join RR_CNF_RevenueRecognitionRule		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_cnf_Product.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  
									INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
									INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
									INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 
									INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid

							where RR_CNF_RevenueRecognitionRule.Enabled = 1
							  and coa_cnf_account.Enabled = 1
							  and COA_CNF_AccountConfig.Enabled = 1
							  and TransactionType in (42, 43, 49)
							  and ((coa_cnf_accountConfig.Siteid = RR_DATA_REVENUE.SiteId) or (coa_cnf_accountConfig.Siteid is null))
							  and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger IN (@OnMoneyCardCashOut)
							  and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
							  and COA_CNF_AccountConfig.RemainingValues &lt;&gt; 1
							  and RR_DATA_REVENUE.fcalcdate = @BatchDate
							  and RR_DATA_REVENUE.coaaccountid = @suspendid
						
					)p
					where RevenueAmount &lt;&gt; 0

				--Normal Transaction with Remaining Values
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[Saleitemid]
				   ,[MatrixCellid]
				   ,[MatrixCellCode]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])
				   select *
				   from(
						select distinct coa_cnf_account.COAAccountId, 
								   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
								   RR_CNF_RevenueRecognitionRule.code,		   
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
								   COA_CNF_AccountConfig.COAAccountConfigId,
								   coa_cnf_account.COAAccountTypeId,
								   coa_cnf_account.Code as AccountCode,
								   RR_DATA_REVENUE.Transactionid as Transactionid,
								   RR_DATA_REVENUE.saleid as Saleid,
								   RR_DATA_REVENUE.SaleitemID as SaleitemID,
								   RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								   RR_DATA_REVENUE.MatrixcellCode as MatrixCode,
								   RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								   RR_DATA_REVENUE.Siteid as SiteID,
								   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								   RR_DATA_REVENUE.Workstationid as Workstationid,
								   RR_DATA_REVENUE.UserGroupid as UserGroupID,
								   RR_DATA_REVENUE.UserId as userID,
								   @BatchDate as BatchDate,
								   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
								        else DATA_Transaction.transactiondate
								   end as TransDate,
								   RR_DATA_REVENUE.Quantity as Quantity,
								   RR_DATA_REVENUE.GrossAmount as GrossAmount,
								   RR_DATA_REVENUE.NetAmount as NetAmount,
								   COA_CNF_AccountConfig.Price as ConfigPrice,
								   COA_CNF_AccountConfig.Percentage as ConfigPercentage,
								   COA_CNF_AccountConfig.RemainingValues,							 
								   ISNULL((RR_DATA_REVENUE.RevenueAmount - (select ISNULL(sum(revenueamount), 0)
								                            from RR_DATA_Revenue rr
												              where rr.saleitemid = RR_DATA_REVENUE.SaleitemID
												        and rr.COAAccountid not in (@SuspendID, @ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)
												 )
									), 0)
									as RevenueAmount,
								   case when TransactionType in (5, 17, 18, 20, 22, 30) and COA_CNF_AccountConfig.Accountingtype = 1 then 2
								        when TransactionType in (5, 17, 18, 20, 22, 30) and COA_CNF_AccountConfig.Accountingtype = 2 then 1
								        else COA_CNF_AccountConfig.Accountingtype
									end Accountingtype,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
								   RR_CNF_RevenueRecognitionRule.Percentage,
								   RR_CNF_RevenueRecognitionRule.Days

						from RR_DATA_REVENUE
								inner join rr_cnf_Product						ON ((RR_DATA_REVENUE.MATRIXCELLID = rr_cnf_Product.MATRIXCELLID) or (RR_DATA_REVENUE.MatrixSheetId = rr_cnf_Product.MatrixSheetId)) and rr_cnf_Product.Enabled = 1
								inner join RR_CNF_RevenueRecognitionRule		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_cnf_Product.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  
								INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
								INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
								INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 
								INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid

							where RR_CNF_RevenueRecognitionRule.Enabled = 1
							  and coa_cnf_account.Enabled = 1
							  and COA_CNF_AccountConfig.Enabled = 1
							  and TransactionType in (42, 43, 49)
							  and ((coa_cnf_accountConfig.Siteid = RR_DATA_REVENUE.SiteId) or (coa_cnf_accountConfig.Siteid is null))
							  and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger IN (@OnMoneyCardCashOut)
							  and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
							  and COA_CNF_AccountConfig.RemainingValues = 1
							  and RR_DATA_REVENUE.fcalcdate = @BatchDate
							  and RR_DATA_REVENUE.coaaccountid = @suspendid
					)p
					where RevenueAmount &lt;&gt; 0

		
		exec otn_sp_RR_RevenueData_PaymentMethodTaxDiscounts @BatchDate, '42, 43, 49,', @OnMoneyCardCashOut, @RRTransDateType										

	end
	select '@OnExternalMoneyCardLoad' as TriggerType, @BatchDate as RunDate
END

</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_RR_RevenueData_OnExternalMoneyCardCashOut]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_RR_RevenueData_OnExternalMoneyCardCashOut
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE Procedure dbo.otn_sp_RR_RevenueData_OnExternalMoneyCardCashOut
	@BatchDate Date,
	@RRTransDateType Integer
AS 
BEGIN

	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer
	Declare @OnMoneyCardCashOut Integer = 16

	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1


		BEGIN

			--Normal Transaction No Remaining Values
			INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[Saleitemid]
				   ,[MatrixCellid]
				   ,[MatrixCellCode]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])
				   select *
				   from(
							select coa_cnf_account.COAAccountId, 
								   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
								   RR_CNF_RevenueRecognitionRule.code,		   
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
								   COA_CNF_AccountConfig.COAAccountConfigId,
								   coa_cnf_account.COAAccountTypeId,
								   coa_cnf_account.Code as AccountCode,
								   RR_DATA_REVENUE.Transactionid as Transactionid,
								   RR_DATA_REVENUE.saleid as Saleid,
								   RR_DATA_REVENUE.SaleitemID as SaleitemID,
								   RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								   RR_DATA_REVENUE.MatrixcellCode as MatrixCode,
								   RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								   RR_DATA_REVENUE.Siteid as SiteID,
								   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								   RR_DATA_REVENUE.Workstationid as Workstationid,
								   RR_DATA_REVENUE.UserGroupid as UserGroupID,
								   RR_DATA_REVENUE.UserId as userID,
								   @BatchDate as BatchDate,
								   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
								        else DATA_Transaction.transactiondate
								   end as TransDate,
								   RR_DATA_REVENUE.Quantity as Quantity,
								   RR_DATA_REVENUE.GrossAmount as GrossAmount,
								   RR_DATA_REVENUE.NetAmount as NetAmount,
								   COA_CNF_AccountConfig.Price as ConfigPrice,
								   COA_CNF_AccountConfig.Percentage as ConfigPercentage,
								   COA_CNF_AccountConfig.RemainingValues,																		
									(CASE WHEN coa_cnf_account.coaaccountid not in (@ACCPaymentMethod, @TaxAccountID, @DiscountAccountID) then   --Accounts not Tax not PaymentMethods 
										Case when COA_CNF_AccountConfig.Price &gt; 0 then (COA_CNF_AccountConfig.Price * RR_DATA_REVENUE.Quantity) 
												else (ISNULL((((ABS(RR_DATA_REVENUE.RevenueAmount)) - ISNULL((select (ABS((sum(TaxAmount) * RR_DATA_REVENUE.Quantity)))
																										from data_saleitemTax
																										where saleitemid = RR_DATA_REVENUE.SaleitemID), 0)) * COA_CNF_AccountConfig.Percentage/100), 0))
										end 																		                                                                                                                                                                                              
									end)  as RevenueAmount,

								   COA_CNF_AccountConfig.Accountingtype,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
								   RR_CNF_RevenueRecognitionRule.Percentage,
								   RR_CNF_RevenueRecognitionRule.Days
		   
							from RR_DATA_REVENUE
									inner join rr_cnf_Product						ON ((RR_DATA_REVENUE.MATRIXCELLID = rr_cnf_Product.MATRIXCELLID) or (RR_DATA_REVENUE.MatrixSheetId = rr_cnf_Product.MatrixSheetId)) and rr_cnf_Product.Enabled = 1
									inner join RR_CNF_RevenueRecognitionRule		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_cnf_Product.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  
									INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
									INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
									INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 
									INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid

							where RR_CNF_RevenueRecognitionRule.Enabled = 1
							  and coa_cnf_account.Enabled = 1
							  and COA_CNF_AccountConfig.Enabled = 1
							  and TransactionType in (48, 52)
							  and ((coa_cnf_accountConfig.Siteid = RR_DATA_REVENUE.SiteId) or (coa_cnf_accountConfig.Siteid is null))
							  and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger IN (@OnMoneyCardCashOut)
							  and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
							  and COA_CNF_AccountConfig.RemainingValues &lt;&gt; 1
							  and RR_DATA_REVENUE.fcalcdate = @BatchDate
							  and RR_DATA_REVENUE.coaaccountid = @suspendid
						
					)p
					where RevenueAmount &lt;&gt; 0

				--Normal Transaction with Remaining Values
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[Saleitemid]
				   ,[MatrixCellid]
				   ,[MatrixCellCode]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])
				   select *
				   from(
						select distinct coa_cnf_account.COAAccountId, 
								   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
								   RR_CNF_RevenueRecognitionRule.code,		   
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
								   COA_CNF_AccountConfig.COAAccountConfigId,
								   coa_cnf_account.COAAccountTypeId,
								   coa_cnf_account.Code as AccountCode,
								   RR_DATA_REVENUE.Transactionid as Transactionid,
								   RR_DATA_REVENUE.saleid as Saleid,
								   RR_DATA_REVENUE.SaleitemID as SaleitemID,
								   RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								   RR_DATA_REVENUE.MatrixcellCode as MatrixCode,
								   RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								   RR_DATA_REVENUE.Siteid as SiteID,
								   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								   RR_DATA_REVENUE.Workstationid as Workstationid,
								   RR_DATA_REVENUE.UserGroupid as UserGroupID,
								   RR_DATA_REVENUE.UserId as userID,
								   @BatchDate as BatchDate,
								   case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
									    else DATA_Transaction.transactiondate
								   end as TransDate,
								   RR_DATA_REVENUE.Quantity as Quantity,
								   RR_DATA_REVENUE.GrossAmount as GrossAmount,
								   RR_DATA_REVENUE.NetAmount as NetAmount,
								   COA_CNF_AccountConfig.Price as ConfigPrice,
								   COA_CNF_AccountConfig.Percentage as ConfigPercentage,
								   COA_CNF_AccountConfig.RemainingValues,							 
								   ISNULL((RR_DATA_REVENUE.RevenueAmount - (select ISNULL(sum(revenueamount), 0)
								                            from RR_DATA_Revenue rr
												              where rr.saleitemid = RR_DATA_REVENUE.SaleitemID
												        and rr.COAAccountid not in (@SuspendID, @ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)
												 )
									), 0)
									as RevenueAmount,
								   case when TransactionType in (5, 17, 18, 20, 22, 30) and COA_CNF_AccountConfig.Accountingtype = 1 then 2
								        when TransactionType in (5, 17, 18, 20, 22, 30) and COA_CNF_AccountConfig.Accountingtype = 2 then 1
								        else COA_CNF_AccountConfig.Accountingtype
									end Accountingtype,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
								   RR_CNF_RevenueRecognitionRule.Percentage,
								   RR_CNF_RevenueRecognitionRule.Days

						from RR_DATA_REVENUE
								inner join rr_cnf_Product						ON ((RR_DATA_REVENUE.MATRIXCELLID = rr_cnf_Product.MATRIXCELLID) or (RR_DATA_REVENUE.MatrixSheetId = rr_cnf_Product.MatrixSheetId)) and rr_cnf_Product.Enabled = 1
								inner join RR_CNF_RevenueRecognitionRule		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_cnf_Product.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  
								INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
								INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
								INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 
								INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid

							where RR_CNF_RevenueRecognitionRule.Enabled = 1
							  and coa_cnf_account.Enabled = 1
							  and COA_CNF_AccountConfig.Enabled = 1
							  and TransactionType in (48, 52)
							  and ((coa_cnf_accountConfig.Siteid = RR_DATA_REVENUE.SiteId) or (coa_cnf_accountConfig.Siteid is null))
							  and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger IN (@OnMoneyCardCashOut)
							  and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
							  and COA_CNF_AccountConfig.RemainingValues = 1
							  and RR_DATA_REVENUE.fcalcdate = @BatchDate
							  and RR_DATA_REVENUE.coaaccountid = @suspendid
					)p
					where RevenueAmount &lt;&gt; 0

		
		exec otn_sp_RR_RevenueData_PaymentMethodTaxDiscounts @BatchDate, '48,52,', @OnMoneyCardCashOut, @RRTransDateType										

	end
	select '@OnExternalMoneyCardCashOut' as TriggerType, @BatchDate as RunDate
END

</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_RR_RevenueData_OnDepositTrigger]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_RR_RevenueData_OnDepositTrigger
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE Procedure dbo.otn_sp_RR_RevenueData_OnDepositTrigger
	@BatchDate Date,
	@RRTransDateType Integer
AS 
BEGIN

	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer
	Declare @DepositTrigger Integer = 5

	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1

	BEGIN																			
	--Normal Transaction No Remaining Values
			INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[Saleitemid]
				   ,[MatrixCellid]
				   ,[MatrixCellCode]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				   ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])
				   select *
				   from (
					select distinct p.COAAccountId, 
								p.RevenueRecognitionRuleId,
								p.code,		   
								p.RRCalcTypeWhere,
								p.RRCalcTypeMethod,	   
								p.COAAccountConfigId,
								p.COAAccountTypeId,
								p.AccountCode,
								RR_DATA_REVENUE.Transactionid as Transactionid,
								RR_DATA_REVENUE.saleid as Saleid,
								RR_DATA_REVENUE.SaleitemID as SaleitemID,
								RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								RR_DATA_REVENUE.MatrixcellCode as MatrixCode,
								RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								RR_DATA_REVENUE.Siteid as SiteID,
								RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								RR_DATA_REVENUE.Workstationid as Workstationid,
								RR_DATA_REVENUE.UserGroupid as UserGroupID,
								RR_DATA_REVENUE.UserId as userID,
								@BatchDate as BatchDate,
								case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
								     else DATA_Transaction.transactiondate
								  end as TransDate,
								RR_DATA_REVENUE.Quantity as Quantity,
								RR_DATA_REVENUE.GrossAmount as GrossAmount,
								RR_DATA_REVENUE.NetAmount as NetAmount,
								p.Price as ConfigPrice,
								p.Percentage as ConfigPercentage,
								p.RemainingValues,
								(CASE WHEN p.coaaccountid not in (@ACCPaymentMethod, @TaxAccountID, @DiscountAccountID) then   --Accounts not Tax not PaymentMethods 
									Case when p.Price &gt; 0 then (p.Price * RR_DATA_REVENUE.Quantity) 
											else (ISNULL((((ABS(RR_DATA_REVENUE.RevenueAmount)) - ISNULL((select (ABS((sum(TaxAmount) * RR_DATA_REVENUE.Quantity)))
																									from data_saleitemTax
																									where saleitemid = RR_DATA_REVENUE.SaleitemID), 0)) * p.Percentage/100), 0))
									end 																		                                                                                                                                                                                              
								end)  as RevenueAmount,
								case when TransactionType in (5, 17, 18, 20, 22, 30) and p.Accountingtype = 1 then 2
										when TransactionType in (5, 17, 18, 20, 22, 30) and p.Accountingtype = 2 then 1
										when TransactionType in (7) and rr_data_revenue.RevenueAmount &lt; 0 and p.Accountingtype = 1 then 2
										when TransactionType in (7) and rr_data_revenue.RevenueAmount &lt; 0 and p.Accountingtype = 2 then 1
										else p.Accountingtype
									end Accountingtype,
									p.RRCalcTypeTrigger,
									p.rrPercentage,
									p.Days						
						
						
							from RR_DATA_REVENUE
								INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
								INNER JOIN (select '1' as PCOAAccountid, 
												   coa_cnf_accountConfig.Siteid, 
												   RR_CNF_RevenueRecognitionRule.Enabled, 
												   RR_CNF_RevenueRecognitionRule.FromDate, 
												   RR_CNF_RevenueRecognitionRule.ToDate,
												   COA_CNF_AccountConfig.RemainingValues,
												   coa_cnf_account.coaaccountid,
												   COA_CNF_AccountConfig.Price,
												   COA_CNF_AccountConfig.Percentage,
												   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
												   RR_CNF_RevenueRecognitionRule.code,		   
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
												   COA_CNF_AccountConfig.COAAccountConfigId,
												   coa_cnf_account.COAAccountTypeId,
												   coa_cnf_account.Code as accountcode,
												   coa_cnf_accountconfig.Accountingtype,
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
												   RR_CNF_RevenueRecognitionRule.Percentage rrPercentage,
												   RR_CNF_RevenueRecognitionRule.Days	

												from RR_CNF_RevenueRecognitionRule	
												INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
												INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid and coa_cnf_account.Enabled = 1
												INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
											where  RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @DepositTrigger
											and RR_CNF_RevenueRecognitionRule.Enabled = 1
											and coa_cnf_account.coaaccountid not in (@ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)) p				on p.PCOAAccountid = rr_data_revenue.coaaccountid 

							where transactiontype in (12)													 
								and p.Enabled = 1
								and ((p.Siteid = RR_DATA_REVENUE.Siteid) or (p.Siteid is null))
								and @BatchDate between p.FromDate and p.ToDate
								and p.RemainingValues &lt;&gt; 1
								and RR_DATA_REVENUE.fcalcdate = @BatchDate
					)r 
					where r.revenueAmount &lt;&gt; 0


				--Normal Transaction with Remaining Values
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[Saleitemid]
				   ,[MatrixCellid]
				   ,[MatrixCellCode]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])
				   select *
				   from (
					select distinct p.COAAccountId, 
								p.RevenueRecognitionRuleId,
								p.code,		   
								p.RRCalcTypeWhere,
								p.RRCalcTypeMethod,	   
								p.COAAccountConfigId,
								p.COAAccountTypeId,
								p.AccountCode,
								RR_DATA_REVENUE.Transactionid as Transactionid,
								RR_DATA_REVENUE.saleid as Saleid,
								RR_DATA_REVENUE.SaleitemID as SaleitemID,
								RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								RR_DATA_REVENUE.MatrixcellCode as MatrixCode,
								RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								RR_DATA_REVENUE.Siteid as SiteID,
								RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								RR_DATA_REVENUE.Workstationid as Workstationid,
								RR_DATA_REVENUE.UserGroupid as UserGroupID,
								RR_DATA_REVENUE.UserId as userID,
								@BatchDate as BatchDate,
								case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
								     else DATA_Transaction.transactiondate
								  end as TransDate,
								RR_DATA_REVENUE.Quantity as Quantity,
								RR_DATA_REVENUE.GrossAmount as GrossAmount,
								RR_DATA_REVENUE.NetAmount as NetAmount,
								p.Price as ConfigPrice,
								p.Percentage as ConfigPercentage,
								p.RemainingValues,
								CASE WHEN p.coaaccountid not in (@ACCPaymentMethod, @TaxAccountID, @DiscountAccountID) then																																													 
							    ABS(ABS(RR_DATA_REVENUE.RevenueAmount) -					 
								ISNULL((select ABS(sum(RevenueAmount))
										from RR_DATA_Revenue rrd
									    where rrd.RevenueRecognitionRuleId = p.RevenueRecognitionRuleId
										and rrd.RevenueRecognitionRuleId not in (@SuspendID, @ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)
										and rrd.transactionid = RR_DATA_REVENUE.transactionid
								), 0)) 
								else 0
								end RevenueAmount,
								case when TransactionType in (5, 17, 18, 20, 22, 30) and p.Accountingtype = 1 then 2
										when TransactionType in (5, 17, 18, 20, 22, 30) and p.Accountingtype = 2 then 1
										when TransactionType in (7) and rr_data_revenue.RevenueAmount &lt; 0 and p.Accountingtype = 1 then 2
										when TransactionType in (7) and rr_data_revenue.RevenueAmount &lt; 0 and p.Accountingtype = 2 then 1
										else p.Accountingtype
									end Accountingtype,
									p.RRCalcTypeTrigger,
									p.rrPercentage,
									p.Days						
						
						
							from RR_DATA_REVENUE
								INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
								INNER JOIN (select '1' as PCOAAccountid, 
												   coa_cnf_accountConfig.Siteid, 
												   RR_CNF_RevenueRecognitionRule.Enabled, 
												   RR_CNF_RevenueRecognitionRule.FromDate, 
												   RR_CNF_RevenueRecognitionRule.ToDate,
												   COA_CNF_AccountConfig.RemainingValues,
												   coa_cnf_account.coaaccountid,
												   COA_CNF_AccountConfig.Price,
												   COA_CNF_AccountConfig.Percentage,
												   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
												   RR_CNF_RevenueRecognitionRule.code,		   
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
												   COA_CNF_AccountConfig.COAAccountConfigId,
												   coa_cnf_account.COAAccountTypeId,
												   coa_cnf_account.Code as accountcode,
												   coa_cnf_accountconfig.Accountingtype,
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
												   RR_CNF_RevenueRecognitionRule.Percentage rrPercentage,
												   RR_CNF_RevenueRecognitionRule.Days	

												from RR_CNF_RevenueRecognitionRule	
												INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
												INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid and coa_cnf_account.Enabled = 1
												INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
											where  RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @DepositTrigger
											and RR_CNF_RevenueRecognitionRule.Enabled = 1
											and coa_cnf_account.coaaccountid not in (@ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)) p				on p.PCOAAccountid = rr_data_revenue.coaaccountid 

							where transactiontype in (12)													 
								and p.Enabled = 1
								and ((p.Siteid = RR_DATA_REVENUE.Siteid) or (p.Siteid is null))
								and @BatchDate between p.FromDate and p.ToDate
								and p.RemainingValues = 1
								and RR_DATA_REVENUE.fcalcdate = @BatchDate		
					)r 
					where r.revenueAmount &lt;&gt; 0	

		exec otn_sp_RR_RevenueData_PaymentMethodTaxDiscounts2 @BatchDate, '12,',   @DepositTrigger, @RRTransDateType
	end
	
	select 'OnDepositTrigger' as TriggerType, @BatchDate as RunDate

END

</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_RR_RevenueData_OnCreditWriteoff]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_RR_RevenueData_OnCreditWriteoff
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE Procedure dbo.otn_sp_RR_RevenueData_OnCreditWriteoff
	@BatchDate Date,
	@RRTransDateType Integer
AS 
BEGIN

	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer
	Declare @OnCreditWriteoff Integer = 9

	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1

	
BEGIN	
			--Normal Transaction No Remaining Values
			INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[Saleitemid]
				   ,[MatrixCellid]
				   ,[MatrixCellCode]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				   ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])
				   select *
				   from (
					select distinct p.COAAccountId, 
								p.RevenueRecognitionRuleId,
								p.code,		   
								p.RRCalcTypeWhere,
								p.RRCalcTypeMethod,	   
								p.COAAccountConfigId,
								p.COAAccountTypeId,
								p.AccountCode,
								RR_DATA_REVENUE.Transactionid as Transactionid,
								RR_DATA_REVENUE.saleid as Saleid,
								RR_DATA_REVENUE.SaleitemID as SaleitemID,
								RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								RR_DATA_REVENUE.MatrixcellCode as MatrixCode,
								RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								RR_DATA_REVENUE.Siteid as SiteID,
								RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								RR_DATA_REVENUE.Workstationid as Workstationid,
								RR_DATA_REVENUE.UserGroupid as UserGroupID,
								RR_DATA_REVENUE.UserId as userID,
								@BatchDate as BatchDate,
								case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
								     else DATA_Transaction.transactiondate
								  end as TransDate,
								RR_DATA_REVENUE.Quantity as Quantity,
								RR_DATA_REVENUE.GrossAmount as GrossAmount,
								RR_DATA_REVENUE.NetAmount as NetAmount,
								p.Price as ConfigPrice,
								p.Percentage as ConfigPercentage,
								p.RemainingValues,
								(CASE WHEN p.coaaccountid not in (@ACCPaymentMethod, @TaxAccountID, @DiscountAccountID) then   --Accounts not Tax not PaymentMethods 
									Case when p.Price &gt; 0 then (p.Price * RR_DATA_REVENUE.Quantity) 
											else (ISNULL((((ABS(RR_DATA_REVENUE.RevenueAmount)) - ISNULL((select (ABS((sum(TaxAmount) * RR_DATA_REVENUE.Quantity)))
																									from data_saleitemTax
																									where saleitemid = RR_DATA_REVENUE.SaleitemID), 0)) * p.Percentage/100), 0))
									end 																		                                                                                                                                                                                              
								end)  as RevenueAmount,
								case when TransactionType in (5, 17, 18, 20, 22, 30) and p.Accountingtype = 1 then 2
										when TransactionType in (5, 17, 18, 20, 22, 30) and p.Accountingtype = 2 then 1
										when TransactionType in (7) and rr_data_revenue.RevenueAmount &lt; 0 and p.Accountingtype = 1 then 2
										when TransactionType in (7) and rr_data_revenue.RevenueAmount &lt; 0 and p.Accountingtype = 2 then 1
										else p.Accountingtype
									end Accountingtype,
									p.RRCalcTypeTrigger,
									p.rrPercentage,
									p.Days						
						
						
							from RR_DATA_REVENUE
								INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
								INNER JOIN (select '1' as PCOAAccountid, 
												   coa_cnf_accountConfig.Siteid, 
												   RR_CNF_RevenueRecognitionRule.Enabled, 
												   RR_CNF_RevenueRecognitionRule.FromDate, 
												   RR_CNF_RevenueRecognitionRule.ToDate,
												   COA_CNF_AccountConfig.RemainingValues,
												   coa_cnf_account.coaaccountid,
												   COA_CNF_AccountConfig.Price,
												   COA_CNF_AccountConfig.Percentage,
												   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
												   RR_CNF_RevenueRecognitionRule.code,		   
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
												   COA_CNF_AccountConfig.COAAccountConfigId,
												   coa_cnf_account.COAAccountTypeId,
												   coa_cnf_account.Code as accountcode,
												   coa_cnf_accountconfig.Accountingtype,
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
												   RR_CNF_RevenueRecognitionRule.Percentage rrPercentage,
												   RR_CNF_RevenueRecognitionRule.Days	

												from RR_CNF_RevenueRecognitionRule	
												INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
												INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid and coa_cnf_account.Enabled = 1
												INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
											where  RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @OnCreditWriteoff
											and RR_CNF_RevenueRecognitionRule.Enabled = 1
											and coa_cnf_account.coaaccountid not in (@ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)) p				on p.PCOAAccountid = rr_data_revenue.coaaccountid 

							where transactiontype in (8)													 
								and p.Enabled = 1
								and ((p.Siteid = RR_DATA_REVENUE.Siteid) or (p.Siteid is null))
								and @BatchDate between p.FromDate and p.ToDate
								and p.RemainingValues &lt;&gt; 1
								and RR_DATA_REVENUE.fcalcdate = @BatchDate
					)r 
					where r.revenueAmount &lt;&gt; 0


				--Normal Transaction with Remaining Values
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[Saleitemid]
				   ,[MatrixCellid]
				   ,[MatrixCellCode]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])
				   select *
				   from (
					select distinct p.COAAccountId, 
								p.RevenueRecognitionRuleId,
								p.code,		   
								p.RRCalcTypeWhere,
								p.RRCalcTypeMethod,	   
								p.COAAccountConfigId,
								p.COAAccountTypeId,
								p.AccountCode,
								RR_DATA_REVENUE.Transactionid as Transactionid,
								RR_DATA_REVENUE.saleid as Saleid,
								RR_DATA_REVENUE.SaleitemID as SaleitemID,
								RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								RR_DATA_REVENUE.MatrixcellCode as MatrixCode,
								RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								RR_DATA_REVENUE.Siteid as SiteID,
								RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								RR_DATA_REVENUE.Workstationid as Workstationid,
								RR_DATA_REVENUE.UserGroupid as UserGroupID,
								RR_DATA_REVENUE.UserId as userID,
								@BatchDate as BatchDate,
								case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
								     else DATA_Transaction.transactiondate
								  end as TransDate,
								RR_DATA_REVENUE.Quantity as Quantity,
								RR_DATA_REVENUE.GrossAmount as GrossAmount,
								RR_DATA_REVENUE.NetAmount as NetAmount,
								p.Price as ConfigPrice,
								p.Percentage as ConfigPercentage,
								p.RemainingValues,
								CASE WHEN p.coaaccountid not in (@ACCPaymentMethod, @TaxAccountID, @DiscountAccountID) then																																													 
							    ABS(ABS(RR_DATA_REVENUE.RevenueAmount) -					 
								ISNULL((select ABS(sum(RevenueAmount))
										from RR_DATA_Revenue rrd
									    where rrd.RevenueRecognitionRuleId = p.RevenueRecognitionRuleId
										and rrd.RevenueRecognitionRuleId not in (@SuspendID, @ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)
										and rrd.transactionid = RR_DATA_REVENUE.transactionid
								), 0)) 
								else 0
								end RevenueAmount,
								case when TransactionType in (5, 17, 18, 20, 22, 30) and p.Accountingtype = 1 then 2
										when TransactionType in (5, 17, 18, 20, 22, 30) and p.Accountingtype = 2 then 1
										when TransactionType in (7) and rr_data_revenue.RevenueAmount &lt; 0 and p.Accountingtype = 1 then 2
										when TransactionType in (7) and rr_data_revenue.RevenueAmount &lt; 0 and p.Accountingtype = 2 then 1
										else p.Accountingtype
									end Accountingtype,
									p.RRCalcTypeTrigger,
									p.rrPercentage,
									p.Days						
						
						
							from RR_DATA_REVENUE
								INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
								INNER JOIN (select '1' as PCOAAccountid, 
												   coa_cnf_accountConfig.Siteid, 
												   RR_CNF_RevenueRecognitionRule.Enabled, 
												   RR_CNF_RevenueRecognitionRule.FromDate, 
												   RR_CNF_RevenueRecognitionRule.ToDate,
												   COA_CNF_AccountConfig.RemainingValues,
												   coa_cnf_account.coaaccountid,
												   COA_CNF_AccountConfig.Price,
												   COA_CNF_AccountConfig.Percentage,
												   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
												   RR_CNF_RevenueRecognitionRule.code,		   
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
												   COA_CNF_AccountConfig.COAAccountConfigId,
												   coa_cnf_account.COAAccountTypeId,
												   coa_cnf_account.Code as accountcode,
												   coa_cnf_accountconfig.Accountingtype,
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
												   RR_CNF_RevenueRecognitionRule.Percentage rrPercentage,
												   RR_CNF_RevenueRecognitionRule.Days	

												from RR_CNF_RevenueRecognitionRule	
												INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
												INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid and coa_cnf_account.Enabled = 1
												INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
											where  RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @OnCreditWriteoff
											and RR_CNF_RevenueRecognitionRule.Enabled = 1
											and coa_cnf_account.coaaccountid not in (@ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)) p				on p.PCOAAccountid = rr_data_revenue.coaaccountid 

							where transactiontype in (8)													 
								and p.Enabled = 1
								and ((p.Siteid = RR_DATA_REVENUE.Siteid) or (p.Siteid is null))
								and @BatchDate between p.FromDate and p.ToDate
								and p.RemainingValues = 1
								and RR_DATA_REVENUE.fcalcdate = @BatchDate		
					)r 
					where r.revenueAmount &lt;&gt; 0

				exec otn_sp_RR_RevenueData_PaymentMethodTaxDiscounts2 @BatchDate, '8,',   @OnCreditWriteoff, @RRTransDateType
	end

	select 'OnCreditWriteoffTrigger' as TriggerType, @BatchDate as RunDate

END

</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_RR_RevenueData_OnAdvancedPaymentTrigger]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_RR_RevenueData_OnAdvancedPaymentTrigger
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>
CREATE Procedure dbo.otn_sp_RR_RevenueData_OnAdvancedPaymentTrigger
	@BatchDate Date,
	@RRTransDateType Integer
AS 
BEGIN

	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer
	Declare @OnAdvancePaymentTrigger Integer = 7

	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1


BEGIN	
			--Normal Transaction No Remaining Values
			INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[Saleitemid]
				   ,[MatrixCellid]
				   ,[MatrixCellCode]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				   ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])
				   select *
				   from (
					select distinct p.COAAccountId, 
								p.RevenueRecognitionRuleId,
								p.code,		   
								p.RRCalcTypeWhere,
								p.RRCalcTypeMethod,	   
								p.COAAccountConfigId,
								p.COAAccountTypeId,
								p.AccountCode,
								RR_DATA_REVENUE.Transactionid as Transactionid,
								RR_DATA_REVENUE.saleid as Saleid,
								RR_DATA_REVENUE.SaleitemID as SaleitemID,
								RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								RR_DATA_REVENUE.MatrixcellCode as MatrixCode,
								RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								RR_DATA_REVENUE.Siteid as SiteID,
								RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								RR_DATA_REVENUE.Workstationid as Workstationid,
								RR_DATA_REVENUE.UserGroupid as UserGroupID,
								RR_DATA_REVENUE.UserId as userID,
								@BatchDate as BatchDate,
								case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
								     else DATA_Transaction.transactiondate
								  end as TransDate,
								RR_DATA_REVENUE.Quantity as Quantity,
								RR_DATA_REVENUE.GrossAmount as GrossAmount,
								RR_DATA_REVENUE.NetAmount as NetAmount,
								p.Price as ConfigPrice,
								p.Percentage as ConfigPercentage,
								p.RemainingValues,
								(CASE WHEN p.coaaccountid not in (@ACCPaymentMethod, @TaxAccountID, @DiscountAccountID) then   --Accounts not Tax not PaymentMethods 
									Case when p.Price &gt; 0 then (p.Price * RR_DATA_REVENUE.Quantity) 
											else (ISNULL((((ABS(RR_DATA_REVENUE.RevenueAmount)) - ISNULL((select (ABS((sum(TaxAmount) * RR_DATA_REVENUE.Quantity)))
																									from data_saleitemTax
																									where saleitemid = RR_DATA_REVENUE.SaleitemID), 0)) * p.Percentage/100), 0))
									end 																		                                                                                                                                                                                              
								end)  as RevenueAmount,
								case when TransactionType in (5, 17, 18, 20, 22, 30) and p.Accountingtype = 1 then 2
										when TransactionType in (5, 17, 18, 20, 22, 30) and p.Accountingtype = 2 then 1
										when TransactionType in (7) and rr_data_revenue.RevenueAmount &lt; 0 and p.Accountingtype = 1 then 2
										when TransactionType in (7) and rr_data_revenue.RevenueAmount &lt; 0 and p.Accountingtype = 2 then 1
										else p.Accountingtype
									end Accountingtype,
									p.RRCalcTypeTrigger,
									p.rrPercentage,
									p.Days						
						
						
							from RR_DATA_REVENUE
								INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
								INNER JOIN (select '1' as PCOAAccountid, 
												   coa_cnf_accountConfig.Siteid, 
												   RR_CNF_RevenueRecognitionRule.Enabled, 
												   RR_CNF_RevenueRecognitionRule.FromDate, 
												   RR_CNF_RevenueRecognitionRule.ToDate,
												   COA_CNF_AccountConfig.RemainingValues,
												   coa_cnf_account.coaaccountid,
												   COA_CNF_AccountConfig.Price,
												   COA_CNF_AccountConfig.Percentage,
												   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
												   RR_CNF_RevenueRecognitionRule.code,		   
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
												   COA_CNF_AccountConfig.COAAccountConfigId,
												   coa_cnf_account.COAAccountTypeId,
												   coa_cnf_account.Code as accountcode,
												   coa_cnf_accountconfig.Accountingtype,
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
												   RR_CNF_RevenueRecognitionRule.Percentage rrPercentage,
												   RR_CNF_RevenueRecognitionRule.Days	

												from RR_CNF_RevenueRecognitionRule	
												INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
												INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid and coa_cnf_account.Enabled = 1
												INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
											where  RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @OnAdvancePaymentTrigger
											and RR_CNF_RevenueRecognitionRule.Enabled = 1
											and coa_cnf_account.coaaccountid not in (@ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)) p				on p.PCOAAccountid = rr_data_revenue.coaaccountid 

							where transactiontype in (34)													 
								and p.Enabled = 1
								and ((p.Siteid = RR_DATA_REVENUE.Siteid) or (p.Siteid is null))
								and @BatchDate between p.FromDate and p.ToDate
								and p.RemainingValues &lt;&gt; 1
								and RR_DATA_REVENUE.fcalcdate = @BatchDate
					)r 
					where r.revenueAmount &lt;&gt; 0


				--Normal Transaction with Remaining Values
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCode]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[COAAccountCode]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[Saleitemid]
				   ,[MatrixCellid]
				   ,[MatrixCellCode]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[FRevenueDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])
				   select *
				   from (
					select distinct p.COAAccountId, 
								p.RevenueRecognitionRuleId,
								p.code,		   
								p.RRCalcTypeWhere,
								p.RRCalcTypeMethod,	   
								p.COAAccountConfigId,
								p.COAAccountTypeId,
								p.AccountCode,
								RR_DATA_REVENUE.Transactionid as Transactionid,
								RR_DATA_REVENUE.saleid as Saleid,
								RR_DATA_REVENUE.SaleitemID as SaleitemID,
								RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								RR_DATA_REVENUE.MatrixcellCode as MatrixCode,
								RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								RR_DATA_REVENUE.Siteid as SiteID,
								RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								RR_DATA_REVENUE.Workstationid as Workstationid,
								RR_DATA_REVENUE.UserGroupid as UserGroupID,
								RR_DATA_REVENUE.UserId as userID,
								@BatchDate as BatchDate,
								case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
								     else DATA_Transaction.transactiondate
								  end as TransDate,
								RR_DATA_REVENUE.Quantity as Quantity,
								RR_DATA_REVENUE.GrossAmount as GrossAmount,
								RR_DATA_REVENUE.NetAmount as NetAmount,
								p.Price as ConfigPrice,
								p.Percentage as ConfigPercentage,
								p.RemainingValues,
								CASE WHEN p.coaaccountid not in (@ACCPaymentMethod, @TaxAccountID, @DiscountAccountID) then																																													 
							    ABS(ABS(RR_DATA_REVENUE.RevenueAmount) -					 
								ISNULL((select ABS(sum(RevenueAmount))
										from RR_DATA_Revenue rrd
									    where rrd.RevenueRecognitionRuleId = p.RevenueRecognitionRuleId
										and rrd.RevenueRecognitionRuleId not in (@SuspendID, @ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)
										and rrd.transactionid = RR_DATA_REVENUE.transactionid
								), 0)) 
								else 0
								end RevenueAmount,
								case when TransactionType in (5, 17, 18, 20, 22, 30) and p.Accountingtype = 1 then 2
										when TransactionType in (5, 17, 18, 20, 22, 30) and p.Accountingtype = 2 then 1
										when TransactionType in (7) and rr_data_revenue.RevenueAmount &lt; 0 and p.Accountingtype = 1 then 2
										when TransactionType in (7) and rr_data_revenue.RevenueAmount &lt; 0 and p.Accountingtype = 2 then 1
										else p.Accountingtype
									end Accountingtype,
									p.RRCalcTypeTrigger,
									p.rrPercentage,
									p.Days						
						
						
							from RR_DATA_REVENUE
								INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
								INNER JOIN (select '1' as PCOAAccountid, 
												   coa_cnf_accountConfig.Siteid, 
												   RR_CNF_RevenueRecognitionRule.Enabled, 
												   RR_CNF_RevenueRecognitionRule.FromDate, 
												   RR_CNF_RevenueRecognitionRule.ToDate,
												   COA_CNF_AccountConfig.RemainingValues,
												   coa_cnf_account.coaaccountid,
												   COA_CNF_AccountConfig.Price,
												   COA_CNF_AccountConfig.Percentage,
												   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
												   RR_CNF_RevenueRecognitionRule.code,		   
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
												   COA_CNF_AccountConfig.COAAccountConfigId,
												   coa_cnf_account.COAAccountTypeId,
												   coa_cnf_account.Code as accountcode,
												   coa_cnf_accountconfig.Accountingtype,
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
												   RR_CNF_RevenueRecognitionRule.Percentage rrPercentage,
												   RR_CNF_RevenueRecognitionRule.Days	

												from RR_CNF_RevenueRecognitionRule	
												INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
												INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid and coa_cnf_account.Enabled = 1
												INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
											where  RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @OnAdvancePaymentTrigger
											and RR_CNF_RevenueRecognitionRule.Enabled = 1
											and coa_cnf_account.coaaccountid not in (@ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)) p				on p.PCOAAccountid = rr_data_revenue.coaaccountid 

							where transactiontype in (34)													 
								and p.Enabled = 1
								and ((p.Siteid = RR_DATA_REVENUE.Siteid) or (p.Siteid is null))
								and @BatchDate between p.FromDate and p.ToDate
								and p.RemainingValues = 1
								and RR_DATA_REVENUE.fcalcdate = @BatchDate		
					)r 
					where r.revenueAmount &lt;&gt; 0

				exec otn_sp_RR_RevenueData_PaymentMethodTaxDiscounts2 @BatchDate, '34,',   @OnAdvancePaymentTrigger, @RRTransDateType
	end

	select 'OnAdvancePaymentTrigger' as TriggerType, @BatchDate as RunDate

END


</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_RR_RevenueData_SettleUpSuspendAccount]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_RR_RevenueData_SettleUpSuspendAccount
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE Procedure dbo.otn_sp_RR_RevenueData_SettleUpSuspendAccount
	@BatchDate Date,
	@RRTransDateType Integer
AS 
BEGIN
	Declare @SuspendRRRId Integer
	Declare @SuspendCOAAccountId Integer
	Declare @SuspendRRRCode varchar(10)
	Declare @SuspendRRCalcTypeTrigger Integer
	Declare @SuspendRRCalcTypeWhere Integer
	Declare @SuspendRRCalcTypeMethod Integer
	Declare @SuspendCOAAccountConfigId Integer
	Declare @SuspendCOAAccountTypeId Integer
	Declare @SuspendCOAAccountCode varchar(10)
	Declare @SuspendPercentage float
	Declare @SuspendDays Integer
	Declare @SuspendPrice float
	Declare @SuspendCOAAccount_Percentage Float
	Declare @SuspendRemainingValues Integer
	Declare @SuspendRRCOAAccountingType Integer

	Declare @TransactionID Integer
	Declare @TransactionType Integer
	Declare @FCalcDate date
	Declare @UsageID Integer
	Declare @TicketID Integer
	Declare @UsagePrice float
	Declare @AmountLeft float

	Declare @saleid Integer
	Declare @Siteid Integer
	Declare @OperatingAreaId Integer
	Declare @Workstationid Integer
	Declare @UserGroupid Integer
	Declare @UserId Integer
	Declare @Quantity Integer
	Declare @GrossAmount Float
	Declare @NetAmount Float
	Declare @RevenueAmount Float
	Declare @PaymentMethod Integer
	Declare @PaymentAmount Float
	Declare @TransDate Date
	Declare @Matrixcell Integer
	Declare @MatrixcellCode varchar(10)
	Declare @MatrixSheetId Integer 
	Declare @SaleitemID Integer
	Declare @PaymentDriver Integer

	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer
	Declare @UsageTrigger Integer = 2
	Declare @DepositTrigger Integer = 5
	Declare @MoneyRefund Integer = 6
	Declare @OnSaleTrigger Integer = 1
	Declare @OnAdvancePaymentTrigger Integer = 7
	Declare @SuspendRule Integer
	Declare @StartTime DateTime

	Set @StartTime = Getdate();
	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @SuspendRule = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleid
	from coa_cnf_account
		INNER JOIN COA_CNF_AccountType				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
		INNER JOIN COA_CNF_AccountConfig			on COA_CNF_AccountConfig.COAAccountId = coa_cnf_account.COAAccountId
		INNER JOIN RR_CNF_RevenueRecognitionRule	on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId
	where coa_cnf_account.COAAccountID = @SuspendID

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1

	select @SuspendRRRId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
		   @SuspendRRRCode = RR_CNF_RevenueRecognitionRule.code,
		   @SuspendRRCalcTypeTrigger = RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
		   @SuspendRRCalcTypeWhere = RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
		   @SuspendRRCalcTypeMethod = RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
		   @SuspendCOAAccountConfigId = COA_CNF_AccountConfig.COAAccountConfigId,
		   @SuspendCOAAccountTypeId = COA_CNF_AccountType.COAAccountTypeId,
		   @SuspendCOAAccountId = coa_cnf_account.COAAccountId,
		   @SuspendPercentage = RR_CNF_RevenueRecognitionRule.Percentage,
		   @SuspendDays = RR_CNF_RevenueRecognitionRule.Days,
		   @SuspendPrice = COA_CNF_AccountConfig.Price,
		   @SuspendCOAAccount_Percentage = COA_CNF_AccountConfig.Percentage,
		   @SuspendRemainingValues = COA_CNF_AccountConfig.RemainingValues,
		   @SuspendCOAAccountCode = coa_cnf_account.Code,
		   @SuspendRRCOAAccountingType = COA_CNF_AccountConfig.AccountingType

	from coa_cnf_account
		INNER JOIN COA_CNF_AccountType				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
		INNER JOIN COA_CNF_AccountConfig			on COA_CNF_AccountConfig.COAAccountId = coa_cnf_account.COAAccountId
		INNER JOIN RR_CNF_RevenueRecognitionRule	on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId
	where coa_cnf_account.COAAccountID = @SuspendID
	  and RR_CNF_RevenueRecognitionRule.enabled = 1
	  and COA_CNF_AccountConfig.enabled = 1


	update rr_data_revenue
	   set revenueamount = abs(revenueamount)		   
	 where FCalcDate = @BatchDate
	   and coaaccountid = @SuspendID

	BEGIN
		
			INSERT INTO [dbo].[RR_DATA_Revenue]
					   ([COAAccountId]
					   ,[RevenueRecognitionRuleId]
					   ,[RRCode]
					   ,[RRCalcTypeWhere]
					   ,[RRCalcTypeMethod]
					   ,[COAAccountConfigId]
					   ,[COAAccountType]
					   ,[COAAccountCode]
					   ,[TransactionId]
					   ,[SaleId]
					   ,[SiteId]
					   ,[OperatingAreaId]
					   ,[WorkstationId]
					   ,[UserGroupId]
					   ,[UserId]
					   ,[FCalcDate]
					   ,[FRevenueDate]
					   ,[Quantity]
					   ,[GrossAmount]
					   ,[NetAmount]
					   ,[Price]
					   ,[Percentage]
					   ,[RemaningValues]
					   ,[RevenueAmount]
					   ,[AccountingType]
					   ,[RRCalcTypeTrigger]
					   ,[RRPercentage]
					   ,[RRDays])
				select SuspendCOAAccountId,
					   SuspendRRRId,
					   SuspendRRRCode,
					   SuspendRRCalcTypeWhere,
					   SuspendRRCalcTypeMethod,
					   SuspendCOAAccountConfigId,
					   SuspendCOAAccountTypeId,
					   SuspendCOAAccountCode,
					   Transactionid,
					   saleid,
					   Siteid,
					   OperatingAreaId,
					   Workstationid,
					   UserGroupid,
					   UserId,
					   BatchDate,
					   TransDate,
					   0,
					   GrossAmount,
					   NetAmount,
					   SuspendPrice,
					   percentage,
					   RemainingValues,
					   sum(ABS(RevenueAmount)) *-1,
					   Accountingtype,
					   rrtrigger,
					   percentage2,
					   rrdays
				from (
				select distinct @SuspendCOAAccountId SuspendCOAAccountId,
					   @SuspendRRRId SuspendRRRId,
					   @SuspendRRRCode SuspendRRRCode,
					   @SuspendRRCalcTypeWhere SuspendRRCalcTypeWhere,
					   @SuspendRRCalcTypeMethod SuspendRRCalcTypeMethod,
					   @SuspendCOAAccountConfigId SuspendCOAAccountConfigId,
					   @SuspendCOAAccountTypeId SuspendCOAAccountTypeId,
					   @SuspendCOAAccountCode SuspendCOAAccountCode,
					   RR_DATA_Revenue.Transactionid Transactionid,
					   RR_DATA_Revenue.saleid saleid,
					   RR_DATA_Revenue.SaleItemid saleitemid,
					   RR_DATA_Revenue.Matrixcellid Matrixcell,
					   RR_DATA_Revenue.MatrixcellCode MatrixcellCode,
					   RR_DATA_Revenue.MatrixSheetId MatrixSheetId,
					   RR_DATA_Revenue.Siteid Siteid,
					   RR_DATA_Revenue.OperatingAreaId OperatingAreaId,
					   RR_DATA_Revenue.Workstationid Workstationid,
					   @UserGroupid UserGroupid,
					   RR_DATA_Revenue.UserId UserId,
					   @BatchDate BatchDate,
						case when @RRTransDateType = 0 then DATA_Transaction.ftransactiondate 
							else DATA_Transaction.transactiondate
						end as TransDate,
					   0 GrossAmount,
					   0 NetAmount,
					   @SuspendPrice SuspendPrice,
					   @SuspendCOAAccount_Percentage percentage,
					   @SuspendRemainingValues RemainingValues,
					   case when RR_DATA_Revenue.RRCalcTypeTrigger = 5 and data_transaction.transactiontype &lt;&gt; 12 then 0
					        else RevenueAmount
						end RevenueAmount, 
					   ISNULL((select top 1 AccountingType 
								  from rr_data_revenue tt
								  where tt.COAAccountId = @SuspendID
									and tt.transactionid = rr_data_revenue.transactionid
									and tt.saleitemid = rr_data_revenue.saleitemid),
								(select top 1 AccountingType 
								  from rr_data_revenue tt
								  where tt.COAAccountId = @SuspendID
									and tt.transactionid = rr_data_revenue.transactionid)
								)	 as Accountingtype,
					   @SuspendRRCalcTypeTrigger rrtrigger,
					   @SuspendPercentage percentage2,
					   @SuspendDays rrdays
	  
				from RR_DATA_Revenue
						INNER JOIN data_transaction					on data_transaction.transactionid = rr_data_revenue.transactionid
						LEFT JOIN DATA_SaleItem					on data_saleitem.saleid = data_transaction.saleid
				   where TransactionType in (5, 7, 8, 9, 10, 12, 13, 14, 18, 20, 22, 16, 30, 31, 34, 42, 43, 48, 49, 52) 
				     and rr_data_revenue.fcalcdate = @BatchDate
					 and rr_data_revenue.coaaccountid not in (select coaaccountid
					                                            from cnf_paymentmethod
																where coaaccountid is not null
															  UNION ALL 
															  select coaaccountid
					                                            from cnf_paymentcard
																where coaaccountid is not null
															  UNION ALL
															   select coaaccountid
					                                            from cnf_tax
																where coaaccountid is not null
															  UNION ALL
															   select coaaccountid
					                                            from cnf_promotion
																where coaaccountid is not null
															  UNION ALL
															    select feecoaaccountid
																 from cnf_paymentmethod
																 where feecoaaccountid is not null
															  UNION ALL
															    select returnedCheckcoaaccountid
																 from cnf_paymentmethod
																 where returnedCheckcoaaccountid is not null
															)
					 and rr_data_revenue.coaaccountid not in (@SuspendID, @ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)
				)p	
				
				group by   SuspendCOAAccountId,
						   SuspendRRRId,
						   SuspendRRRCode,
						   SuspendRRCalcTypeWhere,
						   SuspendRRCalcTypeMethod,
						   SuspendCOAAccountConfigId,
						   SuspendCOAAccountTypeId,
						   SuspendCOAAccountCode,
						   Transactionid,
						   saleid,
						   Siteid,
						   OperatingAreaId,
						   Workstationid,
						   UserGroupid,
						   UserId,
						   BatchDate,
						   TransDate,
						   GrossAmount,
						   NetAmount,
						   SuspendPrice,
						   percentage,
						   RemainingValues,
						   accountingtype,
						   rrtrigger,
						   percentage2,
					       rrdays									  																			
	end
END

</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT *
			FROM   sys.objects
			WHERE  object_id = OBJECT_ID(N'[dbo].[otn_sp_RR_RevenueData_batchJob]')
				AND type IN ( N'P'))
  DROP Procedure [dbo].otn_sp_RR_RevenueData_batchJob
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE Procedure dbo.otn_sp_RR_RevenueData_batchJob	 
	@BatchDate Date
AS 
BEGIN
	Declare @RRTransDateType Integer


	Declare @SuspendRRRId Integer
	Declare @SuspendCOAAccountId Integer
	Declare @SuspendRRRCode varchar(10)
	Declare @SuspendRRCalcTypeTrigger Integer
	Declare @SuspendRRCalcTypeWhere Integer
	Declare @SuspendRRCalcTypeMethod Integer
	Declare @SuspendCOAAccountConfigId Integer
	Declare @SuspendCOAAccountTypeId Integer
	Declare @SuspendCOAAccountCode varchar(10)
	Declare @SuspendPercentage float
	Declare @SuspendDays Integer
	Declare @SuspendPrice float
	Declare @SuspendCOAAccount_Percentage Float
	Declare @SuspendRemainingValues Integer
	Declare @SuspendRRCOAAccountingType Integer
	Declare @SuspendAccountingType Integer

	Declare @PaymentRRRId Integer
	Declare @PaymentCOAAccountId Integer
	Declare @PaymentRRRCode varchar(10)
	Declare @PaymentRRCalcTypeTrigger Integer
	Declare @PaymentRRCalcTypeWhere Integer
	Declare @PaymentRRCalcTypeMethod Integer
	Declare @PaymentCOAAccountConfigId Integer
	Declare @PaymentCOAAccountTypeId Integer
	Declare @PaymentCOAAccountCode varchar(10)
	Declare @PaymentPercentage float
	Declare @PaymentDays Integer
	Declare @PaymentPrice float
	Declare @PaymentCOAAccount_Percentage Float
	Declare @PaymentRemainingValues Integer
	Declare @PaymentRRCOAAccountingType Integer
	Declare @PaymentAccountingType Integer


	Declare @TaxRRRId Integer
	Declare @TaxCOAAccountId Integer
	Declare @TaxRRRCode varchar(10)
	Declare @TaxRRCalcTypeTrigger Integer
	Declare @TaxRRCalcTypeWhere Integer
	Declare @TaxRRCalcTypeMethod Integer
	Declare @TaxCOAAccountConfigId Integer
	Declare @TaxCOAAccountTypeId Integer
	Declare @TaxCOAAccountCode varchar(10)
	Declare @TaxPercentage float
	Declare @TaxDays Integer
	Declare @TaxPrice float
	Declare @TaxCOAAccount_Percentage Float
	Declare @TaxRemainingValues Integer
	Declare @TaxRRCOAAccountingType Integer
	Declare @TaxAccountingType Integer


	Declare @DiscountRRRId Integer
	Declare @DiscountCOAAccountId Integer
	Declare @DiscountRRRCode varchar(10)
	Declare @DiscountRRCalcTypeTrigger Integer
	Declare @DiscountRRCalcTypeWhere Integer
	Declare @DiscountRRCalcTypeMethod Integer
	Declare @DiscountCOAAccountConfigId Integer
	Declare @DiscountCOAAccountTypeId Integer
	Declare @DiscountCOAAccountCode varchar(10)
	Declare @DiscountPercentage float
	Declare @DiscountDays Integer
	Declare @DiscountPrice float
	Declare @DiscountCOAAccount_Percentage Float
	Declare @DiscountRemainingValues Integer
	Declare @DiscountRRCOAAccountingType Integer
	Declare @DiscountAccountingType Integer

	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer

	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1

	delete from rr_data_revenue
	where fcalcdate = @BatchDate 


	select @RRTransDateType = RRTransDateType
      from cnf_system

--Begin Move Transactions to Suspend Account
	select TOP 1 @SuspendRRRId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
			@SuspendRRRCode = RR_CNF_RevenueRecognitionRule.code,
			@SuspendRRCalcTypeTrigger = RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
			@SuspendRRCalcTypeWhere = RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
			@SuspendRRCalcTypeMethod = RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
			@SuspendCOAAccountConfigId = COA_CNF_AccountConfig.COAAccountConfigId,
			@SuspendCOAAccountTypeId = COA_CNF_AccountType.COAAccountTypeId,
			@SuspendCOAAccountId = coa_cnf_account.COAAccountId,
			@SuspendPercentage = RR_CNF_RevenueRecognitionRule.Percentage,
			@SuspendDays = RR_CNF_RevenueRecognitionRule.Days,
			@SuspendPrice = COA_CNF_AccountConfig.Price,
			@SuspendCOAAccount_Percentage = COA_CNF_AccountConfig.Percentage,
			@SuspendRemainingValues = COA_CNF_AccountConfig.RemainingValues,
			@SuspendCOAAccountCode = coa_cnf_account.Code,
			@SuspendRRCOAAccountingType = COA_CNF_AccountConfig.AccountingType
	from coa_cnf_account
		INNER JOIN COA_CNF_AccountType				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
		INNER JOIN COA_CNF_AccountConfig			on COA_CNF_AccountConfig.COAAccountId = coa_cnf_account.COAAccountId
		INNER JOIN RR_CNF_RevenueRecognitionRule	on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId
	where coa_cnf_account.COAAccountID = @SuspendID
	 order by RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId

	select TOP 1 @PaymentRRRId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
			@PaymentRRRCode = RR_CNF_RevenueRecognitionRule.code,
			@PaymentRRCalcTypeTrigger = RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
			@PaymentRRCalcTypeWhere = RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
			@PaymentRRCalcTypeMethod = RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
			@PaymentCOAAccountConfigId = COA_CNF_AccountConfig.COAAccountConfigId,
			@PaymentCOAAccountTypeId = COA_CNF_AccountType.COAAccountTypeId,
			@PaymentCOAAccountId = coa_cnf_account.COAAccountId,
			@PaymentPercentage = RR_CNF_RevenueRecognitionRule.Percentage,
			@PaymentDays = RR_CNF_RevenueRecognitionRule.Days,
			@PaymentPrice = COA_CNF_AccountConfig.Price,
			@PaymentCOAAccount_Percentage = COA_CNF_AccountConfig.Percentage,
			@PaymentRemainingValues = COA_CNF_AccountConfig.RemainingValues,
			@PaymentCOAAccountCode = coa_cnf_account.Code,
			@PaymentRRCOAAccountingType = COA_CNF_AccountConfig.AccountingType
	from coa_cnf_account
		INNER JOIN COA_CNF_AccountType				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
		INNER JOIN COA_CNF_AccountConfig			on COA_CNF_AccountConfig.COAAccountId = coa_cnf_account.COAAccountId
		INNER JOIN RR_CNF_RevenueRecognitionRule	on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId
	where coa_cnf_account.COAAccountID = @ACCPaymentMethod
	 order by RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId

	select TOP 1 @TaxRRRId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
			@TaxRRRCode = RR_CNF_RevenueRecognitionRule.code,
			@TaxRRCalcTypeTrigger = RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
			@TaxRRCalcTypeWhere = RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
			@TaxRRCalcTypeMethod = RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
			@TaxCOAAccountConfigId = COA_CNF_AccountConfig.COAAccountConfigId,
			@TaxCOAAccountTypeId = COA_CNF_AccountType.COAAccountTypeId,
			@TaxCOAAccountId = coa_cnf_account.COAAccountId,
			@TaxPercentage = RR_CNF_RevenueRecognitionRule.Percentage,
			@TaxDays = RR_CNF_RevenueRecognitionRule.Days,
			@TaxPrice = COA_CNF_AccountConfig.Price,
			@TaxCOAAccount_Percentage = COA_CNF_AccountConfig.Percentage,
			@TaxRemainingValues = COA_CNF_AccountConfig.RemainingValues,
			@TaxCOAAccountCode = coa_cnf_account.Code,
			@TaxRRCOAAccountingType = COA_CNF_AccountConfig.AccountingType
	from coa_cnf_account
		INNER JOIN COA_CNF_AccountType				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
		INNER JOIN COA_CNF_AccountConfig			on COA_CNF_AccountConfig.COAAccountId = coa_cnf_account.COAAccountId
		INNER JOIN RR_CNF_RevenueRecognitionRule	on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId
	where coa_cnf_account.COAAccountID = @TaxAccountID
	 order by RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId

	select TOP 1 @DiscountRRRId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
			@DiscountRRRCode = RR_CNF_RevenueRecognitionRule.code,
			@DiscountRRCalcTypeTrigger = RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
			@DiscountRRCalcTypeWhere = RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
			@DiscountRRCalcTypeMethod = RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
			@DiscountCOAAccountConfigId = COA_CNF_AccountConfig.COAAccountConfigId,
			@DiscountCOAAccountTypeId = COA_CNF_AccountType.COAAccountTypeId,
			@DiscountCOAAccountId = coa_cnf_account.COAAccountId,
			@DiscountPercentage = RR_CNF_RevenueRecognitionRule.Percentage,
			@DiscountDays = RR_CNF_RevenueRecognitionRule.Days,
			@DiscountPrice = COA_CNF_AccountConfig.Price,
			@DiscountCOAAccount_Percentage = COA_CNF_AccountConfig.Percentage,
			@DiscountRemainingValues = COA_CNF_AccountConfig.RemainingValues,
			@DiscountCOAAccountCode = coa_cnf_account.Code,
			@DiscountRRCOAAccountingType = COA_CNF_AccountConfig.AccountingType
	from coa_cnf_account
		INNER JOIN COA_CNF_AccountType				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
		INNER JOIN COA_CNF_AccountConfig			on COA_CNF_AccountConfig.COAAccountId = coa_cnf_account.COAAccountId
		INNER JOIN RR_CNF_RevenueRecognitionRule	on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId
	where coa_cnf_account.COAAccountID = @DiscountAccountID
	 order by RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId

INSERT INTO [dbo].[RR_DATA_Revenue]
				([COAAccountId]
				,[RevenueRecognitionRuleId]
				,[RRCode]
				,[RRCalcTypeWhere]
				,[RRCalcTypeMethod]
				,[COAAccountConfigId]
				,[COAAccountType]
				,[COAAccountCode]
				,[TransactionId]
				,[SaleId]
				,[SaleItemId]
				,[MatrixCellId]
				,[MatrixCellCode]
				,[MatrixSheetID]
				,[SiteId]
				,[OperatingAreaId]
				,[WorkstationId]
				,[UserGroupId]
				,[UserId]
				,[FCalcDate]
				,[FRevenueDate]
				,[Quantity]
				,[UnitAmount]
				,[GrossAmount]
				,[NetAmount]
				,[Price]
				,[Percentage]
				,[RemaningValues]
				,[RevenueAmount]
				,[AccountingType]
				,[RRCalcTypeTrigger]
				,[RRPercentage]
				,[RRDays])
		select @SuspendCOAAccountId,
				@SuspendRRRId,
				@SuspendRRRCode,
				@SuspendRRCalcTypeWhere,
				@SuspendRRCalcTypeMethod,
				@SuspendCOAAccountConfigId,
				@SuspendCOAAccountTypeId,
				@SuspendCOAAccountCode,
				data_transaction.transactionid, 
				data_transaction.saleid,
				DATA_TransactionItem.saleitemid,
				DATA_SaleItem.Matrixcellid,
				CNF_MatrixCell.Code,
				CNF_MatrixCell.MatrixSheetid,
				data_transaction.Siteid,
				data_transaction.OperatingAreaId,
				data_transaction.Workstationid,
				data_transaction.UserGroupid,
				data_transaction.UserId,
				@BatchDate,
				CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
				     else data_transaction.TransactionDate
				end TransactionDate,
				Coalesce(DATA_TransactionItem.Quantity, 1),
				DATA_SaleItem.UnitPrice,
				case when isnull(DATA_TransactionItem.TotalAmount, 0) &lt;&gt; 0 then DATA_TransactionItem.TotalAmount
					when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
					else DATA_Sale.TotalAmount
				end,
				case when isnull((DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes)
					when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
					else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
				end as NetAmount,
				@SuspendPrice,
				@SuspendCOAAccount_Percentage,
				@SuspendRemainingValues,
				case    when (data_saleitem.ProductTaxType &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) 
				                  and (isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0) 
								       and (((select discountamount from data_saleitemrule where saleitemid = DATA_SaleItem.saleitemid) &gt; 0) and (data_transaction.transactiontype in (7, 20, 22)))							
                            then ((DATA_SaleItem.UnitPrice + DATA_SaleItem.unittaxes) * DATA_SaleItem.Quantity)
				        when (data_saleitem.ProductTaxType &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice ) * DATA_SaleItem.Quantity)
						when (data_saleitem.ProductTaxType = 1) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice - DATA_SaleItem.unittaxes) * DATA_SaleItem.Quantity)
						when (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 then 0
						
						when isnull((data_transaction.TotalAmount), 0) &lt;&gt; 0 then data_transaction.TotalAmount
						when isnull((DATA_Sale.TotalAmount), 0) &lt;&gt; 0 then DATA_Sale.TotalAmount
						else (data_transaction.Revenue)
				end,
				case    when TransactionType in (5, 8, 17, 18, 20, 22, 30) and @SuspendRRCOAAccountingType = 1 then 2
						when TransactionType in (5, 8, 17, 18, 20, 22, 30) and @SuspendRRCOAAccountingType = 2 then 1
						when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 1
						when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 2
						else @SuspendRRCOAAccountingType
				end Accountingtype,
				@SuspendRRCalcTypeTrigger,
				@SuspendPercentage,
				@SuspendDays
	   
		from DATA_Sale
			inner join data_transaction			on data_transaction.TransactionId = DATA_Sale.PaidTransactionId
			left join DATA_TransactionItem		on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
			left join DATA_SaleItem			    on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
			left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid

		where DATA_Sale.Paid = 1
			and data_transaction.transactiontype in (14)
			and ftransactiondate = @BatchDate
			and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
			   OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
			and data_transaction.transactionid in (select transactionid
													from data_payment
													where PaymentStatus = 1
													and PaymentAmount &lt;&gt; 0
												)

INSERT INTO [dbo].[RR_DATA_Revenue]
				([COAAccountId]
				,[RevenueRecognitionRuleId]
				,[RRCode]
				,[RRCalcTypeWhere]
				,[RRCalcTypeMethod]
				,[COAAccountConfigId]
				,[COAAccountType]
				,[COAAccountCode]
				,[TransactionId]
				,[SaleId]
				,[SaleItemId]
				,[MatrixCellId]
				,[MatrixCellCode]
				,[MatrixSheetID]
				,[SiteId]
				,[OperatingAreaId]
				,[WorkstationId]
				,[UserGroupId]
				,[UserId]
				,[FCalcDate]
				,[FRevenueDate]
				,[Quantity]
				,[UnitAmount]
				,[GrossAmount]
				,[NetAmount]
				,[Price]
				,[Percentage]
				,[RemaningValues]
				,[RevenueAmount]
				,[AccountingType]
				,[RRCalcTypeTrigger]
				,[RRPercentage]
				,[RRDays])
		select @SuspendCOAAccountId,
				@SuspendRRRId,
				@SuspendRRRCode,
				@SuspendRRCalcTypeWhere,
				@SuspendRRCalcTypeMethod,
				@SuspendCOAAccountConfigId,
				@SuspendCOAAccountTypeId,
				@SuspendCOAAccountCode,
				data_transaction.transactionid, 
				data_transaction.saleid,
				DATA_TransactionItem.saleitemid,
				DATA_SaleItem.Matrixcellid,
				CNF_MatrixCell.Code,
				CNF_MatrixCell.MatrixSheetid,
				data_transaction.Siteid,
				data_transaction.OperatingAreaId,
				data_transaction.Workstationid,
				data_transaction.UserGroupid,
				data_transaction.UserId,
				@BatchDate,
				CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
				     else data_transaction.TransactionDate
				end TransactionDate,
				Coalesce(DATA_TransactionItem.Quantity, 1),
				DATA_SaleItem.UnitPrice,
				case when isnull(DATA_TransactionItem.TotalAmount, 0) &lt;&gt; 0 then DATA_TransactionItem.TotalAmount
					when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
					else DATA_Sale.TotalAmount
				end,
				case when isnull((DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes)
					when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
					else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
				end as NetAmount,
				@SuspendPrice,
				@SuspendCOAAccount_Percentage,
				@SuspendRemainingValues,
				DATA_SaleItem.UnitRecharge,
				case    when TransactionType in (5, 8, 17, 18, 20, 22, 30) and @SuspendRRCOAAccountingType = 1 then 2
						when TransactionType in (5, 8, 17, 18, 20, 22, 30) and @SuspendRRCOAAccountingType = 2 then 1
						when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 1
						when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 2
						else @SuspendRRCOAAccountingType
				end Accountingtype,
				@SuspendRRCalcTypeTrigger,
				@SuspendPercentage,
				@SuspendDays
	   
		from DATA_Sale
			inner join data_transaction			on data_transaction.TransactionId = DATA_Sale.PaidTransactionId
			left join DATA_TransactionItem		on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
			left join DATA_SaleItem			    on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
			left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid

		where DATA_Sale.Paid = 1
			and data_transaction.transactiontype in (14, 39)
			and DATA_SaleItem.UnitRecharge &lt;&gt; 0
			and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
			   OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
			and data_transaction.transactionid in (select transactionid
													from data_payment
													where PaymentStatus = 1
													and PaymentAmount &lt;&gt; 0
												)

	INSERT INTO [dbo].[RR_DATA_Revenue]
				([COAAccountId]
				,[RevenueRecognitionRuleId]
				,[RRCode]
				,[RRCalcTypeWhere]
				,[RRCalcTypeMethod]
				,[COAAccountConfigId]
				,[COAAccountType]
				,[COAAccountCode]
				,[TransactionId]
				,[SaleId]
				,[SaleItemId]
				,[MatrixCellId]
				,[MatrixCellCode]
				,[MatrixSheetID]
				,[SiteId]
				,[OperatingAreaId]
				,[WorkstationId]
				,[UserGroupId]
				,[UserId]
				,[FCalcDate]
				,[FRevenueDate]
				,[Quantity]
				,[UnitAmount]
				,[GrossAmount]
				,[NetAmount]
				,[Price]
				,[Percentage]
				,[RemaningValues]
				,[RevenueAmount]
				,[AccountingType]
				,[RRCalcTypeTrigger]
				,[RRPercentage]
				,[RRDays])
		select @SuspendCOAAccountId,
				@SuspendRRRId,
				@SuspendRRRCode,
				@SuspendRRCalcTypeWhere,
				@SuspendRRCalcTypeMethod,
				@SuspendCOAAccountConfigId,
				@SuspendCOAAccountTypeId,
				@SuspendCOAAccountCode,
				data_transaction.transactionid, 
				data_transaction.saleid,
				DATA_TransactionItem.saleitemid,
				DATA_SaleItem.Matrixcellid,
				CNF_MatrixCell.Code,
				CNF_MatrixCell.MatrixSheetid,
				data_transaction.Siteid,
				data_transaction.OperatingAreaId,
				data_transaction.Workstationid,
				data_transaction.UserGroupid,
				data_transaction.UserId,
				@BatchDate,
				CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
				     else data_transaction.TransactionDate
				end TransactionDate,
				Coalesce(DATA_TransactionItem.Quantity, 1),
				DATA_SaleItem.UnitPrice,
				case when isnull(DATA_TransactionItem.TotalAmount, 0) &lt;&gt; 0 then DATA_TransactionItem.TotalAmount
					when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
					else DATA_Sale.TotalAmount
				end,
				case when isnull((DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes)
					when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
					else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
				end as NetAmount,
				@SuspendPrice,
				@SuspendCOAAccount_Percentage,
				@SuspendRemainingValues,
				case    when (data_saleitem.ProductTaxType &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) 
				                  and (isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0) 
								       and (((select discountamount from data_saleitemrule where saleitemid = DATA_SaleItem.saleitemid) &gt; 0) and (data_transaction.transactiontype in (7, 20, 22)))							
                            then ((DATA_SaleItem.UnitPrice + DATA_SaleItem.unittaxes + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)
				        when (data_saleitem.ProductTaxType &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice  + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)
						when (data_saleitem.ProductTaxType = 1) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice - DATA_SaleItem.unittaxes + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)
						when (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 then 0
						when (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 and data_saleitem.unitRecharge &lt;&gt; 0 then data_saleitem.unitRecharge
						when isnull((data_transaction.TotalAmount), 0) &lt;&gt; 0 then data_transaction.TotalAmount
						when isnull((DATA_Sale.TotalAmount), 0) &lt;&gt; 0 then DATA_Sale.TotalAmount
						else (data_transaction.Revenue)
				end,
				case    when TransactionType in (5, 8, 17, 18, 20, 22, 30) and @SuspendRRCOAAccountingType = 1 then 2
						when TransactionType in (5, 8, 17, 18, 20, 22, 30) and @SuspendRRCOAAccountingType = 2 then 1
						when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 1
						when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 2
						else @SuspendRRCOAAccountingType
				end Accountingtype,
				@SuspendRRCalcTypeTrigger,
				@SuspendPercentage,
				@SuspendDays
	   
		from DATA_Sale
			inner join data_transaction			on data_transaction.TransactionId = ISNULL(data_sale.voidtransactionid, DATA_Sale.PaidTransactionId)
			left join DATA_TransactionItem		on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
			left join DATA_SaleItem			    on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
			left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid

		where DATA_Sale.Paid = 1
			and data_transaction.transactiontype not in (8, 10, 12, 14, 16, 42, 43, 31, 39, 48, 49, 52)
			and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
			   OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
			and data_transaction.transactionid in (select transactionid
													from data_payment
													where PaymentStatus = 1
													and PaymentAmount &lt;&gt; 0
												)

--INSERT INTO [dbo].[RR_DATA_Revenue]
--				([COAAccountId]
--				,[RevenueRecognitionRuleId]
--				,[RRCode]
--				,[RRCalcTypeWhere]
--				,[RRCalcTypeMethod]
--				,[COAAccountConfigId]
--				,[COAAccountType]
--				,[COAAccountCode]
--				,[TransactionId]
--				,[SaleId]
--				,[SaleItemId]
--				,[MatrixCellId]
--				,[MatrixCellCode]
--				,[MatrixSheetID]
--				,[SiteId]
--				,[OperatingAreaId]
--				,[WorkstationId]
--				,[UserGroupId]
--				,[UserId]
--				,[FCalcDate]
--				,[FRevenueDate]
--				,[Quantity]
--				,[UnitAmount]
--				,[GrossAmount]
--				,[NetAmount]
--				,[Price]
--				,[Percentage]
--				,[RemaningValues]
--				,[RevenueAmount]
--				,[AccountingType]
--				,[RRCalcTypeTrigger]
--				,[RRPercentage]
--				,[RRDays])
--		select @SuspendCOAAccountId,
--				@SuspendRRRId,
--				@SuspendRRRCode,
--				@SuspendRRCalcTypeWhere,
--				@SuspendRRCalcTypeMethod,
--				@SuspendCOAAccountConfigId,
--				@SuspendCOAAccountTypeId,
--				@SuspendCOAAccountCode,
--				data_transaction.transactionid, 
--				data_transaction.saleid,
--				DATA_SaleItem.saleitemid,
--				DATA_SaleItem.Matrixcellid,
--				CNF_MatrixCell.Code,
--				CNF_MatrixCell.MatrixSheetid,
--				data_transaction.Siteid,
--				data_transaction.OperatingAreaId,
--				data_transaction.Workstationid,
--				data_transaction.UserGroupid,
--				data_transaction.UserId,
--				@BatchDate,
--				Data_Transaction.TransactionDate,
--				Coalesce(DATA_SaleItem.Quantity, 1),
--				DATA_SaleItem.UnitPrice,
--				case when isnull(DATA_SaleItem.TotalAmount, 0) &lt;&gt; 0 then DATA_SaleItem.TotalAmount
--					when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
--					else DATA_Sale.TotalAmount
--				end,
--				case when isnull((DATA_SaleItem.TotalAmount - DATA_SaleItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_SaleItem.TotalAmount - DATA_SaleItem.TotalTaxes)
--					when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
--					else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
--				end as NetAmount,
--				@SuspendPrice,
--				@SuspendCOAAccount_Percentage,
--				@SuspendRemainingValues,
--				case when (data_saleitem.ProductTaxType &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) 
--				             and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 
--							     and (((select discountamount from data_saleitemrule where saleitemid = DATA_SaleItem.saleitemid) &gt; 0) and (data_transaction.transactiontype in (7, 20, 22)))							
--                            then ((DATA_SaleItem.UnitPrice + DATA_SaleItem.unittaxes + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)
--				        when (data_saleitem.ProductTaxType &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice + DATA_SaleItem.unittaxes + data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)
--						when (data_saleitem.ProductTaxType = 1) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice+ data_saleitem.unitRecharge) * DATA_SaleItem.Quantity)
--						when (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 then 0
--						when (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 and data_saleitem.unitRecharge &lt;&gt; 0 then data_saleitem.unitRecharge
--						when isnull((data_transaction.TotalAmount), 0) &lt;&gt; 0 then data_transaction.TotalAmount
--						when isnull((DATA_Sale.TotalAmount), 0) &lt;&gt; 0 then DATA_Sale.TotalAmount
--						else (data_transaction.Revenue)
--				end + 


--					(case when data_saleitem.saleitemid = (select top 1 saleitemid
--														from data_saleitem si
--														where si.saleid = data_sale.saleid
--														and totalamount &gt; 0)
--						then (select sum(Paymentfee)
--									from data_payment
--									where data_payment.transactionid = data_transaction.Transactionid)
--						else 0
--					end) ,
--				case    when TransactionType in (5, 17, 8, 18, 20, 22, 30) and @SuspendRRCOAAccountingType = 1 then 2
--						when TransactionType in (5, 17, 8, 18, 20, 22, 30) and @SuspendRRCOAAccountingType = 2 then 1
--						when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 2
--						when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 1
--						else @SuspendRRCOAAccountingType
--				end Accountingtype,
--				@SuspendRRCalcTypeTrigger,
--				@SuspendPercentage,
--				@SuspendDays
	   
--		from DATA_Sale
--			inner join data_transaction			on data_transaction.saleid = DATA_Sale.saleid
--			left join DATA_SaleItem			    on DATA_SaleItem.saleid = DATA_Sale.saleid
--			left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid

--		where DATA_Sale.Paid = 1
--			and data_transaction.transactiontype not in (8, 10, 12, 16, 42, 43, 31, 39, 48, 49, 52)
			--and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
			--   OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
--			and data_transaction.transactionid in (select transactionid
--													from data_payment
--													where PaymentStatus = 1
--													and PaymentAmount &lt;&gt; 0
--												)
--			and DATA_SaleItem.saleitemid not in (select distinct saleitemid
--			                                       from rr_data_revenue
--												   where fcalcdate = @BatchDate
--												   and saleitemid is not null
--												)


	INSERT INTO [dbo].[RR_DATA_Revenue]
				([COAAccountId]
				,[RevenueRecognitionRuleId]
				,[RRCode]
				,[RRCalcTypeWhere]
				,[RRCalcTypeMethod]
				,[COAAccountConfigId]
				,[COAAccountType]
				,[COAAccountCode]
				,[TransactionId]
				,[SaleId]
				,[SaleItemId]
				,[MatrixCellId]
				,[MatrixCellCode]
				,[MatrixSheetID]
				,[SiteId]
				,[OperatingAreaId]
				,[WorkstationId]
				,[UserGroupId]
				,[UserId]
				,[FCalcDate]
				,[FRevenueDate]
				,[Quantity]
				,[UnitAmount]
				,[GrossAmount]
				,[NetAmount]
				,[Price]
				,[Percentage]
				,[RemaningValues]
				,[RevenueAmount]
				,[AccountingType]
				,[RRCalcTypeTrigger]
				,[RRPercentage]
				,[RRDays])
		select @SuspendCOAAccountId,
				@SuspendRRRId,
				@SuspendRRRCode,
				@SuspendRRCalcTypeWhere,
				@SuspendRRCalcTypeMethod,
				@SuspendCOAAccountConfigId,
				@SuspendCOAAccountTypeId,
				@SuspendCOAAccountCode,
				data_transaction.transactionid, 
				data_transaction.saleid,
				DATA_TransactionItem.saleitemid,
				DATA_SaleItem.Matrixcellid,
				CNF_MatrixCell.Code,
				CNF_MatrixCell.MatrixSheetid,
				data_transaction.Siteid,
				data_transaction.OperatingAreaId,
				data_transaction.Workstationid,
				data_transaction.UserGroupid,
				data_transaction.UserId,
				@BatchDate,
				CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
				     else data_transaction.TransactionDate
				end TransactionDate,
				Coalesce(DATA_TransactionItem.Quantity, 1),
				DATA_SaleItem.UnitPrice,
				case when isnull(DATA_TransactionItem.TotalAmount, 0) &lt;&gt; 0 then DATA_TransactionItem.TotalAmount
					when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
					else DATA_Sale.TotalAmount
				end,
				case when isnull((DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes)
					when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
					else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
				end as NetAmount,
				@SuspendPrice,
				@SuspendCOAAccount_Percentage,
				@SuspendRemainingValues,
				DATA_SaleItem.Unitrecharge,
				case    when TransactionType in (5, 17, 8, 18, 20, 22, 30) and @SuspendRRCOAAccountingType = 1 then 2
						when TransactionType in (5, 17, 8, 18, 20, 22, 30) and @SuspendRRCOAAccountingType = 2 then 1
						when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 2
						when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 1
						else @SuspendRRCOAAccountingType
				end Accountingtype,
				@SuspendRRCalcTypeTrigger,
				@SuspendPercentage,
				@SuspendDays
	   
		from DATA_Sale
			inner join data_transaction			on data_transaction.TransactionId = ISNULL(data_sale.voidtransactionid, DATA_Sale.PaidTransactionId)
			left join DATA_TransactionItem		on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
			left join DATA_SaleItem			    on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
			left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid

		where DATA_Sale.Paid = 1
			and data_transaction.transactiontype in (10, 42, 43, 49)
			and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
			   OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
			and data_transaction.transactionid in (select transactionid
													from data_payment
													where PaymentStatus = 1
													and PaymentAmount &lt;&gt; 0
												)
			
INSERT INTO [dbo].[RR_DATA_Revenue]
				([COAAccountId]
				,[RevenueRecognitionRuleId]
				,[RRCode]
				,[RRCalcTypeWhere]
				,[RRCalcTypeMethod]
				,[COAAccountConfigId]
				,[COAAccountType]
				,[COAAccountCode]
				,[TransactionId]
				,[SaleId]
				,[SaleItemId]
				,[MatrixCellId]
				,[MatrixCellCode]
				,[MatrixSheetID]
				,[SiteId]
				,[OperatingAreaId]
				,[WorkstationId]
				,[UserGroupId]
				,[UserId]
				,[FCalcDate]
				,[FRevenueDate]
				,[Quantity]
				,[UnitAmount]
				,[GrossAmount]
				,[NetAmount]
				,[Price]
				,[Percentage]
				,[RemaningValues]
				,[RevenueAmount]
				,[AccountingType]
				,[RRCalcTypeTrigger]
				,[RRPercentage]
				,[RRDays])
		select @SuspendCOAAccountId,
				@SuspendRRRId,
				@SuspendRRRCode,
				@SuspendRRCalcTypeWhere,
				@SuspendRRCalcTypeMethod,
				@SuspendCOAAccountConfigId,
				@SuspendCOAAccountTypeId,
				@SuspendCOAAccountCode,
				data_transaction.transactionid, 
				data_transaction.saleid,
				DATA_TransactionItem.saleitemid,
				DATA_SaleItem.Matrixcellid,
				CNF_MatrixCell.Code,
				CNF_MatrixCell.MatrixSheetid,
				data_transaction.Siteid,
				data_transaction.OperatingAreaId,
				data_transaction.Workstationid,
				data_transaction.UserGroupid,
				data_transaction.UserId,
				@BatchDate,
				CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
				     else data_transaction.TransactionDate
				end TransactionDate,
				Coalesce(DATA_TransactionItem.Quantity, 1),
				DATA_SaleItem.UnitPrice,
				case when isnull(DATA_TransactionItem.TotalAmount, 0) &lt;&gt; 0 then DATA_TransactionItem.TotalAmount
					when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
					else DATA_Sale.TotalAmount
				end,
				case when isnull((DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes)
					when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
					else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
				end as NetAmount,
				@SuspendPrice,
				@SuspendCOAAccount_Percentage,
				@SuspendRemainingValues,
				ABS(DATA_SaleItem.Unitrecharge),
				case    when TransactionType in (5, 17, 8, 18, 20, 22, 30) and @SuspendRRCOAAccountingType = 1 then 2
						when TransactionType in (5, 17, 8, 18, 20, 22, 30) and @SuspendRRCOAAccountingType = 2 then 1
						when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 2
						when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 1
						else @SuspendRRCOAAccountingType
				end Accountingtype,
				@SuspendRRCalcTypeTrigger,
				@SuspendPercentage,
				@SuspendDays
	   
		from DATA_Sale
			inner join data_transaction			on data_transaction.TransactionId = ISNULL(data_sale.voidtransactionid, DATA_Sale.PaidTransactionId)
			left join DATA_TransactionItem		on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
			left join DATA_SaleItem			    on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
			left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid

		where DATA_Sale.Paid = 1
			and data_transaction.transactiontype in (31, 48, 52)
			and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
			   OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
			and data_transaction.transactionid in (select transactionid
													from data_payment
													where PaymentStatus = 1
													and PaymentAmount &lt;&gt; 0
												)


	INSERT INTO [dbo].[RR_DATA_Revenue]
						([COAAccountId]
						,[RevenueRecognitionRuleId]
						,[RRCode]
						,[RRCalcTypeWhere]
						,[RRCalcTypeMethod]
						,[COAAccountConfigId]
						,[COAAccountType]
						,[COAAccountCode]
						,[TransactionId]
						,[SaleId]
						,[SaleItemId]
						,[MatrixCellId]
						,[MatrixCellCode]
						,[MatrixSheetID]
						,[SiteId]
						,[OperatingAreaId]
						,[WorkstationId]
						,[UserGroupId]
						,[UserId]
						,[FCalcDate]
						,[FRevenueDate]
						,[Quantity]
						,[UnitAmount]
						,[GrossAmount]
						,[NetAmount]
						,[Price]
						,[Percentage]
						,[RemaningValues]
						,[RevenueAmount]
						,[AccountingType]
						,[RRCalcTypeTrigger]
						,[RRPercentage]
						,[RRDays])
				select @SuspendCOAAccountId,
						@SuspendRRRId,
						@SuspendRRRCode,
						@SuspendRRCalcTypeWhere,
						@SuspendRRCalcTypeMethod,
						@SuspendCOAAccountConfigId,
						@SuspendCOAAccountTypeId,
						@SuspendCOAAccountCode,
						data_transaction.transactionid, 
						data_transaction.saleid,
						DATA_TransactionItem.saleitemid,
						DATA_SaleItem.Matrixcellid,
						CNF_MatrixCell.Code,
						CNF_MatrixCell.MatrixSheetid,
						data_transaction.Siteid,
						data_transaction.OperatingAreaId,
						data_transaction.Workstationid,
						data_transaction.UserGroupid,
						data_transaction.UserId,
						@BatchDate,
						CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
							 else data_transaction.TransactionDate
						end TransactionDate,
						Coalesce(DATA_TransactionItem.Quantity, 1),
						DATA_SaleItem.UnitPrice,
						case when isnull(DATA_TransactionItem.TotalAmount, 0) &lt;&gt; 0 then DATA_TransactionItem.TotalAmount
							when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
							else DATA_Sale.TotalAmount
						end,
						case when isnull((DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes)
							when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
							else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
						end as NetAmount,
						@SuspendPrice,
						@SuspendCOAAccount_Percentage,
						@SuspendRemainingValues,
						case when (data_saleitem.ProductTaxType &lt;&gt; 1) and (DATA_SaleItem.UnitrawPrice is not null) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice + DATA_SaleItem.unittaxes) * DATA_SaleItem.Quantity)
						     when (data_saleitem.ProductTaxType = 1) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice) * DATA_SaleItem.Quantity)
						     when (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 then 0
							 when isnull((data_transaction.TotalAmount), 0) &lt;&gt; 0 then data_transaction.TotalAmount
							 when isnull((DATA_Sale.TotalAmount), 0) &lt;&gt; 0 then DATA_Sale.TotalAmount
							 else (data_transaction.Revenue)
						end,
						case    when TransactionType in (5, 8, 17, 18, 20, 22, 30) and @SuspendRRCOAAccountingType = 1 then 2
								when TransactionType in (5, 8, 17, 18, 20, 22, 30) and @SuspendRRCOAAccountingType = 2 then 1
								when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 2
								when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 1
								else @SuspendRRCOAAccountingType
						end Accountingtype,
						@SuspendRRCalcTypeTrigger,
						@SuspendPercentage,
						@SuspendDays
	   
				from DATA_Sale
					inner join data_transaction			on data_transaction.Saleid = DATA_Sale.Saleid
					left join DATA_TransactionItem		on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
					left join DATA_SaleItem			    on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
					left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid

				where data_transaction.transactiontype in (8)
					and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
						OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
					and data_transaction.transactionid in (select transactionid
															from data_payment
															where PaymentStatus = 1
															and PaymentAmount &lt;&gt; 0
														)

			INSERT INTO [dbo].[RR_DATA_Revenue]
						([COAAccountId]
						,[RevenueRecognitionRuleId]
						,[RRCode]
						,[RRCalcTypeWhere]
						,[RRCalcTypeMethod]
						,[COAAccountConfigId]
						,[COAAccountType]
						,[COAAccountCode]
						,[TransactionId]
						,[SaleId]
						,[SiteId]
						,[OperatingAreaId]
						,[WorkstationId]
						,[UserGroupId]
						,[UserId]
						,[FCalcDate]
						,[FRevenueDate]
						,[Quantity]
						,[GrossAmount]
						,[NetAmount]
						,[Price]
						,[Percentage]
						,[RemaningValues]
						,[RevenueAmount]
						,[AccountingType]
						,[RRCalcTypeTrigger]
						,[RRPercentage]
						,[RRDays])
				select @SuspendCOAAccountId,
						@SuspendRRRId,
						@SuspendRRRCode,
						@SuspendRRCalcTypeWhere,
						@SuspendRRCalcTypeMethod,
						@SuspendCOAAccountConfigId,
						@SuspendCOAAccountTypeId,
						@SuspendCOAAccountCode,
						data_transaction.transactionid, 
						data_transaction.saleid,
						data_transaction.Siteid,
						data_transaction.OperatingAreaId,
						data_transaction.Workstationid,
						data_transaction.UserGroupid,
						data_transaction.UserId,
						@BatchDate,
						CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
							 else data_transaction.TransactionDate
						end TransactionDate,
						0 Quantity,
						data_transaction.revenue TotalAmount,
						data_transaction.revenue NetAmount,
						@SuspendPrice,
						@SuspendCOAAccount_Percentage,
						@SuspendRemainingValues,
						data_transaction.revenue,
						@SuspendRRCOAAccountingType,
						@SuspendRRCalcTypeTrigger,
						@SuspendPercentage,
						@SuspendDays
	   
				from DATA_Sale
					inner join data_transaction			on data_transaction.saleid = DATA_Sale.saleid
				where data_transaction.transactiontype = 12
					and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
						OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
					and data_transaction.transactionid in (select transactionid
															from data_payment
															where PaymentStatus = 1
															and PaymentAmount &lt;&gt; 0
															and fPaymentDate = @BatchDate
														)
					and data_transaction.transactionid not in (select distinct transactionid
																from rr_data_Revenue
																where transactionid is not null)


				INSERT INTO [dbo].[RR_DATA_Revenue]
						([COAAccountId]
						,[RevenueRecognitionRuleId]
						,[RRCode]
						,[RRCalcTypeWhere]
						,[RRCalcTypeMethod]
						,[COAAccountConfigId]
						,[COAAccountType]
						,[COAAccountCode]
						,[TransactionId]
						,[SaleId]
						,[SaleItemId]
						,[MatrixCellId]
						,[MatrixCellCode]
						,[MatrixSheetID]
						,[SiteId]
						,[OperatingAreaId]
						,[WorkstationId]
						,[UserGroupId]
						,[UserId]
						,[FCalcDate]
						,[FRevenueDate]
						,[Quantity]
						,[UnitAmount]
						,[GrossAmount]
						,[NetAmount]
						,[Price]
						,[Percentage]
						,[RemaningValues]
						,[RevenueAmount]
						,[AccountingType]
						,[RRCalcTypeTrigger]
						,[RRPercentage]
						,[RRDays])
						select *
						from (
				select @SuspendCOAAccountId as COAAccountId,
						@SuspendRRRId as RevenueRecognitionRuleId,
						@SuspendRRRCode as RRCode,
						@SuspendRRCalcTypeWhere as RRCalcTypeWhere,
						@SuspendRRCalcTypeMethod as RRCalcTypeMethod,
						@SuspendCOAAccountConfigId as COAAccountConfigId,
						@SuspendCOAAccountTypeId as COAAccountType,
						@SuspendCOAAccountCode as COAAccountCode,
						data_transaction.transactionid, 
						data_transaction.saleid,
						DATA_SaleItem.saleitemid,
						DATA_SaleItem.Matrixcellid,
						CNF_MatrixCell.Code,
						CNF_MatrixCell.MatrixSheetid,
						data_transaction.Siteid,
						data_transaction.OperatingAreaId,
						data_transaction.Workstationid,
						data_transaction.UserGroupid,
						data_transaction.UserId,
						@BatchDate as calcdate,
						CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
								else data_transaction.TransactionDate
						end TransactionDate,
						Coalesce(DATA_SaleItem.Quantity, 1) as quantity,
						DATA_SaleItem.UnitPrice,
						case when isnull(DATA_SaleItem.TotalAmount, 0) &lt;&gt; 0 then DATA_SaleItem.TotalAmount
							when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
							else DATA_Sale.TotalAmount
						end as totalamount,
						case when isnull((DATA_SaleItem.TotalAmount - DATA_SaleItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_SaleItem.TotalAmount - DATA_SaleItem.TotalTaxes)
							when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
							else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
						end as NetAmount,
						@SuspendPrice as suspendprice,
						@SuspendCOAAccount_Percentage as percentage,
						@SuspendRemainingValues as remainingValues,
						case when (data_saleitem.ProductTaxType &lt;&gt; 1) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice) * DATA_SaleItem.Quantity)
						     when (data_saleitem.ProductTaxType = 1) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &lt;&gt; 0 then ((DATA_SaleItem.UnitrawPrice - DATA_SaleItem.unittaxes) * DATA_SaleItem.Quantity)
						     when isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 then 0
							 when isnull((data_transaction.TotalAmount), 0) &lt;&gt; 0 then data_transaction.TotalAmount
							 when isnull((DATA_Sale.TotalAmount), 0) &lt;&gt; 0 then DATA_Sale.TotalAmount
							 else (data_transaction.Revenue)
						end as Revenueamount,
						case    when TransactionType in (5, 8, 17, 18, 20, 22, 30) and @SuspendRRCOAAccountingType = 1 then 2
								when TransactionType in (5, 8, 17, 18, 20, 22, 30) and @SuspendRRCOAAccountingType = 2 then 1
								when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 2
								when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 1
								else @SuspendRRCOAAccountingType
						end Accountingtype,
						@SuspendRRCalcTypeTrigger as rrTrigger,
						@SuspendPercentage as suspercentage,
						@SuspendDays as suspendday
	   
				from DATA_Sale
					inner join data_transaction			on data_transaction.TransactionId = DATA_Sale.PaidTransactionId
					left join DATA_SaleItem			    on DATA_SaleItem.SAleid = data_transaction.SAleid
					left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid

				where DATA_Sale.Paid = 1
					and data_transaction.transactiontype in (16)
					and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
					 OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
					and data_transaction.transactionid in (select transactionid
															from data_payment
															where PaymentStatus = 1
															and PaymentAmount &lt;&gt; 0
														)
					and data_transaction.transactionid not in (select distinct transactionid
																from rr_data_Revenue
																where transactionid is not null)
					and data_saleitem.saleitemid not in (select distinct data_saleitem.saleitemid
													from data_saleitem
															inner join data_transactionitem   on data_transactionitem.saleitemid = data_saleitem.saleitemid
															inner join data_transaction       on data_transaction.transactionid = data_transactionitem.transactionid
													where data_transaction.transactiontype in (5)
													)
					)p  where UnitPrice &lt;&gt; 0


				INSERT INTO [dbo].[RR_DATA_Revenue]
						([COAAccountId]
						,[RevenueRecognitionRuleId]
						,[RRCode]
						,[RRCalcTypeWhere]
						,[RRCalcTypeMethod]
						,[COAAccountConfigId]
						,[COAAccountType]
						,[COAAccountCode]
						,[TransactionId]
						,[SaleId]
						,[SaleItemId]
						,[MatrixCellId]
						,[MatrixCellCode]
						,[MatrixSheetID]
						,[SiteId]
						,[OperatingAreaId]
						,[WorkstationId]
						,[UserGroupId]
						,[UserId]
						,[FCalcDate]
						,[FRevenueDate]
						,[Quantity]
						,[UnitAmount]
						,[GrossAmount]
						,[NetAmount]
						,[Price]
						,[Percentage]
						,[RemaningValues]
						,[RevenueAmount]
						,[AccountingType]
						,[RRCalcTypeTrigger]
						,[RRPercentage]
						,[RRDays])
				select @SuspendCOAAccountId,
						@SuspendRRRId,
						@SuspendRRRCode,
						@SuspendRRCalcTypeWhere,
						@SuspendRRCalcTypeMethod,
						@SuspendCOAAccountConfigId,
						@SuspendCOAAccountTypeId,
						@SuspendCOAAccountCode,
						data_transaction.transactionid, 
						data_transaction.saleid,
						DATA_TransactionItem.saleitemid,
						DATA_SaleItem.Matrixcellid,
						CNF_MatrixCell.Code,
						CNF_MatrixCell.MatrixSheetid,
						data_transaction.Siteid,
						data_transaction.OperatingAreaId,
						data_transaction.Workstationid,
						data_transaction.UserGroupid,
						data_transaction.UserId,
						@BatchDate,
						CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
							 else data_transaction.TransactionDate
						end TransactionDate,
						Coalesce(DATA_TransactionItem.Quantity, 1),
						DATA_SaleItem.UnitPrice,
						case when isnull(DATA_TransactionItem.TotalAmount, 0) &lt;&gt; 0 then DATA_TransactionItem.TotalAmount
							when isnull(data_transaction.TotalAmount, 0) &lt;&gt; 0 then data_transaction.TotalAmount
							else DATA_Sale.TotalAmount
						end,
						case when isnull((DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes), 0) &lt;&gt; 0 then (DATA_TransactionItem.TotalAmount - DATA_TransactionItem.TotalTaxes)
							when isnull((data_transaction.TotalAmount - DATA_Transaction.TotalTaxes), 0) &lt;&gt; 0 then (data_transaction.TotalAmount - DATA_Transaction.TotalTaxes)
							else (DATA_Sale.TotalAmount - DATA_Sale.TotalTaxes)
						end as NetAmount,
						@SuspendPrice,
						@SuspendCOAAccount_Percentage,
						@SuspendRemainingValues,
						case when isnull((DATA_TransactionItem.UnitPrice *  DATA_TransactionItem.Quantity), 0) &lt;&gt; 0 then (DATA_TransactionItem.UnitPrice *  DATA_TransactionItem.Quantity)
							when isnull((data_transaction.TotalAmount), 0) &lt;&gt; 0 then data_transaction.TotalAmount
							when isnull((DATA_Sale.TotalAmount), 0) &lt;&gt; 0 then DATA_Sale.TotalAmount
							else (data_transaction.Revenue)
						end,
						case    when TransactionType in (5, 8, 17, 18, 20, 22, 30) and @SuspendRRCOAAccountingType = 1 then 2
								when TransactionType in (5, 8, 17, 18, 20, 22, 30) and @SuspendRRCOAAccountingType = 2 then 1
								when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &lt;= 0  then 2
								when TransactionType in (7) and (DATA_SaleItem.TotalAmount) &gt; 0  then 1
								else @SuspendRRCOAAccountingType
						end Accountingtype,
						@SuspendRRCalcTypeTrigger,
						@SuspendPercentage,
						@SuspendDays
	   
				from DATA_Sale
					inner join data_transaction			on data_transaction.saleid = DATA_Sale.saleid
					inner join DATA_TransactionItem		on DATA_TransactionItem.TransactionId = data_transaction.TransactionId
					left join DATA_SaleItem			    on DATA_SaleItem.saleitemid = DATA_TransactionItem.SaleitemId
					left join CNF_MatrixCell			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid

				where DATA_Sale.Paid = 1
					and data_transaction.transactiontype in (5)
					and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
					 OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
					
					and data_transaction.transactionid in (select transactionid
															from data_payment
															where PaymentStatus = 1
															and PaymentAmount &lt;&gt; 0
														)
					and data_transaction.transactionid not in (select distinct transactionid
																from rr_data_Revenue
																where transactionid is not null)
--PaymentMethod
				INSERT INTO [dbo].[RR_DATA_Revenue]
								([COAAccountId]
								,[RevenueRecognitionRuleId]
								,[RRCode]
								,[RRCalcTypeWhere]
								,[RRCalcTypeMethod]
								,[COAAccountConfigId]
								,[COAAccountType]
								,[COAAccountCode]
								,[TransactionId]
								,[SaleId]
								,[SiteId]
								,[OperatingAreaId]
								,[WorkstationId]
								,[UserGroupId]
								,[UserId]
								,[FCalcDate]
								,[FRevenueDate]
								,[Quantity]
								,[GrossAmount]
								,[NetAmount]
								,[Price]
								,[Percentage]
								,[RemaningValues]
								,[RevenueAmount]
								,[AccountingType]
								,[RRCalcTypeTrigger]
								,[RRPercentage]
								,[RRDays])
								select  coaaccountid,
										RRID,
										RRCode,
										TypeWhere,
										method,
										Configid,
										AccountType,
										AccountCode,
										transactionid, 
										saleid,
										Siteid,
										OperatingAreaId,
										WorkstationID,
										UserGroupid,
										UserId,
										BatchDate,
										TransactionDate,
										Qty,
										Gross,
										net,
										price,
										percentage,
										RemaningValue,
										sum(abs(RevenueAmount)),
										Accountingtype,
										TypeTrigger,
										PaymentPercentage,
										RRDays
								from (
								select  coaaccountid,
										RRID,
										RRCode,
										TypeWhere,
										method,
										Configid,
										AccountType,
										AccountCode,
										transactionid, 
										saleid,
										Siteid,
										OperatingAreaId,
										WorkstationID,
										UserGroupid,
										UserId,
										BatchDate,
										TransactionDate,
										Qty,
										Gross,
										net,
										price,
										percentage,
										RemaningValue,
										case when Rownumber = 1 then RevenueAmount + Change
										     else RevenueAmount
										 end RevenueAmount,
										Accountingtype,
										TypeTrigger,
										PaymentPercentage,
										RRDays
								from (
								select @PaymentCOAAccountId as coaaccountid,
										@PaymentRRRId as RRID,
										@PaymentRRRCode as RRCode,
										@PaymentRRCalcTypeWhere as TypeWhere,
										@PaymentRRCalcTypeMethod as method,
										@PaymentCOAAccountConfigId as Configid,
										@PaymentCOAAccountTypeId as AccountType,
										@PaymentCOAAccountCode as AccountCode,
										data_transaction.transactionid, 
										data_transaction.saleid,
										data_transaction.Siteid,
										data_transaction.OperatingAreaId,
										data_transaction.Workstationid,
										data_transaction.UserGroupid,
										data_transaction.UserId,
										@BatchDate as BatchDate,
										CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
											 else data_transaction.TransactionDate
										end TransactionDate,
										0 as Qty,
										0 as Gross,
										0 as net,
										0 as price,
										100 as percentage,
										0 as RemaningValue,
										(data_payment.PaymentAmount) as RevenueAmount,
										case    when TransactionType in (5, 8, 17, 18, 20, 22, 30) and @PaymentRRCOAAccountingType = 1 then 2
												when TransactionType in (5, 8, 17, 18, 20, 22, 30) and @PaymentRRCOAAccountingType = 2 then 1
												when TransactionType in (7) and (data_payment.PaymentAmount + data_Payment.PaymentFee) &lt;= 0  then 2
												when TransactionType in (7) and (data_payment.PaymentAmount + data_Payment.PaymentFee) &gt; 0  then 1
												else @PaymentRRCOAAccountingType
									    end Accountingtype,
										data_transaction.Change,
										@PaymentRRCalcTypeTrigger as TypeTrigger,
										@PaymentPercentage as PaymentPercentage,
										@PaymentDays as RRDays,
										Row_Number ()  OVER (PARTITION BY data_transaction.transactionid order by data_transaction.transactionid)  as Rownumber
		  
								from DATA_Sale
											INNER join data_transaction			on ((data_transaction.TransactionId = Isnull(data_sale.voidtransactionid, DATA_Sale.PaidTransactionId)) or 
											                                       (data_transaction.saleid = data_sale.saleid))
											INNER JOIN DATA_Payment				on data_payment.transactionid = data_transaction.transactionid
			
								where data_payment.PaymentStatus = 1
									and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
									 OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
							)p
							)r
							group by 	coaaccountid,
										RRID,
										RRCode,
										TypeWhere,
										method,
										Configid,
										AccountType,
										AccountCode,
										transactionid, 
										saleid,
										Siteid,
										OperatingAreaId,
										Workstationid,
										UserGroupid,
										UserId,
										BatchDate,
										TransactionDate,
										Qty,
										Gross,
										net,
										price,
										percentage,
										RemaningValue,
										Accountingtype,
										TypeTrigger,
										PaymentPercentage,
										RRDays
						



--Tax
					INSERT INTO [dbo].[RR_DATA_Revenue]
								([COAAccountId]
								,[RevenueRecognitionRuleId]
								,[RRCode]
								,[RRCalcTypeWhere]
								,[RRCalcTypeMethod]
								,[COAAccountConfigId]
								,[COAAccountType]
								,[COAAccountCode]
								,[TransactionId]
								,[SaleId]
								,[SiteId]
								,[OperatingAreaId]
								,[WorkstationId]
								,[UserGroupId]
								,[UserId]
								,[FCalcDate]
								,[FRevenueDate]
								,[Quantity]
								,[GrossAmount]
								,[NetAmount]
								,[Price]
								,[Percentage]
								,[RemaningValues]
								,[RevenueAmount]
								,[AccountingType]
								,[RRCalcTypeTrigger]
								,[RRPercentage]
								,[RRDays])

								select  @TaxCOAAccountId,
										@TaxRRRId,
										@TaxRRRCode,
										@TaxRRCalcTypeWhere,
										@TaxRRCalcTypeMethod,
										@TaxCOAAccountConfigId,
										@TaxCOAAccountTypeId,
										@TaxCOAAccountCode,
										data_transaction.transactionid, 
										data_transaction.saleid,
										data_transaction.Siteid,
										data_transaction.OperatingAreaId,
										data_transaction.Workstationid,
										data_transaction.UserGroupid,
										data_transaction.UserId,
										@BatchDate,
										CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
											 else data_transaction.TransactionDate
										end TransactionDate,
										0,
										0,
										0,
										0,
										100,
										0,
										ABS(sum(taxamount)) RevenueAmount,
										case    when TransactionType in (5, 8, 17, 18, 20, 22, 30) and @TaxRRCOAAccountingType = 1 then 2
												when TransactionType in (5, 8, 17, 18, 20, 22, 30) and @TaxRRCOAAccountingType = 2 then 1
											    when TransactionType in (7) and sum(taxamount) &lt;= 0  then 1
												when TransactionType in (7) and sum(taxamount) &gt; 0  then 2
												else @TaxRRCOAAccountingType
									    end Accountingtype,
										@TaxRRCalcTypeTrigger,
										@TaxPercentage,
										@TaxDays
		   
							from Data_Sale
								INNER JOIN DATA_Transaction						on data_transaction.Saleid = Data_Sale.Saleid
								INNER JOIN DATA_TransactionTax					on data_transactiontax.transactionid = data_transaction.transactionid
								INNER JOIN CNF_Tax								on cnf_tax.taxid = DATA_TransactionTax.taxid
								INNER JOIN coa_cnf_account coa					on coa.coaaccountid = cnf_tax.coaaccountid


							where Data_Sale.paid = 1
								and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
								 OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
								  and data_transaction.transactionid in (select distinct transactionid
								                                           from data_payment
																		   where data_payment.paymentstatus = 1
																		)
							group by 			data_transaction.transactionid, 
												data_transaction.saleid,
												data_transaction.Siteid,
												data_transaction.OperatingAreaId,
												data_transaction.Workstationid,
												data_transaction.UserGroupid,
												data_transaction.UserId,
												Data_Transaction.TransactionDate,
												TransactionType,
												fTransactionDate


--Discount

						INSERT INTO [dbo].[RR_DATA_Revenue]
								([COAAccountId]
								,[RevenueRecognitionRuleId]
								,[RRCode]
								,[RRCalcTypeWhere]
								,[RRCalcTypeMethod]
								,[COAAccountConfigId]
								,[COAAccountType]
								,[COAAccountCode]
								,[TransactionId]
								,[SaleId]
								,[SiteId]
								,[OperatingAreaId]
								,[WorkstationId]
								,[UserGroupId]
								,[UserId]
								,[FCalcDate]
								,[FRevenueDate]
								,[Quantity]
								,[GrossAmount]
								,[NetAmount]
								,[Price]
								,[Percentage]
								,[RemaningValues]
								,[RevenueAmount]
								,[AccountingType]
								,[RRCalcTypeTrigger]
								,[RRPercentage]
								,[RRDays])

								select  @DiscountCOAAccountId,
										@DiscountRRRId,
										@DiscountRRRCode,
										@DiscountRRCalcTypeWhere,
										@DiscountRRCalcTypeMethod,
										@DiscountCOAAccountConfigId,
										@DiscountCOAAccountTypeId,
										@DiscountCOAAccountCode,
										data_transaction.transactionid, 
										data_transaction.saleid,
										data_transaction.Siteid,
										data_transaction.OperatingAreaId,
										data_transaction.Workstationid,
										data_transaction.UserGroupid,
										data_transaction.UserId,
										@BatchDate,
										CASE WHEN @RRTransDateType = 0 then data_transaction.fTransactionDate
											 else data_transaction.TransactionDate
										end TransactionDate,
										0,
										0,
										0,
										0,
										100,
										0,
										ABS(p.GLAmount) RevenueAmount,
										case    when data_transaction.TransactionType in (5, 8, 17, 18, 20, 22, 30) then 2
											    when data_transaction.TransactionType in (7) and (GLAmount) &lt;= 0  then 2
												when data_transaction.TransactionType in (7) and (GLAmount) &gt; 0  then 1
												else @DiscountRRCOAAccountingType
									    end Accountingtype,

										@DiscountRRCalcTypeTrigger,
										@DiscountPercentage,
										@DiscountDays
							FROM
							(
								SELECT distinct DATA_SaleItem.Saleitemid,
												DATA_Sale.saleid AS SAleid,
      											DATA_Transaction.TransactionType,
      											( SELECT top 1 transactionid
													FROM data_transaction		WITH (NOLOCK)
												   WHERE saleid = DATA_Sale.saleid
													AND transactiontype in (14, 16)
													AND paid = 1
												) AS tester,

												CASE WHEN DATA_Transaction.TransactionId IN (
																							  SELECT TR.TransactionID
																								FROM DATA_Transaction TR			WITH (NOLOCK)
																									LEFT JOIN DATA_Payment DP		WITH (NOLOCK) ON TR.TransactionId = DP.TransactionId
																							  WHERE TR.SaleId = DATA_Sale.SaleId
																								AND TR.Paid = 1
																								AND DP.PaymentStatus NOT IN (0, 2, 3)
																							)
      
															THEN DATA_Transaction.Transactionid
													 ELSE (
															  SELECT MIN(TR.TransactionID)
																FROM DATA_Transaction TR				WITH (NOLOCK)
																	LEFT JOIN DATA_Payment DP			WITH (NOLOCK) ON TR.TransactionId = DP.TransactionId
															   WHERE TR.SaleId = DATA_Sale.saleid
																 AND TR.TransactionType = 16
																 AND TR.Paid = 1
																 AND DP.PaymentStatus NOT IN (0, 2, 3)
														  )
												END Transactionid, 
												 CASE WHEN CNF_Promotion.PromotionType = 1 AND CNF_PromotionItemRule.NewProduct = 1 THEN  (CNF_MatrixCell.Price - SUM(DATA_SaleItemRule.DiscountAmount))
													  ELSE  CASE WHEN sum(1*data_saleItemRule.DiscountAmount) &lt; 0 AND transactiontype IN(20, 22, 30, 7, 5) AND
																																								(SELECT Count(*) 
																																								   FROM data_transaction WITH (NOLOCK)
																																								  WHERE saleid = data_sale.saleid
																																								 ) = 1 					  					  					  										  
																	  THEN Sum(1 * DATA_SaleItemRule.DiscountAmount)
																 WHEN sum(1*data_saleItemRule.DiscountAmount) &lt; 0 THEN	Sum(-1 * DATA_SaleItemRule.DiscountAmount)
																 WHEN sum(1*data_saleItemRule.DiscountAmount) &gt; 0 AND transactiontype IN(20, 22, 30, 7, 5) THEN Sum(-1 * DATA_SaleItemRule.DiscountAmount)		            	                  
																 ELSE sum(1*Data_SaleItemRule.DiscountAmount)
															END
												END AS GLAmount


								FROM dbo.DATA_SaleItemRule				WITH (NOLOCK)
									LEFT JOIN dbo.CNF_PromotionItemRule WITH (NOLOCK) ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
									LEFT JOIN dbo.CNF_PromotionItem		WITH (NOLOCK) ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
									LEFT JOIN dbo.CNF_Promotion			WITH (NOLOCK) ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId
									LEFT JOIN dbo.CNF_DmgCategory		WITH (NOLOCK) ON CNF_DmgCategory.DmgCategoryId = CNF_Promotion.DmgCategoryId
									LEFT JOIN dbo.DATA_SaleItem			WITH (NOLOCK) ON DATA_SaleItem.SaleItemId = DATA_SaleItemRule.SaleItemId
									LEFT JOIN dbo.DATA_Sale				WITH (NOLOCK) ON DATA_Sale.SaleID = DATA_SaleItem.SaleID
									LEFT JOIN DATA_TransactionItem		WITH (NOLOCK) ON DATA_TransactionItem.SaleItemId = DATA_SaleItem.SaleItemId 
									LEFT JOIN DATA_Transaction			WITH (NOLOCK) ON  DATA_Transaction.TransactionId = DATA_TransactionItem.TransactionId
									LEFT JOIN CNF_MatrixCell			WITH (NOLOCK) ON CNF_MatrixCell.MatrixCellId =  DATA_SaleItem.MatrixCellId

 
								WHERE DATA_Transaction.saleid in (
																	SELECT ff.saleid 
																	  FROM DATA_Transaction ff WITH (NOLOCK) 
																		LEFT JOIN Data_Payment WITH (NOLOCK) on (ff.Transactionid = Data_Payment.Transactionid) 
																	 WHERE  ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
																		OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
																	   AND DATA_PAyment.PaymentStatus NOT in (0,2,3) 
																	   AND (TransactionType not in (12)) 
																	   AND ff.PAid = 1
																 )  

								 AND DATA_Sale.Paid = 1
								 AND ((DATA_SaleItem.quantity &gt; 0) OR ((DATA_SaleItem.quantity &lt; 0) AND (transactiontype IN (20, 22, 30, 7, 5))))

         
								group BY DATA_SaleItem.Saleitemid,
										 DATA_Sale.saleid,
										 Data_transaction.Paid,
										 Data_Transaction.Transactionid,
										 Data_Transaction.fTransactionDate,
										 Data_Saleitem.Matrixcellid,
										 CNF_DmgCategory.DmgCategoryCode,
										 PromotionType,
										 CNF_PromotionItemRule.NewProduct,
										 CNF_MatrixCell.Price,
										 transactiontype,
										 CNF_DmgCategory.Description
							)p
								LEFT JOIN data_transaction WITH (NOLOCK) on data_transaction.transactionid = p.transactionid

							WHERE ((p.TransactionType &lt;&gt; 5) or (Tester is not null))
							  AND data_transaction.transactionid is not null


					
		--End Move Transactions to Suspend Account

		exec otn_sp_RR_RevenueData_OnDepositTrigger @BatchDate, @RRTransDateType

		exec otn_sp_RR_RevenueData_OnSaleTrigger @BatchDate, @RRTransDateType
		
		exec otn_sp_RR_RevenueData_OnMoneyCardLoad @BatchDate, @RRTransDateType

		exec otn_sp_RR_RevenueData_OnMoneyCardCashOut @BatchDate, @RRTransDateType

		exec otn_sp_RR_RevenueData_OnExternalMoneyCardCashOut @BatchDate, @RRTransDateType

		exec otn_sp_RR_RevenueData_OnExternalMoneyCardLoad @BatchDate, @RRTransDateType

	    exec otn_sp_RR_RevenueData_OnCreditWriteoff @BatchDate, @RRTransDateType

		exec otn_sp_RR_RevenueData_OnMoneyRefundTrigger @BatchDate, @RRTransDateType

		exec otn_sp_RR_RevenueData_OnAdvancedPaymentTrigger @BatchDate, @RRTransDateType
		
		exec otn_sp_RR_RevenueData_OnFlexContractPayment @BatchDate, @RRTransDateType

		----exec otn_sp_RR_RevenueData_OnCreditSettlementTrigger @BatchDate, @RRTransDateType
		
		exec otn_sp_RR_RevenueData_SettleUpSuspendAccount @BatchDate, @RRTransDateType

		exec otn_sp_RR_RevenueData_OnTicketExpiredTrigger @BatchDate, @RRTransDateType

	    exec otn_sp_RR_RevenueData_OnTicketUsageTrigger @BatchDate, @RRTransDateType

		exec otn_sp_RR_RevenueData_OnTimePeriodTrigger @BatchDate, @RRTransDateType

End

</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>kdixon</ADDEDBY>
			<SQLVERSION>2273</SQLVERSION>
			<RMTRACKLINK>64619</RMTRACKLINK>
			<REASON>Add new Column to Payment Methods</REASON>
			<TABLENAMES>CNF_PaymentMethod=PaymentMethodID</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'ReturnedCheckCOAAccountId' AND
                Object_ID  = Object_ID(N'CNF_PaymentMethod'))
BEGIN
	Alter Table CNF_PaymentMethod
	Add ReturnedCheckCOAAccountId Integer NULL
END
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (Select *
				from coa_cnf_account
				where code = N'DEFREVENUE')
BEGIN
	Update coa_cnf_account
	  set Systemaccount = 0
	  where code = N'DEFREVENUE'
END
</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>kdixon</ADDEDBY>
			<SQLVERSION>2272</SQLVERSION>
			<RMTRACKLINK>64619</RMTRACKLINK>
			<REASON>Default Rule for COA</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Declare @SUSPENSERULEID int 
Declare @SuspenseAccount int
Declare @PaymentMethodAccount int
Declare @TaxAccount int
Declare @DiscountsAccount int

select @SUSPENSERULEID = RevenueRecognitionRuleID 
from RR_CNF_RevenueRecognitionRule
where code = 'SUSPENSE'

select @SuspenseAccount = coaaccountid
from COA_CNF_Account
where code = 'SUSPENSE'

select @PaymentMethodAccount = coaaccountid
from COA_CNF_Account
where code = 'PYMTMETHOD'

select @TaxAccount = coaaccountid
from COA_CNF_Account
where code = 'TAXES'

select @DiscountsAccount = coaaccountid
from COA_CNF_Account
where code = 'DISCOUNTS'

IF ((@SUSPENSERULEID &gt; 0) and  (@SuspenseAccount &gt; 0)  and (@PaymentMethodAccount &gt;0) 
      and (@TaxAccount &gt; 0) and (@DiscountsAccount &gt; 0))
BEGIN
			IF NOT EXISTS (SELECT * FROM COA_CNF_AccountConfig
						   WHERE coaaccountid = @PaymentMethodAccount
							 and RevenueRecognitionRuleId = @SUSPENSERULEID)

			BEGIN

				INSERT INTO [dbo].[COA_CNF_AccountConfig]
						   ([COAAccountId]
						   ,[RevenueRecognitionRuleId]
						   ,[AccountingType]
						   ,[Price]
						   ,[Percentage]
						   ,[RemainingValues]
						   ,[Enabled]
						   ,[SiteId]
						   ,[DebitOriginalAccount])
					 VALUES
						   (@PaymentMethodAccount
						   ,@SUSPENSERULEID
						   ,1
						   ,0
						   ,100
						   ,0
						   ,1
						   ,null
						   ,1)

			END

			IF NOT EXISTS (SELECT * FROM COA_CNF_AccountConfig
						   WHERE coaaccountid = @DiscountsAccount
							 and RevenueRecognitionRuleId = @SUSPENSERULEID)

			BEGIN
				INSERT INTO [dbo].[COA_CNF_AccountConfig]
						   ([COAAccountId]
						   ,[RevenueRecognitionRuleId]
						   ,[AccountingType]
						   ,[Price]
						   ,[Percentage]
						   ,[RemainingValues]
						   ,[Enabled]
						   ,[SiteId]
						   ,[DebitOriginalAccount])
					 VALUES
						   (@DiscountsAccount
						   ,@SUSPENSERULEID
						   ,1
						   ,0
						   ,100
						   ,0
						   ,1
						   ,null
						   ,1)

			END

			IF NOT EXISTS (SELECT * FROM COA_CNF_AccountConfig
						   WHERE coaaccountid = @SuspenseAccount
							 and RevenueRecognitionRuleId = @SUSPENSERULEID)

			BEGIN
				INSERT INTO [dbo].[COA_CNF_AccountConfig]
						   ([COAAccountId]
						   ,[RevenueRecognitionRuleId]
						   ,[AccountingType]
						   ,[Price]
						   ,[Percentage]
						   ,[RemainingValues]
						   ,[Enabled]
						   ,[SiteId]
						   ,[DebitOriginalAccount])
					 VALUES
						   (@SuspenseAccount
						   ,@SUSPENSERULEID
						   ,2
						   ,0
						   ,100
						   ,0
						   ,1
						   ,null
						   ,1)

			END

			IF NOT EXISTS (SELECT * FROM COA_CNF_AccountConfig
						   WHERE coaaccountid = @TaxAccount
							 and RevenueRecognitionRuleId = @SUSPENSERULEID)

			BEGIN
				INSERT INTO [dbo].[COA_CNF_AccountConfig]
						   ([COAAccountId]
						   ,[RevenueRecognitionRuleId]
						   ,[AccountingType]
						   ,[Price]
						   ,[Percentage]
						   ,[RemainingValues]
						   ,[Enabled]
						   ,[SiteId]
						   ,[DebitOriginalAccount])
					 VALUES
						   (@TaxAccount
						   ,@SUSPENSERULEID
						   ,2
						   ,0
						   ,100
						   ,0
						   ,1
						   ,null
						   ,1)

			END

END


</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>kdixon</ADDEDBY>
			<SQLVERSION>2271</SQLVERSION>
			<RMTRACKLINK>64619</RMTRACKLINK>
			<REASON>Delete unused columns on coa_cnf_account</REASON>
			<TABLENAMES>coa_cnf_account=coaaccountid</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
               WHERE Name = N'FromDate' AND
               Object_ID = Object_ID(N'coa_cnf_account'))

BEGIN

	alter table coa_cnf_account
	drop column FromDate

END
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
               WHERE Name = N'ToDate' AND
               Object_ID = Object_ID(N'coa_cnf_account'))

BEGIN

	alter table coa_cnf_account
	drop column ToDate

END
</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>mkimball</ADDEDBY>
			<SQLVERSION>2270</SQLVERSION>
			<RMTRACKLINK>5711</RMTRACKLINK>
			<REASON>-drop CNF_Mask2CRMTemplate
-create CNF_DmgCategory2CRMTemplate
-clean up stored procedures</REASON>
			<TABLENAMES>CNF_DmgCategory2CRMTemplate=DmgCategory2CRMTemplateId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * 
             FROM INFORMATION_SCHEMA.TABLES 
            WHERE TABLE_SCHEMA = 'dbo' 
              AND  TABLE_NAME = 'CNF_Mask2CRMTemplate')
BEGIN
  DROP TABLE  CNF_Mask2CRMTemplate
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                WHERE TABLE_SCHEMA = 'dbo' 
                  AND  TABLE_NAME = 'CNF_DmgCategory2CRMTemplate')

BEGIN
Create table [CNF_DmgCategory2CRMTemplate]
(
	[DmgCategory2CRMTemplateId] Integer Identity(1,1) NOT NULL, UNIQUE ([DmgCategory2CRMTemplateId]),
	[DmgCategoryId] Integer NOT NULL,
	[CRMTemplateId] Integer NOT NULL,
	[CRMType] Smallint NULL,
Primary Key ([DmgCategory2CRMTemplateId]),
Constraint FK_CNF_DmgCategoryCNF_DmgCategory2CRMTemplate Foreign Key ([DmgCategoryId])
References CNF_DmgCategory([DmgCategoryId]),
Constraint FK_CNF_CRMTemplateCNF_DmgCategory2CRMTemplate Foreign Key ([CRMTemplateId])
References CNF_CRMTemplate([CRMTemplateId])
)
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * 
             FROM sys.objects 
            WHERE object_id = OBJECT_ID(N'otn_sp_ui_CNF_Mask2CRMTemplate_delete'))
BEGIN
  DROP PROCEDURE otn_sp_ui_CNF_Mask2CRMTemplate_delete
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * 
             FROM sys.objects 
            WHERE object_id = OBJECT_ID(N'otn_sp_ui_CNF_Mask2CRMTemplate_insert'))
BEGIN
  DROP PROCEDURE otn_sp_ui_CNF_Mask2CRMTemplate_insert
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * 
             FROM sys.objects 
            WHERE object_id = OBJECT_ID(N'otn_sp_ui_CNF_Mask2CRMTemplate_update'))
BEGIN
  DROP PROCEDURE otn_sp_ui_CNF_Mask2CRMTemplate_update
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>jlaguardia</ADDEDBY>
			<SQLVERSION>2269</SQLVERSION>
			<RMTRACKLINK>64619</RMTRACKLINK>
			<REASON>Added column to CNF_System
+ RRTransDateType as smallint not null default 0 for Revenue Recognition (if we need to remove a constraint, use Version 2260 patch 0 as a guide</REASON>
			<TABLENAMES>CNF_System=SystemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
               WHERE Name = N'RRTransDateType' AND
               Object_ID = Object_ID(N'CNF_System'))

BEGIN
   Alter table CNF_System
   add [RRTransDateType] smallint not null default 0;    
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>kdixon</ADDEDBY>
			<SQLVERSION>2268</SQLVERSION>
			<RMTRACKLINK>64619</RMTRACKLINK>
			<REASON>-change OperatingAreaID column to be nullable
-change WorkstationID column to be nullable
-change UserID column to be nullable
-change UserGroupID column to be nullable</REASON>
			<TABLENAMES>rr_data_revenue=RevenueRecognitionDataId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
               WHERE Name = N'OperatingAreaID' AND
               Object_ID = Object_ID(N'rr_data_revenue'))

BEGIN
   Alter table rr_data_revenue
   Alter Column OperatingAreaID int null;    
END
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
               WHERE Name = N'WorkstationID' AND
               Object_ID = Object_ID(N'rr_data_revenue'))

BEGIN
     Alter table rr_data_revenue
     Alter Column WorkstationID int null;  
END
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
               WHERE Name = N'UserID' AND
               Object_ID = Object_ID(N'rr_data_revenue'))

BEGIN
     Alter table rr_data_revenue
     Alter Column UserID int null;  
END
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
               WHERE Name = N'UserGroupID' AND
               Object_ID = Object_ID(N'rr_data_revenue'))

BEGIN
     Alter table rr_data_revenue
     Alter Column UserGroupID int null;  
END
</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fesposito</ADDEDBY>
			<SQLVERSION>2267</SQLVERSION>
			<RMTRACKLINK>5711</RMTRACKLINK>
			<REASON>-create DATA_Account2CRM
-add DATA_Account foreign key</REASON>
			<TABLENAMES>DATA_Account2CRM=Account2CRMId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT (EXISTS 
         (SELECT * 
            FROM INFORMATION_SCHEMA.TABLES 
           WHERE TABLE_SCHEMA = 'dbo' 
               AND  TABLE_NAME = 'DATA_Account2CRM'))

BEGIN

Create table [DATA_Account2CRM]
(
	[Account2CRMId] Integer Identity(1,1) NOT NULL,
	[AccountId] Integer NOT NULL,
	[CRMGuid] Varchar(38) NOT NULL,
	[CRMType] Smallint NOT NULL,
	[Changed] Smallint NULL,
Primary Key ([Account2CRMId])
) 

END
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'DATA_Account2CRM'
	          AND CONSTRAINT_NAME = N'fk_DATA_Account_AccountId')
BEGIN
  ALTER TABLE DATA_Account2CRM 
  ADD CONSTRAINT [fk_DATA_Account_AccountId] FOREIGN KEY([AccountId])
  REFERENCES [DATA_Account] ([AccountId])
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>mkimball</ADDEDBY>
			<SQLVERSION>2266</SQLVERSION>
			<RMTRACKLINK>57511</RMTRACKLINK>
			<REASON>--add IsSearchable to correct table (CNF_CRMTemplateDetail) and remove from CNF_CRMTemplate</REASON>
			<TABLENAMES>CNF_CRMTemplate=CRMTemplateId
CNF_CRMTemplateDetail=CRMTemplateDetailId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'IsSearchable' AND
                Object_ID  = Object_ID(N'CNF_CRMTemplate'))
BEGIN 
  ALTER TABLE CNF_CRMTemplate DROP COLUMN 
  	IsSearchable
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
               WHERE Name = N'IsSearchable' AND
               Object_ID = Object_ID(N'CNF_CRMTemplateDetail'))
BEGIN
  ALTER TABLE CNF_CRMTemplateDetail ADD IsSearchable Smallint NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>mkimball</ADDEDBY>
			<SQLVERSION>2265</SQLVERSION>
			<RMTRACKLINK>57511</RMTRACKLINK>
			<REASON>-- Get rid of CRMTemplateAK
-- Add column IsSearchable column (WRONG TABLE)</REASON>
			<TABLENAMES>CNF_CRMTemplate=CRMTemplateId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
            WHERE Name = N'CRMTemplateAK' AND
            Object_ID = Object_ID(N'CNF_CRMTemplate'))
BEGIN
  declare @cn nvarchar(256);
  declare @command nvarchar(1000);
  set @cn = (select Name from sys.key_constraints where parent_object_id = OBJECT_ID('CNF_CRMTemplate') and type = 'UQ');
  set @command = 'ALTER TABLE CNF_CRMTemplate drop constraint ' + @cn;
  execute(@command);
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'CRMTemplateAK' AND
                Object_ID  = Object_ID(N'CNF_CRMTemplate'))
BEGIN 
  ALTER TABLE CNF_CRMTemplate DROP COLUMN 
  	CRMTemplateAK
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
               WHERE Name = N'IsSearchable' AND
               Object_ID = Object_ID(N'CNF_CRMTemplate'))
BEGIN
  ALTER TABLE CNF_CRMTemplate ADD IsSearchable Smallint NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Federico Caramella</ADDEDBY>
			<SQLVERSION>2264</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>0 Delete Old Values
1 Add Field Target on CNF_ShopCartValidationItem2Event
2 Add Field Target on CNF_ShopCartValidationItem2MAtrixCell
3 Add Field Target on CNF_ShopCartValidationItem2StatisticalGroup</REASON>
			<TABLENAMES>CNF_ShopCartValidationItem2Event=ShopCartValidationItem2EventId
CNF_ShopCartValidationItem2MatrixCell=ShopCartValidationItem2MatrixCellId
CNF_ShopCartValidationItem2StatisticalGroup=ShopCartValidationItem2StatisticalGroupID</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
               WHERE Name = N'Target' AND
               Object_ID = Object_ID(N'CNF_ShopCartValidationItem2Event'))
BEGIN
  ALTER TABLE CNF_ShopCartValidationItem2Event ADD Target Smallint NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
               WHERE Name = N'Target' AND
               Object_ID = Object_ID(N'CNF_ShopCartValidationItem2MatrixCell'))
BEGIN
  ALTER TABLE CNF_ShopCartValidationItem2MatrixCell ADD Target Smallint NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
               WHERE Name = N'Target' AND
               Object_ID = Object_ID(N'CNF_ShopCartValidationItem2StatisticalGroup'))
BEGIN
  ALTER TABLE CNF_ShopCartValidationItem2StatisticalGroup ADD Target Smallint NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>kdixon</ADDEDBY>
			<SQLVERSION>2263</SQLVERSION>
			<RMTRACKLINK>64619</RMTRACKLINK>
			<REASON>Add new table RR_CNF_RevenueRecognitionRuleSchedule</REASON>
			<TABLENAMES>RR_CNF_RevenueRecognitionRuleSchedule=RevenueRecognitionRuleScheduleId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT (EXISTS 
         (SELECT * 
            FROM INFORMATION_SCHEMA.TABLES 
           WHERE TABLE_SCHEMA = 'dbo' 
               AND  TABLE_NAME = 'RR_CNF_RevenueRecognitionRuleSchedule'))

BEGIN

Create table [RR_CNF_RevenueRecognitionRuleSchedule]
(
        [RevenueRecognitionRuleScheduleId] Integer Identity(1,1) NOT NULL,
	[RevenueRecognitionRuleId] Integer NOT NULL,
	[PeriodOption] Smallint NULL,
	[ActiveSunday] Smallint NULL,
	[ActiveMonday] Smallint NULL,
	[ActiveTuesday] Smallint NULL,
	[ActiveWednesday] Smallint NULL,
	[ActiveThursday] Smallint NULL,
	[ActiveFriday] Smallint NULL,
	[ActiveSaturday] Smallint NULL,
	[LastDayOptionDay] Smallint NULL,
	[LastDayOptionWeek] Smallint NULL,
	[SpecificDay] Integer NULL,
	[WeekOption] Smallint NULL,
	[MonthOption] Smallint NULL,

Primary Key ([RevenueRecognitionRuleScheduleId])
) 

END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Federico Caramella</ADDEDBY>
			<SQLVERSION>2262</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>ALTER TABLE CNF_ShopcartValidationItem 

0 Delete Old Values
1 Add Field ShopCartValidationItemAK
2 Add Fields Phase_Add  Phase_Upsell  Phase_BeforeCheckout Phase_Checkout
3 Add Field DmgCategoryId
4 Add FK on DmgCategoryId</REASON>
			<TABLENAMES>CNF_ShopCartValidationItem=ShopCartValidationItemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>delete from CNF_ShopCartValidationItem2StatisticalGroup
delete from CNF_ShopCartValidationItem2Event
delete from CNF_ShopCartValidationItem2MatrixCell
delete from CNF_ShopCartValidationItem</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
               WHERE Name = N'ShopCartValidationItemAK' AND
               Object_ID = Object_ID(N'CNF_ShopCartValidationItem'))
BEGIN
  ALTER TABLE CNF_ShopCartValidationItem ADD ShopCartValidationItemAK NVarchar(32) NOT NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
               WHERE Name = N'Phase_Add' AND
               Object_ID = Object_ID(N'CNF_ShopCartValidationItem'))
BEGIN
  ALTER TABLE CNF_ShopCartValidationItem ADD Phase_Add Smallint NULL
  ALTER TABLE CNF_ShopCartValidationItem ADD Phase_Upsell Smallint NULL
  ALTER TABLE CNF_ShopCartValidationItem ADD Phase_BeforeCheckout Smallint NULL
  ALTER TABLE CNF_ShopCartValidationItem ADD Phase_Checkout Smallint NULL      
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
               WHERE Name = N'DmgCategoryId' AND
               Object_ID = Object_ID(N'CNF_ShopCartValidationItem'))
BEGIN
  ALTER TABLE CNF_ShopCartValidationItem ADD DmgCategoryId int NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_ShopCartValidationItem'
	          AND CONSTRAINT_NAME = N'fk_CNF_ShopCartValidationItem_DmgCategoryId')
BEGIN
  ALTER TABLE CNF_ShopCartValidationItem 
  ADD CONSTRAINT [fk_CNF_ShopCartValidationItem_DmgCategoryId] FOREIGN KEY([DmgCategoryId])
  REFERENCES [CNF_DmgCategory] ([DmgCategoryId])
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>mkimball</ADDEDBY>
			<SQLVERSION>2261</SQLVERSION>
			<RMTRACKLINK>57511</RMTRACKLINK>
			<REASON>--added CNF_Mask2CRMTemplate</REASON>
			<TABLENAMES>CNF_Mask2CRMTemplate=Mask2CRMTemplateId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT (EXISTS 
         (SELECT * 
            FROM INFORMATION_SCHEMA.TABLES 
           WHERE TABLE_SCHEMA = 'dbo' 
               AND  TABLE_NAME = 'CNF_Mask2CRMTemplate'))

BEGIN
Create table [CNF_Mask2CRMTemplate]
(
	[Mask2CRMTemplateId] Integer Identity(1,1) NOT NULL,
	[MaskId] Integer NOT NULL,
	[CRMTemplateId] Integer NOT NULL,
	[CRMType] Smallint NOT NULL,
Primary Key ([Mask2CRMTemplateId],[MaskId],[CRMTemplateId])
) 
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>jlaguardia</ADDEDBY>
			<SQLVERSION>2260</SQLVERSION>
			<RMTRACKLINK>69569</RMTRACKLINK>
			<REASON>Changed default constraint from 1 to 0 in  RES_CNF_MatrixCell</REASON>
			<TABLENAMES>RES_CNF_MatrixCell=MatrixCellId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT> IF EXISTS (SELECT * FROM sys.columns
            WHERE Name = N'UseQtyInSchedule' AND
            Object_ID = Object_ID(N'RES_CNF_MatrixCell'))
BEGIN
  declare @cn nvarchar(256);
  declare @command nvarchar(1000);
  set @cn = (select Name from sys.default_constraints where parent_object_id = OBJECT_ID('RES_CNF_MatrixCell'));
  set @command = 'ALTER TABLE RES_CNF_MatrixCell drop constraint ' + @cn;
  execute(@command);
  alter table RES_CNF_MatrixCell add constraint DF_RES_CNF_M_Default DEFAULT 0 for UseQtyInSchedule;
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fesposito</ADDEDBY>
			<SQLVERSION>2259</SQLVERSION>
			<RMTRACKLINK>57511</RMTRACKLINK>
			<REASON>-clean up stored procedures</REASON>
			<TABLENAMES>CNF_Mask=MaskId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (
SELECT * FROM sys.objects 
WHERE object_id = OBJECT_ID(N'otn_sp_ui_CNF_DataMask2Crm_insert')
)
BEGIN
drop procedure otn_sp_ui_CNF_DataMask2Crm_insert
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (
SELECT * FROM sys.objects 
WHERE object_id = OBJECT_ID(N'otn_sp_ui_CNF_DataMask2Crm_update')
)
BEGIN
drop procedure otn_sp_ui_CNF_DataMask2Crm_update
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (
SELECT * FROM sys.objects 
WHERE object_id = OBJECT_ID(N'otn_sp_ui_CNF_DataMask2Crm_delete')
)
BEGIN
drop procedure otn_sp_ui_CNF_DataMask2Crm_delete
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>kdixon</ADDEDBY>
			<SQLVERSION>2258</SQLVERSION>
			<RMTRACKLINK>64619</RMTRACKLINK>
			<REASON>Add new column to account cofig</REASON>
			<TABLENAMES>COA_CNF_AccountConfig=COAAccountConfigId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
               WHERE Name = N'DebitOriginalAccount' AND
               Object_ID = Object_ID(N'COA_CNF_AccountConfig'))
BEGIN
  ALTER TABLE COA_CNF_AccountConfig ADD DebitOriginalAccount Bit NULL
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>mkimball</ADDEDBY>
			<SQLVERSION>2257</SQLVERSION>
			<RMTRACKLINK>57511</RMTRACKLINK>
			<REASON>--Changed CNF_Mask -&gt; CNF_CRMTemplate relationship from 1:M to M:N by adding CNF_Mask2CRMTemplate and removing CRMTemplateId from CNF_Mask
--Dropped and recreated CNF_CRMTemplate to have CRMTemplateId  autoincrement
--Added CNF_CRMTemplateDetail table</REASON>
			<TABLENAMES>CNF_CRMTemplate=CRMTemplateId
CNF_CRMTemplateDetail=CRMTemplateDetailId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
            WHERE TABLE_NAME = N'CNF_Mask'
              AND CONSTRAINT_NAME = N'fkCNF_Mask_CNF_CRMTemplate_CRMTemplateId')          
BEGIN
  ALTER TABLE [CNF_Mask]
  DROP CONSTRAINT  fkCNF_Mask_CNF_CRMTemplate_CRMTemplateId
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'CRMTemplateId' AND
                Object_ID  = Object_ID(N'CNF_Mask'))
BEGIN 
  ALTER TABLE CNF_Mask DROP COLUMN 
  	CRMTemplateId
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'CNF_CRMTemplate'))

drop table  CNF_CRMTemplate</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT (EXISTS 
         (SELECT * 
            FROM INFORMATION_SCHEMA.TABLES 
           WHERE TABLE_SCHEMA = 'dbo' 
               AND  TABLE_NAME = 'CNF_CRMTemplate'))

BEGIN
Create table [CNF_CRMTemplate]
(
	[CRMTemplateId] Integer Identity(1,1) NOT NULL,
	[CRMTemplateAK] Varchar(32) NOT NULL, UNIQUE ([CRMTemplateAK]),
	[CRMTemplateName] Nvarchar(50) NOT NULL,
	[CRMDescription] Nvarchar(255) NULL,
	[CRMType] Smallint NOT NULL,
Primary Key ([CRMTemplateId])
)
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT (EXISTS 
         (SELECT * 
            FROM INFORMATION_SCHEMA.TABLES 
           WHERE TABLE_SCHEMA = 'dbo' 
               AND  TABLE_NAME = 'CNF_CRMTemplateDetail'))

BEGIN
Create table [CNF_CRMTemplateDetail]
(
	[CRMTemplateDetailId] Integer Identity(1,1) NOT NULL,
	[CRMTemplateId] Integer NOT NULL,
	[ObjType] Integer NOT NULL,
	[CRMFieldName] Varchar(255) NOT NULL,
Primary Key ([CRMTemplateDetailId])
)
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Damiani</ADDEDBY>
			<SQLVERSION>2256</SQLVERSION>
			<RMTRACKLINK>68586</RMTRACKLINK>
			<REASON>-- modify column CNF_Upsell.UpsellDescritpion to null</REASON>
			<TABLENAMES>CNF_UpSell=UpSellId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS(SELECT 1 FROM sys.columns 
          WHERE Name = N'UpSellDescription'
          AND Object_ID = Object_ID(N'CNF_UpSell'))
BEGIN


 ALTER TABLE CNF_UpSell ALTER COLUMN UpSellDescription NVARCHAR(50) NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AndreaDavanzo</ADDEDBY>
			<SQLVERSION>2255</SQLVERSION>
			<RMTRACKLINK>67102</RMTRACKLINK>
			<REASON>CNF_Promotion
[0] Column added MaxTicketsToApplyPromotion</REASON>
			<TABLENAMES>CNF_Promotion=PromotionId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
               WHERE Name = N'MaxTicketsToApplyPromotion' AND
               Object_ID = Object_ID(N'CNF_Promotion'))
BEGIN
  ALTER TABLE CNF_Promotion ADD MaxTicketsToApplyPromotion Integer NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>kdixon</ADDEDBY>
			<SQLVERSION>2254</SQLVERSION>
			<RMTRACKLINK>64619</RMTRACKLINK>
			<REASON>-- Change SUSPENSE code to SUSPEND</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (select * 
               from RR_CNF_RevenueRecognitionRule 
               where Code = 'SUSPEND')

BEGIN
   UPDATE RR_CNF_RevenueRecognitionRule   
      SET Code = 'SUSPENSE',      
          Description = 'Suspense Account'          
  where code = 'SUSPEND'
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (select * 
               from coa_cnf_account 
               where Code = 'SUSPEND')

BEGIN
   UPDATE coa_cnf_account   
      SET Code = 'SUSPENSE',      
          Description = 'Suspense Account',
          Name = 'Suspense'          
  where code = 'SUSPEND'
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>2253</SQLVERSION>
			<RMTRACKLINK>69614</RMTRACKLINK>
			<REASON>Table SIAE_SoccerLtaTask2PerfItem 
[0] - Add Fiield LastTransactionId int
[1] - Add Fiield DateTimeLastRun datetime


Table SIAE_DATA_SoccerLtaTaskItem
[2] - Add Fiield IsLast smallint 
[3] - Update table
[4] - Add not null

			</REASON>
			<TABLENAMES>SIAE_SoccerLtaTask2PerfItem=Task2PerfItemId
SIAE_DATA_SoccerLtaTaskItem=TaskItemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>
IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'LastTransactionId' AND
                Object_ID  = Object_ID(N'SIAE_SoccerLtaTask2PerfItem'))
BEGIN
  ALTER TABLE SIAE_SoccerLtaTask2PerfItem ADD LastTransactionId Integer NULL
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>

IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'DateTimeLastRun' AND
                Object_ID  = Object_ID(N'SIAE_SoccerLtaTask2PerfItem'))
BEGIN
  ALTER TABLE SIAE_SoccerLtaTask2PerfItem ADD DateTimeLastRun datetime NULL
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>

IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'IsLast' AND
                Object_ID  = Object_ID(N'SIAE_DATA_SoccerLtaTaskItem'))
BEGIN
  ALTER TABLE SIAE_DATA_SoccerLtaTaskItem ADD IsLast smallint NULL
END
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>

UPDATE SIAE_DATA_SoccerLtaTaskItem SET IsLast = 1

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>

 ALTER TABLE SIAE_DATA_SoccerLtaTaskItem ALTER COLUMN IsLast smallint NOT NULL

			</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>mkimball</ADDEDBY>
			<SQLVERSION>2252</SQLVERSION>
			<RMTRACKLINK>57511</RMTRACKLINK>
			<REASON>--Added CNF_CRMTemplate table
--Remove CrmIntegration column from CNF_Mask
--Remove CrmType column from CNF_Mask
--Dropped CNF_DataMask2Crm table
--Add CRMTemplateId foreign key to CNF_Mask</REASON>
			<TABLENAMES>CNF_CRMTemplate=CRMTemplateId
CNF_Mask=MaskId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT (EXISTS 
         (SELECT * 
            FROM INFORMATION_SCHEMA.TABLES 
           WHERE TABLE_SCHEMA = 'dbo' 
               AND  TABLE_NAME = 'CNF_CRMTemplate'))

BEGIN
Create table [CNF_CRMTemplate]
(
	[CRMTemplateId] Integer NOT NULL,
	[CRMTemplateAK] Varchar(32) NOT NULL, UNIQUE ([CRMTemplateAK]),
	[CRMTemplateName] Nvarchar(50) NOT NULL,
	[CRMType] Smallint NOT NULL,
	[CRMMapping] Varchar(4000) NOT NULL,
Primary Key ([CRMTemplateId])
)
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'CrmIntegration' AND
                Object_ID  = Object_ID(N'CNF_Mask'))
BEGIN 
  ALTER TABLE CNF_Mask DROP COLUMN 
  	CrmIntegration
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'CrmType' AND
                Object_ID  = Object_ID(N'CNF_Mask'))
BEGIN 
  ALTER TABLE CNF_Mask DROP COLUMN 
  	CrmType
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'CNF_DataMask2Crm'))

drop table  CNF_DataMask2Crm</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'CRMTemplateId' AND
                Object_ID  = Object_ID(N'CNF_Mask'))
BEGIN
  ALTER TABLE CNF_Mask ADD CRMTemplateId Integer NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_Mask'
	          AND CONSTRAINT_NAME = N'fkCNF_Mask_CNF_CRMTemplate_CRMTemplateId')          
BEGIN
  ALTER TABLE [CNF_Mask] WITH CHECK 
  ADD  CONSTRAINT [fkCNF_Mask_CNF_CRMTemplate_CRMTemplateId] FOREIGN KEY([CRMTemplateId])
  REFERENCES [CNF_CRMTemplate] ([CRMTemplateId])
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>kdixon</ADDEDBY>
			<SQLVERSION>2251</SQLVERSION>
			<RMTRACKLINK>64619</RMTRACKLINK>
			<REASON>--Add New FeeCOAAccountID column to 
--    CNF_PaymentMethod


Added Default Rule for Suspend 
			</REASON>
			<TABLENAMES>CNF_PaymentMethod=PaymentMethodID</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'FeeCOAAccountId' AND
                Object_ID  = Object_ID(N'CNF_PaymentMethod'))
BEGIN
	Alter Table CNF_PaymentMethod
	Add FeeCOAAccountId Integer NULL
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (select * 
               from RR_CNF_RevenueRecognitionRule 
               where Code = 'SUSPENSE')

BEGIN

	INSERT INTO [dbo].[RR_CNF_RevenueRecognitionRule]
			   ([RevenueRecognitionRuleAK]
			   ,[Code]
			   ,[Description]
			   ,[RRCalcTypeWhere]
			   ,[RRCalcTypeMethod]
			   ,[FromDate]
			   ,[ToDate]
			   ,[CreationDate]
			   ,[LastUpdate]
			   ,[Enabled]
			   ,[RRCalcTypeTrigger]
			   ,[Percentage]
			   ,[Days])
		 VALUES
			   (SUBSTRING(CONVERT(VARCHAR(36), NEWID()), 1, 32)
			   ,'SUSPENSE'
			   ,'Suspense Account'
			   ,1
			   ,1
			   ,'20180101'
			   ,'20450101'
			   ,Getdate()
			   ,Getdate()
			   ,1
			   ,1
			   ,0
			   ,0)
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>jlaguardia</ADDEDBY>
			<SQLVERSION>2250</SQLVERSION>
			<RMTRACKLINK>69989</RMTRACKLINK>
			<REASON>Added column to CNF_System
+ RRStartDate as DateTime/nullable for Revenue Recognition</REASON>
			<TABLENAMES>CNF_System=SystemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'RRStartDate' AND
                Object_ID  = Object_ID(N'CNF_System'))
BEGIN
  ALTER TABLE CNF_System ADD RRStartDate Datetime NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>2249</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>drop table:
[0]   ShopcartValidation2MatrixCell
[1]  ShopcartValidation2Event
[2]  ShopcartValidation2StatGroup

Creaetable:
[3]   ShopcartValidation2Event
[4]  ShopcartValidation2MatrixCell
[5]  ShopcartValidation2StatGroup

Create FK on Linked table
[6] ShopCartValidationItem2Event
[7] ShopCartValidationItem2MatrixCell
[8] ShopCartValidationItem2StatisticalGroup

Create FK on Primary Table
[9] ShopCartValidationItem2Event
[10] ShopCartValidationItem2MatrixCell
[11] ShopCartValidationItem2StatisticalGroup</REASON>
			<TABLENAMES>CNF_ShopCartValidationItem2Event=ShopCartValidationItem2EventId
CNF_ShopCartValidationItem2MatrixCell=ShopCartValidationItem2MatrixCellId
CNF_ShopCartValidationItem2StatisticalGroup=ShopCartValidationItem2StatisticalGroupID</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'CNF_ShopCartVaidationItem2MatrixCell'))
BEGIN                  
  DROP TABLE CNF_ShopCartVaidationItem2MatrixCell
END  
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'CNF_ShopCartVaidationItem2Event'))
BEGIN                  
  DROP TABLE CNF_ShopCartVaidationItem2Event
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'CNF_ShopCartVaidationItem2StatisticalGroup'))
BEGIN                  
  DROP TABLE CNF_ShopCartVaidationItem2StatisticalGroup
END </SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS ( SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND  TABLE_NAME = 'CNF_ShopCartValidationItem2Event' )

BEGIN
   CREATE TABLE CNF_ShopCartValidationItem2Event
  (
    ShopCartValidationItem2EventId Integer Identity(1,1) NOT NULL, UNIQUE ( ShopCartValidationItem2EventId ),
    ShopCartValidationItemId Integer NOT NULL,
    EventId Integer NOT NULL,
  PRIMARY KEY ( ShopCartValidationItem2EventId )
  ) 
END </SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS ( SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND  TABLE_NAME = 'CNF_ShopCartValidationItem2MatrixCell' )

BEGIN  
  CREATE TABLE CNF_ShopCartValidationItem2MatrixCell
  (
    ShopCartValidationItem2MatrixCellId Integer Identity(1,1) NOT NULL, UNIQUE ([ShopCartValidationItem2MatrixCellId]),
    ShopCartValidationItemId Integer NOT NULL,
    MatrixCellId Integer NOT NULL,
  PRIMARY KEY (ShopCartValidationItem2MatrixCellId)
  ) 
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS ( SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND  TABLE_NAME = 'CNF_ShopCartValidationItem2StatisticalGroup' )

BEGIN
  CREATE TABLE CNF_ShopCartValidationItem2StatisticalGroup
  (
    ShopCartValidationItem2StatisticalGroupId Integer Identity(1,1) NOT NULL, UNIQUE (ShopCartValidationItem2StatisticalGroupId),
    ShopCartValidationItemId Integer NOT NULL,
    StatisticalGroupId Integer NOT NULL,
  PRIMARY KEY (ShopCartValidationItem2StatisticalGroupId)
  )   
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_ShopCartValidationItem2Event'
	          AND CONSTRAINT_NAME = N'fk_CNF_ShopCartValidationItem2Event_ShopCartValidationItemId')          
BEGIN
  ALTER TABLE CNF_ShopCartValidationItem2Event WITH CHECK
  ADD CONSTRAINT [fk_CNF_ShopCartValidationItem2Event_ShopCartValidationItemId] FOREIGN KEY([ShopCartValidationItemId])
  REFERENCES [CNF_ShopCartValidationItem] ([ShopCartValidationItemId])
END </SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_ShopCartValidationItem2MatrixCell'
	          AND CONSTRAINT_NAME = N'fk_CNF_ShopCartValidationItem2MatrixCell_MatrixCellId')          
BEGIN
  ALTER TABLE CNF_ShopCartValidationItem2MatrixCell WITH CHECK
  ADD CONSTRAINT [fk_CNF_ShopCartValidationItem2MatrixCell_MatrixCellId] FOREIGN KEY([MatrixCellId])
  REFERENCES [CNF_MatrixCell] ([MatrixCellId])
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_ShopCartValidationItem2MatrixCell'
	          AND CONSTRAINT_NAME = N'fk_CNF_ShopCartValidationItem2MatrixCell_MatrixCellId')          
BEGIN
  ALTER TABLE CNF_ShopCartValidationItem2MatrixCell WITH CHECK
  ADD CONSTRAINT [fk_CNF_ShopCartValidationItem2MatrixCell_MatrixCellId] FOREIGN KEY([MatrixCellId])
  REFERENCES [CNF_MatrixCell] ([MatrixCellId])
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_ShopCartValidationItem2Event'
	          AND CONSTRAINT_NAME = N'fk_CNF_ShopCartValidationItem2Event_ShopCartValidationItemId')          
BEGIN
  ALTER TABLE CNF_ShopCartValidationItem2Event WITH CHECK
  ADD CONSTRAINT [fk_CNF_ShopCartValidationItem2Event_ShopCartValidationItemId] FOREIGN KEY([ShopCartValidationItemId])
  REFERENCES [CNF_ShopCartValidationItem] ([ShopCartValidationItemId])
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_ShopCartValidationItem2MatrixCell'
	          AND CONSTRAINT_NAME = N'fk_CNF_ShopCartValidationItem2MatrixCell_ShopCartValidationItemId')          
BEGIN
  ALTER TABLE CNF_ShopCartValidationItem2MatrixCell WITH CHECK
  ADD CONSTRAINT [fk_CNF_ShopCartValidationItem2MatrixCell_ShopCartValidationItemId] FOREIGN KEY([ShopCartValidationItemId])
  REFERENCES [CNF_ShopCartValidationItem] ([ShopCartValidationItemId])
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_ShopCartValidationItem2StatisticalGroup'
	          AND CONSTRAINT_NAME = N'fk_CNF_ShopCartValidationItem2StatisticalGroup_ShopCartValidationItemId')          
BEGIN
  ALTER TABLE CNF_ShopCartValidationItem2StatisticalGroup WITH CHECK
  ADD CONSTRAINT [fk_CNF_ShopCartValidationItem2StatisticalGroup_ShopCartValidationItemId] FOREIGN KEY([ShopCartValidationItemId])
  REFERENCES [CNF_ShopCartValidationItem] ([ShopCartValidationItemId])
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>kdixon</ADDEDBY>
			<SQLVERSION>2248</SQLVERSION>
			<RMTRACKLINK>64619</RMTRACKLINK>
			<REASON>Alter RR_Data_Revenue to null some columns

Add new Column to RR_Data_Revenue to identify debit or credit

			</REASON>
			<TABLENAMES>RR_DATA_Revenue=RevenueRecognitionDataId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'UnitAmount' AND
                Object_ID  = Object_ID(N'RR_DATA_Revenue'))
BEGIN
  ALTER TABLE RR_DATA_Revenue ALTER COLUMN UnitAmount Float NULL
END

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'UserGroupId' AND
                Object_ID  = Object_ID(N'RR_DATA_Revenue'))
BEGIN
  ALTER TABLE RR_DATA_Revenue ALTER COLUMN UserGroupId Int NULL
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Transactionid' AND
                Object_ID  = Object_ID(N'RR_DATA_Revenue'))
BEGIN
  ALTER TABLE RR_DATA_Revenue ALTER COLUMN Transactionid Int NULL
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'AccountingType' AND
                Object_ID  = Object_ID(N'RR_DATA_Revenue'))
BEGIN
  ALTER TABLE RR_DATA_Revenue ADD AccountingType Smallint NULL
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>jlaguardia</ADDEDBY>
			<SQLVERSION>2247</SQLVERSION>
			<RMTRACKLINK>65084</RMTRACKLINK>
			<REASON>Added 2 coilumns to DATA_PaymentHotel
[0] +added ResponseStatus varchar(255)
[1] +added ResponseText varchar(1000)</REASON>
			<TABLENAMES>DATA_PaymentHotel=PaymentId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'ResponseStatus' AND
                Object_ID  = Object_ID(N'DATA_PaymentHotel'))
BEGIN
  ALTER TABLE DATA_PaymentHotel ADD ResponseStatus varchar(255) NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'ResponseText' AND
                Object_ID  = Object_ID(N'DATA_PaymentHotel'))
BEGIN
  ALTER TABLE DATA_PaymentHotel ADD ResponseText varchar(1000) NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>2246</SQLVERSION>
			<RMTRACKLINK>61356</RMTRACKLINK>
			<REASON>Add fields on table DATA_Media2Performances
- FK TicketId int 
- FK TransactionId int 


			</REASON>
			<TABLENAMES>DATA_Media2Performances=Media2PerformancesId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'TicketId' AND
                Object_ID  = Object_ID(N'DATA_Media2Performances'))
BEGIN
  ALTER TABLE DATA_Media2Performances ADD TicketId Integer NULL
END

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'TransactionId' AND
                Object_ID  = Object_ID(N'DATA_Media2Performances'))
BEGIN
  ALTER TABLE DATA_Media2Performances ADD TransactionId Integer NULL
END

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> 
IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'DATA_Media2Performances'
	          AND CONSTRAINT_NAME = N'fkDATA_Media2Performances_DATA_Ticket_TicketId')          
BEGIN
  ALTER TABLE [DATA_Media2Performances] WITH CHECK 
  ADD  CONSTRAINT [fkDATA_Media2Performances_DATA_Ticket_TicketId] FOREIGN KEY([TicketId])
  REFERENCES [DATA_Ticket] ([TicketId])
END

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> 
IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'DATA_Media2Performances'
	          AND CONSTRAINT_NAME = N'fkDATA_Media2Performances_DATA_Transaction_TransactionId')          
BEGIN
  ALTER TABLE [DATA_Media2Performances] WITH CHECK 
  ADD  CONSTRAINT [fkDATA_Media2Performances_DATA_Transaction_TransactionId] FOREIGN KEY([TransactionId])
  REFERENCES [DATA_Transaction] ([TransactionId])
END

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>jlaguardia</ADDEDBY>
			<SQLVERSION>2245</SQLVERSION>
			<RMTRACKLINK>65084</RMTRACKLINK>
			<REASON>Added Table DATA_PaymentHotel
[0] Drop table
[1] Added table
[2] Added foreign key to link DATA_PaymentHotel and DATA_Payment</REASON>
			<TABLENAMES>DATA_PaymentHotel=PaymentId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'DATA_PaymentHotel')

BEGIN
  drop table DATA_PaymentHotel
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'DATA_PaymentHotel')

BEGIN
Create table DATA_PaymentHotel
(
	PaymentId Integer NOT NULL,
	RawRequest Nvarchar(1000),
	RawAnswer Nvarchar(1000),
	ReferenceId Integer,
	SequenceNumber Integer,
  Primary Key ([PaymentId])
)
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'DATA_PaymentHotel'
	          AND CONSTRAINT_NAME = N'fk_DATA_PaymentHotel_PaymentId')          
BEGIN
  ALTER TABLE [DATA_PaymentHotel] WITH CHECK 
  ADD  CONSTRAINT [fk_DATA_PaymentHotel_PaymentId] FOREIGN KEY([PaymentId])
  REFERENCES [DATA_Payment] ([PaymentId])
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>dapicella</ADDEDBY>
			<SQLVERSION>2244</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>missing patch</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>dapicella</ADDEDBY>
			<SQLVERSION>2243</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>missing patch</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>2242</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>Change filed name form Allowed to Allow</REASON>
			<TABLENAMES>CNF_ShopCartValidation_Permission=ShopCartValidationPermissionID</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
               WHERE Name = N'Allowed' AND
               Object_ID = Object_ID(N'CNF_ShopCartValidation_Permission'))
BEGIN
  ALTER TABLE CNF_ShopCartValidation_Permission ADD Allow SmallInt NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
               WHERE Name = N'Allowed' AND
               Object_ID = Object_ID(N'CNF_ShopCartValidation_Permission'))
BEGIN
  UPDATE CNF_ShopCartValidation_Permission
    SET Allow = Allowed
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
               WHERE Name = N'Allow' AND
               Object_ID = Object_ID(N'CNF_ShopCartValidation_Permission'))
BEGIN
  ALTER TABLE CNF_ShopCartValidation_Permission
    ALTER COLUMN Allow smallint NOT NULL
END 
</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
               WHERE Name = N'Allowed' AND
               Object_ID = Object_ID(N'CNF_ShopCartValidation_Permission'))
BEGIN
  ALTER TABLE CNF_ShopCartValidation_Permission
    DROP COLUMN Allowed 
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>2241</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>Add New Shop Cart Validation Feature

0 Add Table CNF_ShopCartValidation
1 Add table CNF_ShopCartVaidationItem
2 Add FK between the two table
3 Add table CNF_ShopCartValidation_Permission
4 Add FK on ShopCartValidation
5 Add FK on Workstation
6 Add FK on Site
7 Add FK on OperatingArea
8 Add FK on UserGroup
9 Add FK on User
10 Add new table CNF_ShopCartVaidationItem2Event
11 add FK on ShopCartValidationItem
12 add FK on Event
13 create table CNF_ShopCartVaidationItem2MatrixCell
14 add FK on ShopCartValidationItemId
15 add FK on MatrixCellId
16 Add table CNF_ShopCartVaidationItem2StatisticalGroup
17 Add FK on ShopCartValidationItemId
18 Add FK on StatisticalGroupId




			</REASON>
			<TABLENAMES>CNF_ShopCartValidation=ShopCartValidationId
CNF_ShopCartValidationItem=ShopCartValidationItemId
CNF_ShopCartValidation_Permission=ShopCartValidationPermissionID
CNF_ShopCartVaidationItem2Event=ShopCartVaidationItem2EventId
CNF_ShopCartVaidationItem2MatrixCell=ShopCartVaidationItem2MatrixCellId
CNF_ShopCartVaidationItem2StatisticalGroup=ShopCartVaidationItem2StatisticalGroupID</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS ( SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND  TABLE_NAME = 'CNF_ShopCartValidation' )

BEGIN
  CREATE TABLE CNF_ShopCartValidation
  (
    ShopCartValidationId Integer Identity(1,1) NOT NULL, UNIQUE ([ShopCartValidationId]),
    ShopCartValidationAK Nvarchar(32) NOT NULL,
    ShopCartValidationCode Nvarchar(10) NOT NULL,
    ShopCartValidationName Nvarchar(50) NOT NULL,
    ShopCartValidationDescription Nvarchar(50) NULL,
    Enabled Smallint NOT NULL,
  PRIMARY KEY ([ShopCartValidationId])
  )
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS ( SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND  TABLE_NAME = 'CNF_ShopCartValidationItem' )

BEGIN
  CREATE TABLE CNF_ShopCartValidationItem
  (
	ShopCartValidationItemId Integer Identity(1,1) NOT NULL, UNIQUE ([ShopCartValidationItemId]),
	ShopCartValidationId Integer NOT NULL,
	MinQty Integer NOT NULL,
	MaxQty Integer NOT NULL,
	ValidationType Smallint NOT NULL,
  PRIMARY KEY ([ShopCartValidationItemId])
  ) 
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_ShopCartValidationItem'
	          AND CONSTRAINT_NAME = N'fk_CNF_ShopCartValidationItem_ShopCartValidationId')          
BEGIN
  ALTER TABLE CNF_ShopCartValidationItem 
  ADD CONSTRAINT [fk_CNF_ShopCartValidationItem_ShopCartValidationId] FOREIGN KEY([ShopCartValidationId])
  REFERENCES [CNF_ShopCartValidation] ([ShopCartValidationId])
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS ( SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND  TABLE_NAME = 'CNF_ShopCartValidation_Permission' )

BEGIN
  CREATE TABLE CNF_ShopCartValidation_Permission
  (
      ShopCartValidationPermissionID Integer Identity(1,1) NOT NULL, UNIQUE ([ShopCartValidationPermissionID]),
      ShopCartValidationId Integer NOT NULL,
      UserGroupId Integer NULL,
      UserId Integer NULL,
      SiteId Integer NULL,
      OperatingAreaId Integer NULL,
      WorkstationId Integer NULL,
      Allowed Smallint NOT NULL,
  PRIMARY KEY ([ShopCartValidationPermissionID])
  ) 
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_ShopCartValidation_Permission'
	          AND CONSTRAINT_NAME = N'fk_CNF_ShopCartValidation_Permission_ShopCartValidationId')          
BEGIN
  ALTER TABLE CNF_ShopCartValidation_Permission
  ADD CONSTRAINT [fk_CNF_ShopCartValidation_Permission_ShopCartValidationId] FOREIGN KEY([ShopCartValidationId])
  REFERENCES [CNF_ShopCartValidation] ([ShopCartValidationId])
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_ShopCartValidation_Permission'
	          AND CONSTRAINT_NAME = N'fk_CNF_ShopCartValidation_Permission_WorkstationId')          
BEGIN
  ALTER TABLE CNF_ShopCartValidation_Permission WITH CHECK
  ADD CONSTRAINT [fk_CNF_ShopCartValidation_Permission_WorkstationId] FOREIGN KEY([WorkstationId])
  REFERENCES [CNF_Workstation] ([WorkstationId])
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_ShopCartValidation_Permission'
	          AND CONSTRAINT_NAME = N'fk_CNF_ShopCartValidation_Permission_SiteId')          
BEGIN
  ALTER TABLE CNF_ShopCartValidation_Permission WITH CHECK
  ADD CONSTRAINT [fk_CNF_ShopCartValidation_Permission_SiteId] FOREIGN KEY([SiteId])
  REFERENCES [CNF_Site] ([SiteId])
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_ShopCartValidation_Permission'
	          AND CONSTRAINT_NAME = N'fk_CNF_ShopCartValidation_Permission_OperatingAreaId')          
BEGIN
  ALTER TABLE CNF_ShopCartValidation_Permission WITH CHECK
  ADD CONSTRAINT [fk_CNF_ShopCartValidation_Permission_OperatingAreaId] FOREIGN KEY([OperatingAreaId])
  REFERENCES [CNF_OperatingArea] ([OperatingAreaId])
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_ShopCartValidation_Permission'
	          AND CONSTRAINT_NAME = N'fk_CNF_ShopCartValidation_Permission_UserGroupId')          
BEGIN
  ALTER TABLE CNF_ShopCartValidation_Permission WITH CHECK
  ADD CONSTRAINT [fk_CNF_ShopCartValidation_Permission_UserGroupId] FOREIGN KEY([UserGroupId])
  REFERENCES [CNF_UserGroup] ([UserGroupId])
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_ShopCartValidation_Permission'
	          AND CONSTRAINT_NAME = N'fk_CNF_ShopCartValidation_Permission_UserGroupId')          
BEGIN
  ALTER TABLE CNF_ShopCartValidation_Permission WITH CHECK
  ADD CONSTRAINT [fk_CNF_ShopCartValidation_Permission_UserId] FOREIGN KEY([UserId])
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS ( SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND  TABLE_NAME = 'CNF_ShopCartVaidationItem2Event' )

BEGIN
   CREATE TABLE CNF_ShopCartVaidationItem2Event
  (
      ShopCartVaidationItem2EventId Integer Identity(1,1) NOT NULL, UNIQUE ( ShopCartVaidationItem2EventId ),
      ShopCartValidationItemId Integer NOT NULL,
      EventId Integer NOT NULL,
  PRIMARY KEY ( ShopCartVaidationItem2EventId )
  ) 
END </SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_ShopCartVaidationItem2Event'
	          AND CONSTRAINT_NAME = N'fk_CNF_ShopCartVaidationItem2Event_ShopCartValidationItemId')          
BEGIN
  ALTER TABLE CNF_ShopCartVaidationItem2Event WITH CHECK
  ADD CONSTRAINT [fk_CNF_ShopCartVaidationItem2Event_ShopCartValidationItemId] FOREIGN KEY([ShopCartValidationItemId])
  REFERENCES [CNF_ShopCartValidationItem] ([ShopCartValidationItemId])
END


				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_ShopCartVaidationItem2Event'
	          AND CONSTRAINT_NAME = N'fk_CNF_ShopCartVaidationItem2Event_EventId')          
BEGIN
  ALTER TABLE CNF_ShopCartVaidationItem2Event WITH CHECK
  ADD CONSTRAINT [fk_CNF_ShopCartVaidationItem2Event_EventId] FOREIGN KEY([EventId])
  REFERENCES [CNF_Event] ([EventId])
END 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS ( SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND  TABLE_NAME = 'CNF_ShopCartVaidationItem2MatrixCell' )

BEGIN
   CREATE TABLE CNF_ShopCartVaidationItem2MatrixCell
  (
      ShopCartVaidationItem2MatrixCellId Integer Identity(1,1) NOT NULL, UNIQUE ([ShopCartVaidationItem2MatrixCellId]),
      ShopCartValidationItemId Integer NOT NULL,
      MatrixCellId Integer NOT NULL,
  PRIMARY KEY (ShopCartVaidationItem2MatrixCellId)
  ) 
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_ShopCartVaidationItem2MatrixCell'
	          AND CONSTRAINT_NAME = N'fk_CNF_ShopCartVaidationItem2MatrixCell_ShopCartValidationItemId')          
BEGIN
  ALTER TABLE CNF_ShopCartVaidationItem2MatrixCell WITH CHECK
  ADD CONSTRAINT [fk_CNF_ShopCartVaidationItem2MatrixCell_ShopCartValidationItemId] FOREIGN KEY([ShopCartValidationItemId])
  REFERENCES [CNF_ShopCartValidationItem] ([ShopCartValidationItemId])
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_ShopCartVaidationItem2MatrixCell'
	          AND CONSTRAINT_NAME = N'fk_CNF_ShopCartVaidationItem2MatrixCell_MatrixCellId')          
BEGIN
  ALTER TABLE CNF_ShopCartVaidationItem2MatrixCell WITH CHECK
  ADD CONSTRAINT [fk_CNF_ShopCartVaidationItem2MatrixCell_MatrixCellId] FOREIGN KEY([MatrixCellId])
  REFERENCES [CNF_MatrixCell] ([MatrixCellId])
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS ( SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
               AND  TABLE_NAME = 'CNF_ShopCartVaidationItem2StatisticalGroup' )

BEGIN
  CREATE TABLE CNF_ShopCartVaidationItem2StatisticalGroup
  (
      ShopCartVaidationItem2StatisticalGroupId Integer Identity(1,1) NOT NULL, UNIQUE ( ShopCartVaidationItem2StatisticalGroupId ),
      ShopCartValidationItemId Integer NOT NULL,
      StatisticalGroupId Integer NOT NULL,
  PRIMARY KEY ( ShopCartVaidationItem2StatisticalGroupId )
  ) 
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_ShopCartVaidationItem2StatisticalGroup'
	          AND CONSTRAINT_NAME = N'fk_CNF_ShopCartVaidationItem2StatisticalGroup_ShopCartValidationItemId')          
BEGIN
  ALTER TABLE CNF_ShopCartVaidationItem2StatisticalGroup WITH CHECK
  ADD CONSTRAINT [fk_CNF_ShopCartVaidationItem2StatisticalGroup_ShopCartValidationItemId] FOREIGN KEY([ShopCartValidationItemId])
  REFERENCES [CNF_ShopCartValidationItem] ([ShopCartValidationItemId])
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_ShopCartVaidationItem2StatisticalGroup'
	          AND CONSTRAINT_NAME = N'fk_CNF_ShopCartVaidationItem2StatisticalGroup_StatisticalGroupId')          
BEGIN
  ALTER TABLE CNF_ShopCartVaidationItem2StatisticalGroup WITH CHECK
  ADD CONSTRAINT [fk_CNF_ShopCartVaidationItem2StatisticalGroup_StatisticalGroupId] FOREIGN KEY([StatisticalGroupId])
  REFERENCES [CNF_StatisticalGroup] ([StatisticalGroupId])
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>2240</SQLVERSION>
			<RMTRACKLINK>66121</RMTRACKLINK>
			<REASON>Add field DateTimeLastRun on table SIAE_SoccerLtaTask2PerfItem</REASON>
			<TABLENAMES>SIAE_SoccerLtaTask2PerfItem=Task2PerfItemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'DateTimeLastRun' AND
                Object_ID  = Object_ID(N'SIAE_SoccerLtaTask2PerfItem'))
BEGIN
  ALTER TABLE SIAE_SoccerLtaTask2PerfItem ADD DateTimeLastRun datetime NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>kdixon</ADDEDBY>
			<SQLVERSION>2239</SQLVERSION>
			<RMTRACKLINK>69622 </RMTRACKLINK>
			<REASON>Chaange length of column doctemplatename in cnf_doctemplate table.
			</REASON>
			<TABLENAMES>CNF_Doctemplate=DocTemplateId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
            WHERE Name = N'DocTemplateName' AND
            Object_ID  = Object_ID(N'CNF_Doctemplate'))
BEGIN
  ALTER TABLE CNF_Doctemplate ALTER COLUMN DocTemplateName nvarchar(100) NOT NULL
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AndreaDavanzo</ADDEDBY>
			<SQLVERSION>2238</SQLVERSION>
			<RMTRACKLINK>68045</RMTRACKLINK>
			<REASON>Added column Active to the CNF_PromotionItemRule
[0] Add Column</REASON>
			<TABLENAMES>CNF_PromotionItemRule=PromotionItemRuleId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Active' AND
                Object_ID  = Object_ID(N'CNF_PromotionItemRule'))
BEGIN
  ALTER TABLE CNF_PromotionItemRule ADD Active smallint NOT NULL default 1
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Damiani</ADDEDBY>
			<SQLVERSION>2237</SQLVERSION>
			<RMTRACKLINK>69330</RMTRACKLINK>
			<REASON>// Updte all UpSellType in CNF_UpSell. The UpSelltype = 2 is not still used and avoided from BOS so all UpSelltype becomes =1
			</REASON>
			<TABLENAMES>CNF_UpSell=UpSellId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>UPDATE CNF_UPSell SET UpSellType = 1</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>dapicella</ADDEDBY>
			<SQLVERSION>2236</SQLVERSION>
			<RMTRACKLINK>67125</RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF OBJECT_ID('ExportTransactionPayments', 'V') IS NOT NULL
    DROP VIEW ExportTransactionPayments</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE VIEW [dbo].[ExportTransactionPayments] AS 

	SELECT 
		SI.SiteCode, 
		TR.TransactionAk,
		TR.SaleId,  
		PAY.PaymentId, 
		PAY.FPaymentDate, 
		WS.WorkstationAK, 
		US.UserCode, 
		OP.AreaCode, 
		LkTRType.Description as TransactionTypeDesc, 
		PM.Description as PaymentMethodDesc, 
		CNFPAYC.CCName, 
		PAYC.AuthorizationCode, 
		PAYC.DevResponseCode, 
		PAY.PaymentAmount, 
		TR.Revenue as TransactionAmount,
		CASE
			WHEN PAYCR.PaymentId &gt; 0
				THEN 'TRUE'
			ELSE
				'FALSE'
		END as CREDIT, 
		TR.TransactionId, 
		TR.Completed, 
		TR.Encoded, 
		TR.Items, 
		TR.TransactionType, 
		PAY.PaymentType, 
		LkPAYType.Description as PaymentTypeDesc, 
		CUR.ISOCode, 
		PAY.ExchangeRate, 
		AC.AccountId, 
		AC.AccountAk,
		DMGAC.DmgCategoryCode AccountDMG, 
		V.VoucherCode, 
		RES.ReservationAK, 
		RES_AC.AccountId RES_AccountId, 
		RES_AC.AccountAk RES_AccountAk,
		RES_DMGAC.DmgCategoryCode RES_AccountDMG, 
		DEBT.PaymentId DEBT_ID, 
		DEBT_RES.ReservationAK DEBT_ReservationAK, 
		DEBT_V.VoucherCode DEBT_VoucherCode, 
		DEBT_AC.AccountId DEBT_AccountId, 
		DEBT_AC.AccountAk DEBT_AccountAk,
		DEBT_DMGAC.DmgCategoryCode DEBT_AccountDMG,  
		V_AC.AccountId V_AccountId, 
		V_AC.AccountAk V_AccountAk,
		V_DMGAC.DmgCategoryCode V_AccountDMG,
		TR.FTransactionDate, 
		TR.SiteId
	FROM 
		DATA_Payment PAY With(NoLock) 
		INNER JOIN DATA_Transaction TR With(NoLock) ON TR.TransactionId = PAY.TransactionId 
		INNER JOIN CNF_PaymentMethod PM With(NoLock) ON PAY.PaymentMethodId = PM.PaymentMethodId 
		INNER JOIN CNF_Workstation WS With(NoLock) ON TR.WorkstationId = WS.WorkstationId 
		INNER JOIN CNF_User US With(NoLock) ON TR.UserId = US.UserId 
		INNER JOIN CNF_OperatingArea OP With(NoLock) ON TR.OperatingAreaId = OP.OperatingAreaId 
		INNER JOIN CNF_Site SI With(NoLock) ON TR.SiteId = SI.SiteId 
		INNER JOIN CNF_LookUp LkTRType With(NoLock) ON TR.TransactionType = LkTRType.ItemId 
														AND LkTRType.LookUpTableId = 3
		INNER JOIN CNF_LookUp LkPAYType With(NoLock) ON PAY.PaymentType = LkPAYType.ItemId 
														AND LkPAYType.LookUpTableId = 7
		LEFT OUTER JOIN DATA_PaymentCard PAYC With(NoLock) ON PAY.PaymentId = PAYC.PaymentId 
		LEFT OUTER JOIN CNF_PaymentCard CNFPAYC With(NoLock) ON PAYC.PaymentCardId = CNFPAYC.PaymentCardId 
		LEFT OUTER JOIN DATA_PaymentCredit PAYCR With(NoLock) ON PAY.PaymentId = PAYCR.PaymentId 
		LEFT OUTER JOIN DATA_Account AC With(NoLock) ON PAYCR.AccountId = AC.AccountId
		left outer join CNF_DmgCategory DMGAC With(NoLock) ON DMGAC.DmgCategoryId = AC.DmgCategoryId 
		LEFT OUTER JOIN DATA_Voucher V With(NoLock) ON PAYCR.EntityId = V.VoucherId 
														AND PAYCR.EntityTable = 186
		LEFT OUTER JOIN DATA_Account V_AC With(NoLock) ON V.AccountId = V_AC.AccountId
		LEFT OUTER JOIN CNF_DmgCategory V_DMGAC With(NoLock) ON V_DMGAC.DmgCategoryId = V_AC.DmgCategoryId  
		LEFT OUTER JOIN DATA_Reservation RES With(NoLock) ON TR.SaleId = RES.SaleId 
		LEFT OUTER JOIN DATA_Account RES_AC With(NoLock) ON RES.AccountId = RES_AC.AccountId
		LEFT OUTER JOIN CNF_DmgCategory RES_DMGAC With(NoLock) ON RES_DMGAC.DmgCategoryId = RES_AC.DmgCategoryId 
		LEFT OUTER JOIN DATA_PaymentCredit DEBT With(NoLock) ON PAY.TransactionId = DEBT.SettleTransactionId 
		LEFT OUTER JOIN DATA_Account DEBT_AC With(NoLock) ON DEBT.AccountId = DEBT_AC.AccountId
		LEFT OUTER JOIN CNF_DmgCategory DEBT_DMGAC With(NoLock) ON DEBT_DMGAC.DmgCategoryId = DEBT_AC.DmgCategoryId  
		LEFT OUTER JOIN DATA_Voucher DEBT_V With(NoLock) ON DEBT.EntityId = DEBT_V.VoucherId 
															AND DEBT.EntityTable = 186
		LEFT OUTER JOIN DATA_Payment DEBT_PAY With(NoLock) ON DEBT.PaymentId = DEBT_PAY.PaymentId 
		LEFT OUTER JOIN DATA_Transaction DEBT_TR With(NoLock) ON DEBT_PAY.TransactionId = DEBT_TR.TransactionId 
		LEFT OUTER JOIN DATA_Reservation DEBT_RES With(NoLock) ON DEBT_TR.SaleId = DEBT_RES.SaleId 
		INNER JOIN CNF_Currency CUR With(NoLock) ON PAY.CurrencyId = CUR.CurrencyId 
	WHERE 
		(DEBT_TR.TransactionType &lt;&gt; 22 OR DEBT_TR.TransactionType IS NULL)	--Lk_TransactionType_VoidTransaction
		AND PAY.PaymentStatus = 1	--Lk_PaymentStatus_Approved</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>dapicella</ADDEDBY>
			<SQLVERSION>2235</SQLVERSION>
			<RMTRACKLINK>67125</RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>ecandido</ADDEDBY>
			<SQLVERSION>2234</SQLVERSION>
			<RMTRACKLINK>69455</RMTRACKLINK>
			<REASON>Enlarge the Descriptiln field for "Dynamic offer", "Coupon" and "Fee" from 30 to 50</REASON>
			<TABLENAMES>CNF_Promotion=PromotionId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>  IF EXISTS (SELECT * FROM sys.columns
            WHERE Name = N'Description' AND
            Object_ID  = Object_ID(N'CNF_Promotion'))
BEGIN
  ALTER TABLE CNF_Promotion ALTER COLUMN [Description] nvarchar(50) NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>jlaguardia</ADDEDBY>
			<SQLVERSION>2233</SQLVERSION>
			<RMTRACKLINK>68736</RMTRACKLINK>
			<REASON>Added Column to DATA_SaleItem
+UpSellMatrixCellId smallint NULL
  *This is an enhancement for UpSell to keep track of the original MatrixCellId before the upsell product. (This is not retroactive - if an upsell MCid is linked to another upsell MCid, this value will be the the latter MCid and not the former)</REASON>
			<TABLENAMES>DATA_SaleItem=SaleItemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'UpSellMatrixCellId' AND 
                Object_ID  = Object_ID(N'DATA_SaleItem'))
BEGIN
  ALTER TABLE DATA_SaleItem
  ADD [UpSellMatrixCellId] smallint NULL; 
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>kdixon</ADDEDBY>
			<SQLVERSION>2232</SQLVERSION>
			<RMTRACKLINK>64619</RMTRACKLINK>
			<REASON>--Add New COAAccountID column to 
--    CNF_PaymentMethod
--   CNF_PaymentCard
--   CNF_Tax
--   CNF_Promotion

--Add New Column MatrixSheetID to 
--   RR_Data_Revenue


--Change the following columns in RR_Data_Revenue to null
--  SaleItemid 
--  MatrixCellid 
--  TransactionId
--  SaleId</REASON>
			<TABLENAMES>CNF_PaymentMethod=PaymentMethodID
CNF_PaymentCard=PaymentCardId
CNF_Tax=TaxID
CNF_Promotion=PromotionId
RR_DATA_Revenue=RevenueRecognitionDataId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'COAAccountId' AND
                Object_ID  = Object_ID(N'CNF_PaymentMethod'))
BEGIN
	Alter Table CNF_PaymentMethod
	Add COAAccountId Integer NULL
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'COAAccountId' AND
                Object_ID  = Object_ID(N'CNF_PaymentCard'))
BEGIN
	Alter Table CNF_PaymentCard
	Add COAAccountId Integer NULL
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'COAAccountId' AND
                Object_ID  = Object_ID(N'CNF_Tax'))
BEGIN
	Alter Table CNF_Tax
	Add COAAccountId Integer NULL
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'COAAccountId' AND
                Object_ID  = Object_ID(N'CNF_Promotion'))
BEGIN
	Alter Table CNF_Promotion
	Add COAAccountId Integer NULL
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'MatrixSheetId' AND
                Object_ID  = Object_ID(N'RR_DATA_Revenue'))
BEGIN
	Alter Table RR_DATA_Revenue
	Add MatrixSheetId Integer NULL
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'SaleItemid' AND
                Object_ID  = Object_ID(N'RR_DATA_Revenue'))
BEGIN
	Alter Table RR_DATA_Revenue
	Alter Column SaleItemid int null
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'MatrixCellid' AND
                Object_ID  = Object_ID(N'RR_DATA_Revenue'))
BEGIN
	Alter Table RR_DATA_Revenue
	Alter Column MatrixCellid int null
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'TransactionId' AND
                Object_ID  = Object_ID(N'RR_DATA_Revenue'))
BEGIN
	Alter Table RR_DATA_Revenue
	Alter Column TransactionId int null
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'SaleId' AND
                Object_ID  = Object_ID(N'RR_DATA_Revenue'))
BEGIN
	Alter Table RR_DATA_Revenue
	Alter Column SaleId int null
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>dapicella</ADDEDBY>
			<SQLVERSION>2231</SQLVERSION>
			<RMTRACKLINK>67125</RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF OBJECT_ID('ExportEncodedReservations', 'V') IS NOT NULL
    DROP VIEW ExportEncodedReservations</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF OBJECT_ID('ExportNoPayTransactions', 'V') IS NOT NULL
    DROP VIEW ExportNoPayTransactions</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF OBJECT_ID('ExportTicketReissue', 'V') IS NOT NULL
    DROP VIEW ExportTicketReissue</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF OBJECT_ID('ExportTicketUsages', 'V') IS NOT NULL
    DROP VIEW ExportTicketUsages</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF OBJECT_ID('ExportTransactionItems', 'V') IS NOT NULL
    DROP VIEW ExportTransactionItems</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF OBJECT_ID('ExportTransactionPayments', 'V') IS NOT NULL
    DROP VIEW ExportTransactionPayments</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE VIEW [dbo].[ExportEncodedReservations] as

	SELECT
		TR.TransactionId,
		TR.TransactionAK,
		TR.Completed,
		TR.SiteId,
		PAYTR.TransactionId PAYTrId,
		PAYTR.TransactionAK PAYTrAK,
		APPTR.TransactionId APPTrId,
		APPTR.TransactionAK APPTrAK
	FROM 
		DATA_Transaction TR With(NoLock)
		INNER JOIN DATA_Sale Sale With(NoLock) ON TR.SaleId = Sale.SaleId
		INNER JOIN DATA_Transaction PAYTR With(NoLock) ON Sale.SaleId = PAYTR.SaleId
															AND PAYTR.Paid &gt; 0 
															AND PAYTR.Encoded = 0
															AND PAYTR.TransactionType = 16 --Lk_TransactionType_Reservation
		INNER JOIN DATA_Transaction APPTR With(NoLock) ON Sale.SaleId = APPTR.SaleId
															AND APPTR.Approved &gt; 0 
															AND APPTR.Encoded = 0
															AND APPTR.TransactionType = 16 --Lk_TransactionType_Reservation
	WHERE 
		TR.Encoded = 1 
		AND TR.Paid = 0</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE VIEW [dbo].[ExportNoPayTransactions] as

	SELECT
		SI.SiteCode,
		S.SaleId,
		TR.TransactionId,
		TR.Completed,
		TR.Encoded,
		0 as PaymentId,
		TR.SiteId,
		TR.TransactionAk,
		TR.FTransactionDate,
		WS.WorkstationAK,
		US.UserCode,
		OP.AreaCode,
		TR.TransactionType,
		LkTRType.Description as TransactionTypeDesc,
		0 as PaymentType,
		'NOPAY' as PaymentMethodDesc,
		TR.Revenue as TransactionAmount,
		CUR.ISOCode,
		CUR.ExchangeRate,
		'FALSE' as CREDIT,
		RES.ReservationAK,
		RES_AC.AccountId RES_AccountId,
		RES_AC.AccountAk RES_AccountAk,
		RES_DMGAC.DmgCategoryCode RES_AccountDMG
	FROM
		DATA_Transaction TR With(NoLock) 
		INNER JOIN DATA_Sale S With(NoLock) ON TR.SaleId = S.SaleId
		INNER JOIN CNF_Workstation WS With(NoLock) ON TR.WorkstationId = WS.WorkstationId
		INNER JOIN CNF_User US With(NoLock) ON TR.UserId = US.UserId
		INNER JOIN CNF_OperatingArea OP With(NoLock) ON TR.OperatingAreaId = OP.OperatingAreaId
		INNER JOIN CNF_Site SI With(NoLock) ON TR.SiteId = SI.SiteId
		INNER JOIN CNF_LookUp LkTRType With(NoLock) ON TR.TransactionType = LkTRType.ItemId
														AND LkTRType.LookUpTableId = 3	--Lookup_TransactionType
		LEFT OUTER JOIN DATA_Reservation RES With(NoLock) ON TR.SaleId = RES.SaleId
		LEFT OUTER JOIN DATA_Account RES_AC With(NoLock) ON RES.AccountId = RES_AC.AccountId
		LEFT OUTER JOIN CNF_DmgCategory RES_DMGAC With(NoLock) ON RES_DMGAC.DmgCategoryId = RES_AC.DmgCategoryId
		INNER JOIN CNF_Currency CUR With(NoLock) ON CUR.CurrencyType = 1
		LEFT OUTER JOIN DATA_Payment PAY With(NoLock) ON TR.TransactionId = PAY.TransactionId
	WHERE
		TR.Paid = 1
		AND S.Paid = 1
		AND PAY.PaymentId IS NULL
		AND TR.TransactionType &lt;&gt; 4	--Lk_TransactionType_Reissue
		AND (	
				(TR.TransactionType &lt;&gt; 7 AND TR.Quantity &gt; 0 AND TR.Items &gt; 0)	--Lk_TransactionType_UpgradeDowngrade
				OR
				(TR.TransactionType = 7 AND TR.Quantity = 0 AND TR.Items &gt; 0)	--Lk_TransactionType_UpgradeDowngrade
			)</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE VIEW [dbo].[ExportTicketReissue] as

--reissue

	SELECT 
		SI.SaleItemId,
		TCK.SaleItemId AS TicketSaleItemId, 
		ABS(TI.Quantity) AS Quantity, 
		TI.ProductType,
		TR.TransactionId, 				 
		--TR.TransactionType, 	
		TR.SaleId,			 
		CNF_Site.SiteCode, 
		TR.TransactionAK, 
		TI.ItemId,
		TR.TransactionDate, 
		WS.WorkstationAK,
		US.UserCode, 
		OP.AreaCode,
		LkTRType.Description AS ActionType, --TransactionTypeDesc,
		SI.MatrixCellId AS TicketUniqueId, 
		MC.Code AS ProductCode,
		--identifiercode
		--StoredValue
		RESAC.AccountId AS AccountCode,
		RES.ReservationAK AS ReservationCode,
		DMGOP.DmgCategoryCode AS TransactionType,
		RESDMGAC.DmgCategoryCode AS AccountDMG,
		Promo.DmgCategoryCode AS PromoCategory,
		CASE 
			WHEN (MS.ProductType = 2) 
			THEN (SI.UnitRawPrice * TI.Quantity)
			ELSE --(SI.UnitRawPrice * TI.TransactionItemOperation)
				CASE 
					WHEN (TR.TransactionType &lt;&gt; 30) AND (TCK.TicketId IS NULL)
					THEN 0
					ELSE
						(SI.UnitRawPrice * TI.TransactionItemOperation)
				END 
		END AS GrossAmount,	 
		CASE 
			WHEN (MS.ProductType = 2) 
			THEN (TI.TotalAmount)
			ELSE --(SI.UnitPrice * TI.TransactionItemOperation)
				CASE 
					WHEN (TR.TransactionType &lt;&gt; 30) AND (TCK.TicketId IS NULL)
					THEN 0
					ELSE
						(SI.UnitPrice * TI.TransactionItemOperation)
				END 
		END AS Amount,
		CASE 
			WHEN (MS.ProductType = 2) 
			THEN ((SI.UnitRawPrice - SI.UnitPrice) * TI.Quantity)
			ELSE --((SI.UnitRawPrice - SI.UnitPrice) * TI.TransactionItemOperation)
				CASE 
					WHEN (TR.TransactionType &lt;&gt; 30) AND (TCK.TicketId IS NULL)
					THEN 0
					ELSE
						((SI.UnitRawPrice - SI.UnitPrice) * TI.TransactionItemOperation)
				END 
		END AS DiscountAmount,
		CASE 
			WHEN (MS.ProductType = 2) 
			THEN (TI.TotalTaxes)
			ELSE --(TI.UnitTaxes * TI.TransactionItemOperation)
				CASE 
					WHEN (TR.TransactionType &lt;&gt; 30) AND (TCK.TicketId IS NULL)
					THEN 0
					ELSE
						(TI.UnitTaxes * TI.TransactionItemOperation)
				END 
		END AS TaxAmount,
		SI.UnitRawPrice * TI.TransactionItemOperation AS UnitGrossAmount,
		TI.UnitPrice * TI.TransactionItemOperation AS UnitAmount,
		(SI.UnitRawPrice - SI.UnitPrice) * TI.TransactionItemOperation AS UnitDiscountAmount,
		TI.UnitTaxes * TI.TransactionItemOperation AS UnitTaxAmount,
		(SI.UnitRawPrice * TI.Quantity) AS TotalGrossAmount,
		TI.TotalAmount AS TotalAmount,
		(SI.UnitRawPrice - SI.UnitPrice) * TI.Quantity AS TotalDiscountAmount,
		TI.TotalTaxes AS TotalTaxAmount,
		MultiPark.Code AS MultiParkYesNo, 
		ParkCombo.Code AS ParkCombo,
		CASE	
			WHEN (MS.ProductType &lt;&gt; 2) AND (TR.TransactionType &lt;&gt; 30) AND (TCK.TicketId IS NULL)
			THEN 0
			ELSE
				CASE
					WHEN SICC1.Amount &lt; 0 
						THEN -ISNULL(SICC1.UnitAmount, 0)
					ELSE ISNULL(SICC1.UnitAmount, 0)
				END
		END AS CC1,
		CASE	
			WHEN (MS.ProductType &lt;&gt; 2) AND (TR.TransactionType &lt;&gt; 30) AND (TCK.TicketId IS NULL)
			THEN 0
			ELSE
				CASE
					WHEN SICC2.Amount &lt; 0 
						THEN -ISNULL(SICC2.UnitAmount, 0)
					ELSE ISNULL(SICC2.UnitAmount, 0)
				END
		END AS CC2,
		CASE	
			WHEN (MS.ProductType &lt;&gt; 2) AND (TR.TransactionType &lt;&gt; 30) AND (TCK.TicketId IS NULL)
			THEN 0
			ELSE
				CASE	
					WHEN SICC3.Amount &lt; 0 
						THEN -ISNULL(SICC3.UnitAmount, 0)
					ELSE ISNULL(SICC3.UnitAmount, 0)
				END
		END AS CC3,
		CASE	
			WHEN (MS.ProductType &lt;&gt; 2) AND (TR.TransactionType &lt;&gt; 30) AND (TCK.TicketId IS NULL)
			THEN 0
			ELSE
				CASE
					WHEN SICC4.Amount &lt; 0 
						THEN -ISNULL(SICC4.UnitAmount, 0)
					ELSE ISNULL(SICC4.UnitAmount, 0)
				END
		END AS CC4,
		TI.Quantity AS TicketQty,		
		SeasonalPass.Code AS SeasonalPassYesNo,
		TCK.ActiveTo AS TicketExpireDate,
		TCK.TicketId AS TicketId,
		SI.TicketId ReplacedTicketId,
		SI.ItemTicketId VoidedTicketId,
		TR.Completed, 
		TR.Siteid, 
		TCK.VoidType, 
		S2T.OperationType, 
		CASE 
			WHEN TCK.PrintDateTime IS NULL 
				THEN TCK.FEncodeDate 
			ELSE TCK.PrintDateTime 
		END AS EncodeDateTime, 
		TI.TransactionItemOperation, 
		TI.UnitPrice, 
		TI.UnitRecharge, 
		RESAC.AccountAk 
	FROM 
		DATA_TransactionItem TI				With(NoLock) 
		INNER JOIN DATA_Transaction TR		With(NoLock) ON TI.TransactionId = TR.TransactionId 
		INNER JOIN DATA_SaleItem SI			With(NoLock) ON TI.SaleItemId = SI.SaleItemId 
		INNER JOIN CNF_Workstation WS		With(NoLock) ON TR.WorkstationId = WS.WorkstationId 
		INNER JOIN CNF_User US				With(NoLock) ON TR.UserId = US.UserId 
		INNER JOIN CNF_OperatingArea OP		With(NoLock) ON TR.OperatingAreaId = OP.OperatingAreaId 
		LEFT JOIN  CNF_DmgCategory DMGOP	With(NoLock) ON DMGOP.DmgCategoryId = OP.DmgCategoryId 
		INNER JOIN CNF_Site					With(NoLock) ON TR.SiteId = CNF_Site.SiteId 
		INNER JOIN CNF_LookUp LkTRType		With(NoLock) ON TR.TransactionType = LkTRType.ItemId 
															AND LkTRType.LookUpTableId = 3	--Lookup_TransactionType
		INNER JOIN CNF_MatrixCell MC		With(NoLock) ON SI.MatrixCellId = MC.MatrixCellId 
		LEFT JOIN  CNF_MatrixSheet MS		With(NoLock) ON MS.MatrixSheetId = MC.MatrixSheetId
		LEFT JOIN  (SELECT
						SG.StatisticalGroupCode as Code,
						SGV.MatrixCellId	
					FROM
						CNF_StatisticalGroupValidity SGV With(NoLock)
						INNER JOIN CNF_StatisticalGroup SG With(NoLock) ON SG.ParentId = 4	
																			AND SG.StatisticalGroupId = SGV.StatisticalGroupId) AS MultiPark ON MultiPark.MatrixCellId = MC.MatrixCellId
		LEFT JOIN  (SELECT
						SG.StatisticalGroupCode as Code,
						SGV.MatrixCellId	
					FROM
						CNF_StatisticalGroupValidity SGV With(NoLock)
						INNER JOIN CNF_StatisticalGroup SG With(NoLock) ON SG.ParentId = 7	
																			AND SG.StatisticalGroupId = SGV.StatisticalGroupId) AS ParkCombo ON ParkCombo.MatrixCellId = MC.MatrixCellId
		LEFT JOIN  (SELECT
						SG.StatisticalGroupCode as Code,
						SGV.MatrixCellId	
					FROM
						CNF_StatisticalGroupValidity SGV With(NoLock)
						INNER JOIN CNF_StatisticalGroup SG With(NoLock) ON SG.ParentId = 1	
																			AND SG.StatisticalGroupId = SGV.StatisticalGroupId) AS SeasonalPass ON SeasonalPass.MatrixCellId = MC.MatrixCellId
		LEFT JOIN  DATA_SaleItem2Ticket S2T	With(NoLock) ON SI.SaleItemId = S2T.SaleItemId
		LEFT JOIN  DATA_Ticket TCK			With(NoLock) ON TCK.TicketId = S2T.TicketId 
															AND TCK.VoidType IN (0, 1, 102, 107, 108, 109, 111)--, 125) 
															--Lk_VoidType_Active, Lk_VoidType_Inactive, Lk_VoidType_VoidByEncodingStation,
															--Lk_VoidType_UpgradeDowngrade, Lk_VoidType_BlockUnblock, Lk_VoidType_Refund,
															--Lk_VoidType_Reissue, 
															--Lk_VoidType_TransactionAbort removed
		--LEFT JOIN  DATA_SaleItem SIOriginal With(NoLock) ON TCK.SaleItemId = SIOriginal.SaleItemId
		LEFT JOIN  DATA_Reservation RES		With(NoLock) ON TR.SaleId = RES.SaleId 
															OR (RES.SaleId IN (	SELECT 
																					SaleId 
																				FROM 
																					DATA_Transaction2Ticket With(NoLock)
																					INNER JOIN DATA_Transaction With(NoLock) ON DATA_Transaction2Ticket.TransactionId = DATA_Transaction.TransactionId  
																				WHERE 
																					(DATA_Transaction2Ticket.TicketId = TCK.TicketId)
																					OR
																					(DATA_Transaction2Ticket.TicketId = SI.TicketId))
																					)  
		LEFT JOIN  DATA_Account RESAC		With(NoLock) ON RES.AccountId = RESAC.AccountId
		LEFT JOIN  CNF_DmgCategory RESDMGAC	With(NoLock) ON RESDMGAC.DmgCategoryId = RESAC.DmgCategoryId 
		LEFT JOIN  DATA_SaleItem2CostCenter SICC1	With(NoLock) ON SICC1.SaleItemId = SI.SaleItemId AND SICC1.CostCenterId = 1
		LEFT JOIN  DATA_SaleItem2CostCenter SICC2	With(NoLock) ON SICC2.SaleItemId = SI.SaleItemId AND SICC2.CostCenterId = 2
		LEFT JOIN  DATA_SaleItem2CostCenter SICC3	With(NoLock) ON SICC3.SaleItemId = SI.SaleItemId AND SICC3.CostCenterId = 3
		LEFT JOIN  DATA_SaleItem2CostCenter SICC4	With(NoLock) ON SICC4.SaleItemId = SI.SaleItemId AND SICC4.CostCenterId = 4
		OUTER APPLY  (	SELECT TOP 1
							PRDMGAC.DmgCategoryCode
						FROM
							DATA_TransactionItemRule TIR			With(NoLock) 
							LEFT JOIN  CNF_PromotionItemRule PRIR	With(NoLock) ON PRIR.PromotionItemRuleId = TIR.PromotionItemRuleId
							LEFT JOIN  CNF_PromotionItem PRI		With(NoLock) ON PRI.PromotionItemId = PRIR.PromotionItemId
							LEFT JOIN  CNF_Promotion PR				With(NoLock) ON PR.PromotionId = PRI.PromotionId
							LEFT JOIN  CNF_DmgCategory PRDMGAC		With(NoLock) ON PRDMGAC.DmgCategoryId = PR.DmgCategoryId  
						WHERE
							TIR.ItemId = TI.ItemId
					) as Promo
	WHERE 
		TR.TransactionType = 4			--Lk_TransactionType_Reissue</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE VIEW [dbo].[ExportTicketUsages] as

	SELECT       		
		TCK.FirstUsageId,
		TU.FUsageDate,
		TU.UsageType,
		--lkUT.Description AS UsageType, 
		--MC_Type.OptionValue AS CardActionType,
		MS.ProductType,
		S.SiteId, 
		S.SiteCode, 
		TR.TransactionAK,
		TR.SaleId,   
		TU.UsageId, 
		TU.UsageDate, 		
		WS.WorkstationAK, 
		'SYSTEM' AS UserCode, 
		OP.AreaCode,  
		ISNULL(lkUT.Description, '') + ' ' + ISNULL(MC_Type.OptionValue, '') AS ActionType,
		MC.MatrixCellId AS TicketUniqueId,  
		MC.Code AS ProductCode,
		MI.IdentifierCode,  
		RESAC.AccountId AS AccountCode,
		RES.ReservationAK AS ReservationCode,
		DMGOP.DmgCategoryCode AS TransactionType,
		RESDMGAC.DmgCategoryCode AS AccountDMG,
		Promo.DmgCategoryCode AS PromoCategory,
		(SI.UnitRawPrice) AS GrossAmount,	 
		(SI.UnitPrice) AS Amount,
		(SI.UnitRawPrice - SI.UnitPrice) DiscountAmount,
		(SI.UnitTaxes) TaxAmount,
		(SI.UnitRawPrice * SI.Quantity) AS TotalGrossAmount,
		(SI.TotalAmount) AS TotalAmount,
		(SI.UnitRawPrice - SI.UnitPrice) * SI.Quantity AS TotalDiscountAmount,
		(SI.TotalTaxes) AS TotalTaxAmount,
		MultiPark.Code AS MultiParkYesNo, 
		ParkCombo.Code AS ParkCombo,
		CASE	
			WHEN SICC1.Amount &lt; 0 
				THEN -ISNULL(SICC1.UnitAmount, 0)
			ELSE ISNULL(SICC1.UnitAmount, 0)
		END AS CC1,
		CASE	
			WHEN SICC2.Amount &lt; 0 
				THEN -ISNULL(SICC2.UnitAmount, 0)
			ELSE ISNULL(SICC2.UnitAmount, 0)
		END AS CC2,
		CASE	
			WHEN SICC3.Amount &lt; 0 
				THEN -ISNULL(SICC3.UnitAmount, 0)
			ELSE ISNULL(SICC3.UnitAmount, 0)
		END AS CC3,
		CASE	
			WHEN SICC4.Amount &lt; 0 
				THEN -ISNULL(SICC4.UnitAmount, 0)
			ELSE ISNULL(SICC4.UnitAmount, 0)
		END AS CC4,
		1 AS TicketQty,
		SeasonalPass.Code AS SeasonalPassYesNo,
		TCK.ActiveTo AS TicketExpireDate,
		TCK.TicketId,
		NULL AS ReplacedTicketId, 
		TCK.Serial,  
		MC_Amount.OptionValue AS StoredValue,  
		TU.ValidateResult
	FROM            
		DATA_TicketUsage AS TU With(NoLock) 
		INNER JOIN DATA_MediaIdentifier AS MI With(NoLock) ON MI.MediaIdentifierId = TU.MediaIdentifierId 
		INNER JOIN CNF_Workstation AS WS With(NoLock) ON TU.WorkstationId = WS.WorkstationId 
		INNER JOIN CNF_OperatingArea AS OP With(NoLock) ON WS.OperatingAreaId = OP.OperatingAreaId
		LEFT JOIN  CNF_DmgCategory DMGOP	With(NoLock) ON DMGOP.DmgCategoryId = OP.DmgCategoryId 
		INNER JOIN CNF_Site AS S With(NoLock) ON WS.SiteId = S.SiteId 
		--INNER JOIN (	SELECT 
		--					MIN(UsageId) AS usageid, 
		--					TicketId,
		--					SiteId 
		--				FROM 
		--					DATA_TicketUsage
		--					INNER JOIN CNF_Workstation With(NoLock) ON CNF_Workstation.WorkstationId = DATA_TicketUsage.WorkstationId
		--				WHERE
		--					DATA_TicketUsage.UsageType = 1 --Lk_TicketUsageType_Entry
		--				GROUP BY 
		--					TicketId,
		--					SiteId) AS FTU ON FTU.TicketId = TU.TicketId 
		--										AND FTU.SiteId = Ws.SiteId 
		INNER JOIN DATA_Ticket AS TCK With(NoLock) ON TU.TicketId = TCK.TicketId 
		INNER JOIN DATA_Transaction2Ticket AS T2T With(NoLock) ON TCK.TicketId = T2T.TicketId 
																	AND T2T.OperationType = 1	--Lk_TicketOperationType_Create
		INNER JOIN DATA_Transaction AS TR With(NoLock) ON T2T.TransactionId = TR.TransactionId 
		INNER JOIN CNF_MatrixCell AS MC With(NoLock) ON TCK.MatrixCellId = MC.MatrixCellId
		LEFT JOIN  (SELECT
						SG.StatisticalGroupCode as Code,
						SGV.MatrixCellId	
					FROM
						CNF_StatisticalGroupValidity SGV With(NoLock)
						INNER JOIN CNF_StatisticalGroup SG With(NoLock) ON SG.ParentId = 4	
																			AND SG.StatisticalGroupId = SGV.StatisticalGroupId) AS MultiPark ON MultiPark.MatrixCellId = MC.MatrixCellId
		LEFT JOIN  (SELECT
						SG.StatisticalGroupCode as Code,
						SGV.MatrixCellId	
					FROM
						CNF_StatisticalGroupValidity SGV With(NoLock)
						INNER JOIN CNF_StatisticalGroup SG With(NoLock) ON SG.ParentId = 7	
																			AND SG.StatisticalGroupId = SGV.StatisticalGroupId) AS ParkCombo ON ParkCombo.MatrixCellId = MC.MatrixCellId
		LEFT JOIN  (SELECT
						SG.StatisticalGroupCode as Code,
						SGV.MatrixCellId	
					FROM
						CNF_StatisticalGroupValidity SGV With(NoLock)
						INNER JOIN CNF_StatisticalGroup SG With(NoLock) ON SG.ParentId = 1	
																			AND SG.StatisticalGroupId = SGV.StatisticalGroupId) AS SeasonalPass ON SeasonalPass.MatrixCellId = MC.MatrixCellId 
		INNER JOIN CNF_MatrixSheet AS MS With(NoLock) ON MC.MatrixSheetId = MS.MatrixSheetId 
		LEFT JOIN  CNF_LookUp AS lkUT With(NoLock) ON TU.UsageType = lkUT.ItemId 
															AND lkUT.LookUpTableId = 69	--Lookup_TicketUsageType
		LEFT JOIN  DATA_Reservation AS RES With(NoLock) ON TR.SaleId = RES.SaleId 
		LEFT JOIN  DATA_Account RESAC		With(NoLock) ON RES.AccountId = RESAC.AccountId
		LEFT JOIN  CNF_DmgCategory RESDMGAC	With(NoLock) ON RESDMGAC.DmgCategoryId = RESAC.DmgCategoryId 
		LEFT JOIN  DATA_TicketUsageOption AS MC_Amount With(NoLock) ON TU.UsageId = MC_Amount.UsageId 
																			AND MC_Amount.OptionType = 5	--Lk_TicketUsageOption_MoneyCardAmount
		LEFT JOIN  DATA_TicketUsageOption AS MC_Type With(NoLock) ON TU.UsageId = MC_Type.UsageId 
																			AND MC_Type.OptionType = 4		--Lk_TicketUsageOption_ProductDescription
		LEFT JOIN  DATA_SaleItem SI					With(NoLock) ON TCK.SaleItemId = SI.SaleItemId
		LEFT JOIN  DATA_SaleItem2CostCenter SICC1	With(NoLock) ON SICC1.SaleItemId = SI.SaleItemId AND SICC1.CostCenterId = 1
		LEFT JOIN  DATA_SaleItem2CostCenter SICC2	With(NoLock) ON SICC2.SaleItemId = SI.SaleItemId AND SICC2.CostCenterId = 2
		LEFT JOIN  DATA_SaleItem2CostCenter SICC3	With(NoLock) ON SICC3.SaleItemId = SI.SaleItemId AND SICC3.CostCenterId = 3
		LEFT JOIN  DATA_SaleItem2CostCenter SICC4	With(NoLock) ON SICC4.SaleItemId = SI.SaleItemId AND SICC4.CostCenterId = 4
		OUTER APPLY  (	SELECT TOP 1
							PRDMGAC.DmgCategoryCode
						FROM
							DATA_SaleItemRule SIR					With(NoLock) 
							LEFT JOIN  CNF_PromotionItemRule PRIR	With(NoLock) ON PRIR.PromotionItemRuleId = SIR.PromotionItemRuleId
							LEFT JOIN  CNF_PromotionItem PRI		With(NoLock) ON PRI.PromotionItemId = PRIR.PromotionItemId
							LEFT JOIN  CNF_Promotion PR				With(NoLock) ON PR.PromotionId = PRI.PromotionId
							LEFT JOIN  CNF_DmgCategory PRDMGAC		With(NoLock) ON PRDMGAC.DmgCategoryId = PR.DmgCategoryId  
						WHERE
							SIR.SaleItemId = SI.SaleItemId
					) as Promo
	WHERE        
		(TU.ValidateResult &lt; 99)
		AND (TCK.VoidType not in (107, 111))	--Lk_VoidType_UpgradeDowngrade, Lk_VoidType_Reissue</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE VIEW [dbo].[ExportTransactionItems] AS  

	SELECT 
		SI.SaleItemId,
		TCK.SaleItemId AS TicketSaleItemId, 
		ABS(TI.Quantity) AS Quantity, 
		TI.ProductType,
		TR.TransactionId,
		--TR.TransactionType, 	
		TR.SaleId,			 
		CNF_Site.SiteCode, 
		TR.TransactionAK, 
		TI.ItemId,
		TR.TransactionDate, 
		WS.WorkstationAK,
		US.UserCode, 
		OP.AreaCode,
		LkTRType.Description AS ActionType, --TransactionTypeDesc,
		SI.MatrixCellId AS TicketUniqueId, 
		MC.Code AS ProductCode,
		--identifiercode
		--StoredValue
		RESAC.AccountId AS AccountCode,
		RES.ReservationAK AS ReservationCode,
		DMGOP.DmgCategoryCode AS TransactionType,
		RESDMGAC.DmgCategoryCode AS AccountDMG,
		Promo.DmgCategoryCode AS PromoCategory,
		CASE 
			WHEN (MS.ProductType = 2) 
			THEN (SI.UnitRawPrice * TI.Quantity)
			ELSE --(SI.UnitRawPrice * TI.TransactionItemOperation)
				CASE 
					WHEN (TR.TransactionType &lt;&gt; 30) AND (TCK.TicketId IS NULL)
					THEN 0
					ELSE
						(SI.UnitRawPrice * TI.TransactionItemOperation)
				END 
		END AS GrossAmount,	 
		CASE 
			WHEN (MS.ProductType = 2) 
			THEN (TI.TotalAmount)
			ELSE --(SI.UnitPrice * TI.TransactionItemOperation)
				CASE 
					WHEN (TR.TransactionType &lt;&gt; 30) AND (TCK.TicketId IS NULL)
					THEN 0
					ELSE
						(SI.UnitPrice * TI.TransactionItemOperation)
				END 
		END AS Amount,
		CASE 
			WHEN (MS.ProductType = 2) 
			THEN ((SI.UnitRawPrice - SI.UnitPrice) * TI.Quantity)
			ELSE --((SI.UnitRawPrice - SI.UnitPrice) * TI.TransactionItemOperation)
				CASE 
					WHEN (TR.TransactionType &lt;&gt; 30) AND (TCK.TicketId IS NULL)
					THEN 0
					ELSE
						((SI.UnitRawPrice - SI.UnitPrice) * TI.TransactionItemOperation)
				END 
		END AS DiscountAmount,
		CASE 
			WHEN (MS.ProductType = 2) 
			THEN (TI.TotalTaxes)
			ELSE --(TI.UnitTaxes * TI.TransactionItemOperation)
				CASE 
					WHEN (TR.TransactionType &lt;&gt; 30) AND (TCK.TicketId IS NULL)
					THEN 0
					ELSE
						(TI.UnitTaxes * TI.TransactionItemOperation)
				END 
		END AS TaxAmount,
		SI.UnitRawPrice * TI.TransactionItemOperation AS UnitGrossAmount,
		TI.UnitPrice * TI.TransactionItemOperation AS UnitAmount,
		(SI.UnitRawPrice - SI.UnitPrice) * TI.TransactionItemOperation AS UnitDiscountAmount,
		TI.UnitTaxes * TI.TransactionItemOperation AS UnitTaxAmount,
		(SI.UnitRawPrice * TI.Quantity) AS TotalGrossAmount,
		TI.TotalAmount AS TotalAmount,
		(SI.UnitRawPrice - SI.UnitPrice) * TI.Quantity AS TotalDiscountAmount,
		TI.TotalTaxes AS TotalTaxAmount,
		MultiPark.Code AS MultiParkYesNo, 
		ParkCombo.Code AS ParkCombo,
		CASE	
			WHEN (MS.ProductType &lt;&gt; 2) AND (TR.TransactionType &lt;&gt; 30) AND (TCK.TicketId IS NULL)
			THEN 0
			ELSE
				CASE
					WHEN SICC1.Amount &lt; 0 
						THEN -ISNULL(SICC1.UnitAmount, 0)
					ELSE ISNULL(SICC1.UnitAmount, 0)
				END
		END AS CC1,
		CASE	
			WHEN (MS.ProductType &lt;&gt; 2) AND (TR.TransactionType &lt;&gt; 30) AND (TCK.TicketId IS NULL)
			THEN 0
			ELSE
				CASE
					WHEN SICC2.Amount &lt; 0 
						THEN -ISNULL(SICC2.UnitAmount, 0)
					ELSE ISNULL(SICC2.UnitAmount, 0)
				END
		END AS CC2,
		CASE
			WHEN (MS.ProductType &lt;&gt; 2) AND (TR.TransactionType &lt;&gt; 30) AND (TCK.TicketId IS NULL)
			THEN 0
			ELSE
				CASE	
					WHEN SICC3.Amount &lt; 0 
						THEN -ISNULL(SICC3.UnitAmount, 0)
					ELSE ISNULL(SICC3.UnitAmount, 0)
				END
		END AS CC3,
		CASE	
			WHEN (MS.ProductType &lt;&gt; 2) AND (TR.TransactionType &lt;&gt; 30) AND (TCK.TicketId IS NULL)
			THEN 0
			ELSE
				CASE
					WHEN SICC4.Amount &lt; 0 
						THEN -ISNULL(SICC4.UnitAmount, 0)
					ELSE ISNULL(SICC4.UnitAmount, 0)
				END
		END AS CC4,
		TI.Quantity AS TicketQty,		
		SeasonalPass.Code AS SeasonalPassYesNo,
		TCK.ActiveTo AS TicketExpireDate,
		TCK.TicketId AS TicketId,
		SI.TicketId ReplacedTicketId,
		TR.Completed, 
		TR.Siteid, 
		TCK.VoidType, 
		S2T.OperationType, 
		CASE 
			WHEN TCK.PrintDateTime IS NULL 
				THEN TCK.FEncodeDate 
			ELSE TCK.PrintDateTime 
		END AS EncodeDateTime, 
		TI.TransactionItemOperation, 
		TI.UnitPrice, 
		TI.UnitRecharge, 
		RESAC.AccountAk 
	FROM 
		DATA_TransactionItem TI				With(NoLock) 
		INNER JOIN DATA_Transaction TR		With(NoLock) ON TI.TransactionId = TR.TransactionId 
		INNER JOIN DATA_SaleItem SI			With(NoLock) ON TI.SaleItemId = SI.SaleItemId 
		INNER JOIN CNF_Workstation WS		With(NoLock) ON TR.WorkstationId = WS.WorkstationId 
		INNER JOIN CNF_User US				With(NoLock) ON TR.UserId = US.UserId 
		INNER JOIN CNF_OperatingArea OP		With(NoLock) ON TR.OperatingAreaId = OP.OperatingAreaId 
		LEFT JOIN  CNF_DmgCategory DMGOP	With(NoLock) ON DMGOP.DmgCategoryId = OP.DmgCategoryId 
		INNER JOIN CNF_Site					With(NoLock) ON TR.SiteId = CNF_Site.SiteId 
		INNER JOIN CNF_LookUp LkTRType		With(NoLock) ON TR.TransactionType = LkTRType.ItemId 
															AND LkTRType.LookUpTableId = 3	--Lookup_TransactionType
		INNER JOIN CNF_MatrixCell MC		With(NoLock) ON SI.MatrixCellId = MC.MatrixCellId 
		LEFT JOIN  CNF_MatrixSheet MS		With(NoLock) ON MS.MatrixSheetId = MC.MatrixSheetId
		LEFT JOIN  (SELECT
						SG.StatisticalGroupCode as Code,
						SGV.MatrixCellId	
					FROM
						CNF_StatisticalGroupValidity SGV With(NoLock)
						INNER JOIN CNF_StatisticalGroup SG With(NoLock) ON SG.ParentId = 4	
																			AND SG.StatisticalGroupId = SGV.StatisticalGroupId) AS MultiPark ON MultiPark.MatrixCellId = MC.MatrixCellId
		LEFT JOIN  (SELECT
						SG.StatisticalGroupCode as Code,
						SGV.MatrixCellId	
					FROM
						CNF_StatisticalGroupValidity SGV With(NoLock)
						INNER JOIN CNF_StatisticalGroup SG With(NoLock) ON SG.ParentId = 7	
																			AND SG.StatisticalGroupId = SGV.StatisticalGroupId) AS ParkCombo ON ParkCombo.MatrixCellId = MC.MatrixCellId
		LEFT JOIN  (SELECT
						SG.StatisticalGroupCode as Code,
						SGV.MatrixCellId	
					FROM
						CNF_StatisticalGroupValidity SGV With(NoLock)
						INNER JOIN CNF_StatisticalGroup SG With(NoLock) ON SG.ParentId = 1	
																			AND SG.StatisticalGroupId = SGV.StatisticalGroupId) AS SeasonalPass ON SeasonalPass.MatrixCellId = MC.MatrixCellId
		LEFT JOIN  DATA_SaleItem2Ticket S2T	With(NoLock) ON SI.SaleItemId = S2T.SaleItemId
		LEFT JOIN  DATA_Ticket TCK			With(NoLock) ON TCK.TicketId = S2T.TicketId 
															AND TCK.VoidType IN (0, 1, 102, 107, 108, 109, 111)--, 125) 
															--Lk_VoidType_Active, Lk_VoidType_Inactive, Lk_VoidType_VoidByEncodingStation,
															--Lk_VoidType_UpgradeDowngrade, Lk_VoidType_BlockUnblock, Lk_VoidType_Refund,
															--Lk_VoidType_Reissue, 
															--Lk_VoidType_TransactionAbort removed
		--LEFT JOIN  DATA_SaleItem SIOriginal With(NoLock) ON TCK.SaleItemId = SIOriginal.SaleItemId
		LEFT JOIN  DATA_Reservation RES		With(NoLock) ON TR.SaleId = RES.SaleId 
															OR (RES.SaleId IN (	SELECT 
																					SaleId 
																				FROM 
																					DATA_Transaction2Ticket With(NoLock)
																					INNER JOIN DATA_Transaction With(NoLock) ON DATA_Transaction2Ticket.TransactionId = DATA_Transaction.TransactionId  
																				WHERE 
																					DATA_Transaction2Ticket.TicketId = TCK.TicketId))  
		LEFT JOIN  DATA_Account RESAC		With(NoLock) ON RES.AccountId = RESAC.AccountId
		LEFT JOIN  CNF_DmgCategory RESDMGAC	With(NoLock) ON RESDMGAC.DmgCategoryId = RESAC.DmgCategoryId 
		LEFT JOIN  DATA_SaleItem2CostCenter SICC1	With(NoLock) ON SICC1.SaleItemId = SI.SaleItemId AND SICC1.CostCenterId = 1
		LEFT JOIN  DATA_SaleItem2CostCenter SICC2	With(NoLock) ON SICC2.SaleItemId = SI.SaleItemId AND SICC2.CostCenterId = 2
		LEFT JOIN  DATA_SaleItem2CostCenter SICC3	With(NoLock) ON SICC3.SaleItemId = SI.SaleItemId AND SICC3.CostCenterId = 3
		LEFT JOIN  DATA_SaleItem2CostCenter SICC4	With(NoLock) ON SICC4.SaleItemId = SI.SaleItemId AND SICC4.CostCenterId = 4
		OUTER APPLY  (	SELECT TOP 1
							PRDMGAC.DmgCategoryCode
						FROM
							DATA_TransactionItemRule TIR			With(NoLock) 
							LEFT JOIN  CNF_PromotionItemRule PRIR	With(NoLock) ON PRIR.PromotionItemRuleId = TIR.PromotionItemRuleId
							LEFT JOIN  CNF_PromotionItem PRI		With(NoLock) ON PRI.PromotionItemId = PRIR.PromotionItemId
							LEFT JOIN  CNF_Promotion PR				With(NoLock) ON PR.PromotionId = PRI.PromotionId
							LEFT JOIN  CNF_DmgCategory PRDMGAC		With(NoLock) ON PRDMGAC.DmgCategoryId = PR.DmgCategoryId  
						WHERE
							TIR.ItemId = TI.ItemId
					) as Promo  
	WHERE 
		TR.TransactionType &lt;&gt; 4			--Lk_TransactionType_Reissue</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE VIEW [dbo].[ExportTransactionPayments] AS 

	SELECT 
		SI.SiteCode, 
		TR.TransactionAk,
		TR.SaleId,  
		PAY.PaymentId, 
		PAY.FPaymentDate, 
		WS.WorkstationAK, 
		US.UserCode, 
		OP.AreaCode, 
		LkTRType.Description as TransactionTypeDesc, 
		PM.Description as PaymentMethodDesc, 
		CNFPAYC.CCName, 
		PAYC.AuthorizationCode, 
		PAYC.DevResponseCode, 
		PAY.PaymentAmount, 
		TR.Revenue as TransactionAmount,
		CASE
			WHEN PAYCR.PaymentId &gt; 0
				THEN 'TRUE'
			ELSE
				'FALSE'
		END as CREDIT, 
		TR.TransactionId, 
		TR.Completed, 
		TR.Encoded, 
		TR.Items, 
		TR.TransactionType, 
		PAY.PaymentType, 
		LkPAYType.Description as PaymentTypeDesc, 
		CUR.ISOCode, 
		PAY.ExchangeRate, 
		AC.AccountId, 
		AC.AccountAk,
		DMGAC.DmgCategoryCode AccountDMG, 
		V.VoucherCode, 
		RES.ReservationAK, 
		RES_AC.AccountId RES_AccountId, 
		RES_AC.AccountAk RES_AccountAk,
		RES_DMGAC.DmgCategoryCode RES_AccountDMG, 
		DEBT.PaymentId DEBT_ID, 
		DEBT_RES.ReservationAK DEBT_ReservationAK, 
		DEBT_V.VoucherCode DEBT_VoucherCode, 
		DEBT_AC.AccountId DEBT_AccountId, 
		DEBT_AC.AccountAk DEBT_AccountAk,
		DEBT_DMGAC.DmgCategoryCode DEBT_AccountDMG,  
		TR.FTransactionDate, 
		TR.SiteId
	FROM 
		DATA_Payment PAY With(NoLock) 
		INNER JOIN DATA_Transaction TR With(NoLock) ON TR.TransactionId = PAY.TransactionId 
		INNER JOIN CNF_PaymentMethod PM With(NoLock) ON PAY.PaymentMethodId = PM.PaymentMethodId 
		INNER JOIN CNF_Workstation WS With(NoLock) ON TR.WorkstationId = WS.WorkstationId 
		INNER JOIN CNF_User US With(NoLock) ON TR.UserId = US.UserId 
		INNER JOIN CNF_OperatingArea OP With(NoLock) ON TR.OperatingAreaId = OP.OperatingAreaId 
		INNER JOIN CNF_Site SI With(NoLock) ON TR.SiteId = SI.SiteId 
		INNER JOIN CNF_LookUp LkTRType With(NoLock) ON TR.TransactionType = LkTRType.ItemId 
														AND LkTRType.LookUpTableId = 3
		INNER JOIN CNF_LookUp LkPAYType With(NoLock) ON PAY.PaymentType = LkPAYType.ItemId 
														AND LkPAYType.LookUpTableId = 7
		LEFT OUTER JOIN DATA_PaymentCard PAYC With(NoLock) ON PAY.PaymentId = PAYC.PaymentId 
		LEFT OUTER JOIN CNF_PaymentCard CNFPAYC With(NoLock) ON PAYC.PaymentCardId = CNFPAYC.PaymentCardId 
		LEFT OUTER JOIN DATA_PaymentCredit PAYCR With(NoLock) ON PAY.PaymentId = PAYCR.PaymentId 
		LEFT OUTER JOIN DATA_Account AC With(NoLock) ON PAYCR.AccountId = AC.AccountId
		left outer join CNF_DmgCategory DMGAC With(NoLock) ON DMGAC.DmgCategoryId = AC.DmgCategoryId 
		LEFT OUTER JOIN DATA_Voucher V With(NoLock) ON PAYCR.EntityId = V.VoucherId 
														AND PAYCR.EntityTable = 186
		LEFT OUTER JOIN DATA_Reservation RES With(NoLock) ON TR.SaleId = RES.SaleId 
		LEFT OUTER JOIN DATA_Account RES_AC With(NoLock) ON RES.AccountId = RES_AC.AccountId
		LEFT OUTER JOIN CNF_DmgCategory RES_DMGAC With(NoLock) ON RES_DMGAC.DmgCategoryId = RES_AC.DmgCategoryId 
		LEFT OUTER JOIN DATA_PaymentCredit DEBT With(NoLock) ON PAY.TransactionId = DEBT.SettleTransactionId 
		LEFT OUTER JOIN DATA_Account DEBT_AC With(NoLock) ON DEBT.AccountId = DEBT_AC.AccountId
		LEFT OUTER JOIN CNF_DmgCategory DEBT_DMGAC With(NoLock) ON DEBT_DMGAC.DmgCategoryId = DEBT_AC.DmgCategoryId  
		LEFT OUTER JOIN DATA_Voucher DEBT_V With(NoLock) ON DEBT.EntityId = DEBT_V.VoucherId 
															AND DEBT.EntityTable = 186
		LEFT OUTER JOIN DATA_Payment DEBT_PAY With(NoLock) ON DEBT.PaymentId = DEBT_PAY.PaymentId 
		LEFT OUTER JOIN DATA_Transaction DEBT_TR With(NoLock) ON DEBT_PAY.TransactionId = DEBT_TR.TransactionId 
		LEFT OUTER JOIN DATA_Reservation DEBT_RES With(NoLock) ON DEBT_TR.SaleId = DEBT_RES.SaleId 
		INNER JOIN CNF_Currency CUR With(NoLock) ON PAY.CurrencyId = CUR.CurrencyId 
	WHERE 
		(DEBT_TR.TransactionType &lt;&gt; 22 OR DEBT_TR.TransactionType IS NULL)	--Lk_TransactionType_VoidTransaction
		AND PAY.PaymentStatus = 1	--Lk_PaymentStatus_Approved</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>jlaguardia</ADDEDBY>
			<SQLVERSION>2230</SQLVERSION>
			<RMTRACKLINK>69109</RMTRACKLINK>
			<REASON>+Added column to CNF_Sytem:
ProdWebAddress nvarchar(100)</REASON>
			<TABLENAMES>CNF_System=SystemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'ProdWebAddress' AND 
                Object_ID  = Object_ID(N'CNF_System'))
BEGIN
  ALTER TABLE CNF_System
  ADD [ProdWebAddress] Nvarchar(100) NULL; 
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fesposito</ADDEDBY>
			<SQLVERSION>2229</SQLVERSION>
			<RMTRACKLINK>69144</RMTRACKLINK>
			<REASON>Drop foreign key for Preview and Final contract document template</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
            WHERE TABLE_NAME = N'CNF_FlexContract'
              AND CONSTRAINT_NAME = N'FK_CNF_DocTemplate_PreviewDocTemplateId')          
BEGIN
  ALTER TABLE [CNF_FlexContract]
  DROP CONSTRAINT  FK_CNF_DocTemplate_PreviewDocTemplateId
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
            WHERE TABLE_NAME = N'CNF_FlexContract'
              AND CONSTRAINT_NAME = N'FK_CNF_DocTemplate_FinalDocTemplateId')          
BEGIN
  ALTER TABLE [CNF_FlexContract]
  DROP CONSTRAINT  FK_CNF_DocTemplate_FinalDocTemplateId
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fhufty</ADDEDBY>
			<SQLVERSION>2228</SQLVERSION>
			<RMTRACKLINK>57511</RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES>CNF_DataMask2Crm=DataMask2CrmId
CNF_Mask=MaskId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'CrmIntegration' AND 
                Object_ID  = Object_ID(N'CNF_Mask'))
BEGIN
  ALTER TABLE CNF_Mask
  ADD CrmIntegration smallint 
  ,CrmType smallint 
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>  IF NOT (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'CNF_DataMask2Crm'))

BEGIN

Create table [CNF_DataMask2Crm]
(
	[DataMask2CrmId] Integer Identity(1,1) NOT NULL,
	[DataMaskId] Integer NOT NULL,
	[CrmType] Smallint NOT NULL,
	[CrmTableName] Nvarchar(50) NOT NULL,
	[CrmFieldName] Nvarchar(50) NOT NULL,
	[CrmFieldType] Nvarchar(50) NOT NULL,
Primary Key ([DataMask2CrmId])
) 

END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_DataMask2Crm'
	          AND CONSTRAINT_NAME = N'fk_CNF_DataMask2Crm_DataMaskId')          
BEGIN
  ALTER TABLE [CNF_DataMask2Crm] WITH CHECK 
  ADD  CONSTRAINT [fk_CNF_DataMask2Crm_DataMaskId] FOREIGN KEY([DataMaskId])
  REFERENCES [CNF_DataMask] ([DataMaskId])
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Programmatore</ADDEDBY>
			<SQLVERSION>2227</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.13.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************
			</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Programmatore</ADDEDBY>
			<SQLVERSION>2226</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.13.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************
			</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Programmatore</ADDEDBY>
			<SQLVERSION>2225</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.13.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************
			</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Programmatore</ADDEDBY>
			<SQLVERSION>2224</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.13.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************
			</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Programmatore</ADDEDBY>
			<SQLVERSION>2223</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.13.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************
			</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Programmatore</ADDEDBY>
			<SQLVERSION>2222</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.13.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************
			</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Programmatore</ADDEDBY>
			<SQLVERSION>2221</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.13.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************
			</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Programmatore</ADDEDBY>
			<SQLVERSION>2220</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.13.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************
			</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Programmatore</ADDEDBY>
			<SQLVERSION>2219</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.13.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************
			</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Programmatore</ADDEDBY>
			<SQLVERSION>2218</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.13.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************
			</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>jlaguardia</ADDEDBY>
			<SQLVERSION>2217</SQLVERSION>
			<RMTRACKLINK>68988</RMTRACKLINK>
			<REASON>+Added Enabled field to CNF_Notification</REASON>
			<TABLENAMES>CNF_Notification=NotificationId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Enabled' AND
                Object_ID  = Object_ID(N'CNF_Notification'))
BEGIN
  ALTER TABLE CNF_Notification
  ADD Enabled smallint NOT NULL DEFAULT 0
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>kdixon</ADDEDBY>
			<SQLVERSION>2216</SQLVERSION>
			<RMTRACKLINK>64619</RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES>RR_DATA_Revenue=RevenueRecognitionDataId
COA_CNF_AccountConfig=COAAccountConfigId
RR_CNF_RevenueRecognitionRule=RevenueRecognitionRuleId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'RRCalcTypePeriod' AND
                Object_ID  = Object_ID(N'RR_CNF_RevenueRecognitionRule'))
BEGIN
	ALTER TABLE RR_CNF_RevenueRecognitionRule
	DROP COLUMN RRCalcTypePeriod; 
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'RRCalcTypeSplit' AND
                Object_ID  = Object_ID(N'RR_CNF_RevenueRecognitionRule'))
BEGIN
	ALTER TABLE RR_CNF_RevenueRecognitionRule
	DROP COLUMN RRCalcTypeSplit; 
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'FixedQuantity' AND
                Object_ID  = Object_ID(N'RR_CNF_RevenueRecognitionRule'))
BEGIN
	ALTER TABLE RR_CNF_RevenueRecognitionRule
	DROP COLUMN FixedQuantity; 
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'RRCalcTypeWhen' AND
                Object_ID  = Object_ID(N'RR_CNF_RevenueRecognitionRule'))
BEGIN
	ALTER TABLE RR_CNF_RevenueRecognitionRule
	DROP COLUMN RRCalcTypeWhen;
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'RRCalcTypeTrigger' AND
                Object_ID  = Object_ID(N'RR_CNF_RevenueRecognitionRule'))
BEGIN
  ALTER TABLE RR_CNF_RevenueRecognitionRule
  ADD RRCalcTypeTrigger Smallint NULL
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Percentage' AND
                Object_ID  = Object_ID(N'RR_CNF_RevenueRecognitionRule'))
BEGIN
  ALTER TABLE RR_CNF_RevenueRecognitionRule
  ADD Percentage Float NULL
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Days' AND
                Object_ID  = Object_ID(N'RR_CNF_RevenueRecognitionRule'))
BEGIN
  ALTER TABLE RR_CNF_RevenueRecognitionRule
  ADD Days Integer NULL
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'SiteId' AND
                Object_ID  = Object_ID(N'COA_CNF_AccountConfig'))
BEGIN
  ALTER TABLE COA_CNF_AccountConfig
  ADD SiteId Integer NULL
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'RRCalcTypePeriod' AND
                Object_ID  = Object_ID(N'RR_Data_Revenue'))
BEGIN
	ALTER TABLE RR_Data_Revenue
	DROP COLUMN RRCalcTypePeriod; 
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'RRCalcTypeSplit' AND
                Object_ID  = Object_ID(N'RR_Data_Revenue'))
BEGIN
	ALTER TABLE RR_Data_Revenue
	DROP COLUMN RRCalcTypeSplit; 
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'COAAccountConfigItemId' AND
                Object_ID  = Object_ID(N'RR_Data_Revenue'))
BEGIN
	ALTER TABLE RR_Data_Revenue
	DROP COLUMN COAAccountConfigItemId; 
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'RRCalcTypeWhen' AND
                Object_ID  = Object_ID(N'RR_Data_Revenue'))
BEGIN
	ALTER TABLE RR_Data_Revenue
	DROP COLUMN RRCalcTypeWhen;
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'RRCalcTypeTrigger' AND
                Object_ID  = Object_ID(N'RR_Data_Revenue'))
BEGIN
  ALTER TABLE RR_Data_Revenue
  ADD RRCalcTypeTrigger Smallint NULL
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'RRPercentage' AND
                Object_ID  = Object_ID(N'RR_Data_Revenue'))
BEGIN
  ALTER TABLE RR_Data_Revenue
  ADD RRPercentage Float NULL
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'RRDays' AND
                Object_ID  = Object_ID(N'RR_Data_Revenue'))
BEGIN
  ALTER TABLE RR_Data_Revenue
  ADD RRDays Integer NULL
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS(select 1 from ARC_Document where contextType = 5 and documentType = 0 and repositoryType = 5 and filename = 'bestunionlogo00001.png' and userid = 1 and version = 0)
   delete from ARC_Document where contextType = 5 and documentType = 0 and repositoryType = 5 and filename = 'bestunionlogo00001.png' and userid = 1 and version = 0

Declare @p1 VARCHAR(38)
Declare @p2 DateTime
Set @p1 = '{' + CONVERT(VARCHAR(36), NEWID()) + '}'
Set @p2 = GETDATE()

Insert INTO ARC_Document 
(DocumentAK, DocumentGUID, ContextType, LastUpdate, DocumentType, RepositoryType
 , FileName, UserId, Version, Description, DocData )
VALUES (NULL, @p1, 5, @p2, 0, 5, 'bestunionlogo00001.png', 1, 0, '', [encoded data, 43679 characters])

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fesposito</ADDEDBY>
			<SQLVERSION>2215</SQLVERSION>
			<RMTRACKLINK>68084</RMTRACKLINK>
			<REASON>Add SurveyAK on CNF_Survey</REASON>
			<TABLENAMES>CNF_Survey=SurveyId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'SurveyAK' AND
                Object_ID  = Object_ID(N'CNF_Survey'))
BEGIN
  ALTER TABLE CNF_Survey
  ADD SurveyAK Nvarchar(38) NOT NULL DEFAULT NEWID()
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fesposito</ADDEDBY>
			<SQLVERSION>2214</SQLVERSION>
			<RMTRACKLINK>68084</RMTRACKLINK>
			<REASON>Add MatrixSheetAK in CNF_MatrixSheet</REASON>
			<TABLENAMES>CNF_MatrixSheet=MatrixSheetId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'MatrixSheetAK' AND
                Object_ID  = Object_ID(N'CNF_MatrixSheet'))
BEGIN
  ALTER TABLE CNF_MatrixSheet
  ADD MatrixSheetAK Nvarchar(38) NOT NULL DEFAULT NEWID()
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fesposito</ADDEDBY>
			<SQLVERSION>2213</SQLVERSION>
			<RMTRACKLINK>68084</RMTRACKLINK>
			<REASON>Add TaxPackgeAK in CNF_TaxPackage</REASON>
			<TABLENAMES>CNF_TaxPackage=TaxPackageId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'TaxPackageAK' AND
                Object_ID  = Object_ID(N'CNF_TaxPackage'))
BEGIN
  ALTER TABLE CNF_TaxPackage 
  ADD TaxPackageAK Nvarchar(38) NOT NULL DEFAULT NEWID()
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fesposito</ADDEDBY>
			<SQLVERSION>2212</SQLVERSION>
			<RMTRACKLINK>68084</RMTRACKLINK>
			<REASON>Add CategoryAK in STOCK_CNF_ProductCategory</REASON>
			<TABLENAMES>STOCK_CNF_ProductCategory=CategoryId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'CategoryAK' AND
                Object_ID  = Object_ID(N'STOCK_CNF_ProductCategory'))
BEGIN
  ALTER TABLE STOCK_CNF_ProductCategory 
  ADD CategoryAK Nvarchar(38) NOT NULL DEFAULT NEWID()
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>2211</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>CNF_Delivery_Permission
[0] Create table
[1] Add FK on UserGroup
[2] Add FK on User
[3] Add FK on Site
[4] Add FK on OpArea
[5] Add FK on Workstation
[5] Add FK on Delivery</REASON>
			<TABLENAMES>CNF_Delivery_Permission=DeliverypermissionId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT (EXISTS (SELECT * 
                FROM INFORMATION_SCHEMA.TABLES 
                WHERE TABLE_SCHEMA = 'dbo' 
                  AND TABLE_NAME = 'CNF_Delivery_Permission'))

BEGIN
Create table [CNF_Delivery_Permission]
(
	[DeliveryPermissionId] Integer Identity(1,1) NOT NULL, UNIQUE ([DeliveryPermissionId]),
	[DeliveryId] Integer NOT NULL,
	[UserGroupId] Integer NULL,
	[UserId] Integer NULL,
	[SiteId] Integer NULL,
	[OperatingAreaId] Integer NULL,
	[WorkstationId] Integer NULL,
	[Allow] Smallint NOT NULL,
Primary Key ([DeliveryPermissionId])
) 
END				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Delivery_Permission] 
add  foreign key([UserGroupId]) references [CNF_UserGroup] ([UserGroupId])
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Delivery_Permission] 
  add  foreign key([UserId]) references [CNF_User] ([UserId])

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Delivery_Permission] 
  add  foreign key([SiteId]) references [CNF_Site] ([SiteId]) 


				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Delivery_Permission] 
  add  foreign key([OperatingAreaId]) references [CNF_OperatingArea] ([OperatingAreaId]) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Delivery_Permission] 
  add  foreign key([WorkstationId]) references [CNF_Workstation] ([WorkstationId])

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Delivery_Permission] 
  add  foreign key([DeliveryId]) references [CNF_Delivery] ([DeliveryId]) 
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fesposito</ADDEDBY>
			<SQLVERSION>2210</SQLVERSION>
			<RMTRACKLINK>68084</RMTRACKLINK>
			<REASON>Add UmAK in STOCK_CNF_Um</REASON>
			<TABLENAMES>STOCK_CNF_Um=UmId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'UmAK' AND
                Object_ID  = Object_ID(N'STOCK_CNF_Um'))
BEGIN
  ALTER TABLE STOCK_CNF_Um 
  ADD UmAK Nvarchar(38) NOT NULL DEFAULT NEWID()
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>kdixon</ADDEDBY>
			<SQLVERSION>2209</SQLVERSION>
			<RMTRACKLINK>64619</RMTRACKLINK>
			<REASON>0 - Add External Code to coa_cnf_account table
1 - add enabled to coa_cnf_accountconfig
2 - add enabled to rr_cnf_product</REASON>
			<TABLENAMES>COA_CNF_AccountConfig=COAAccountConfigId
RR_CNF_Product=RevenueRecognitionProductId
COA_CNF_Account=COAAccountId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'ExternalCode' AND
                Object_ID  = Object_ID(N'COA_CNF_ACCOUNT'))
BEGIN
  ALTER TABLE COA_CNF_ACCOUNT 
  ADD [ExternalCode] Nvarchar(25) NULL
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Enabled' AND
                Object_ID  = Object_ID(N'RR_CNF_Product'))
BEGIN
  ALTER TABLE RR_CNF_Product 
  ADD [Enabled] Smallint NOT NULL
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Enabled' AND
                Object_ID  = Object_ID(N'COA_CNF_AccountConfig'))
BEGIN
  ALTER TABLE COA_CNF_AccountConfig 
  ADD [Enabled] Smallint NOT NULL
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>dapicella</ADDEDBY>
			<SQLVERSION>2208</SQLVERSION>
			<RMTRACKLINK>52454</RMTRACKLINK>
			<REASON>CNF_License
[0] Delete Existing Data
[1] alter column License to varchar</REASON>
			<TABLENAMES>CNF_License=LicenseId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>DELETE FROM CNF_License</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'License' AND
                Object_ID  = Object_ID(N'CNF_License'))
BEGIN
  ALTER TABLE CNF_License ALTER COLUMN License varchar(MAX) NOT NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>kdixon</ADDEDBY>
			<SQLVERSION>2207</SQLVERSION>
			<RMTRACKLINK>64619</RMTRACKLINK>
			<REASON>0 - Drop unused table
1 - Remove Column
3 - Drop unused Table
4 - 
5 - Drop table and Rebuild
			</REASON>
			<TABLENAMES>COA_CNF_AccountConfig=COAAccountConfigId
RR_DATA_Revenue=RevenueRecognitionDataId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'rr_cnf_validity')) 
DROP TABLE rr_cnf_validity
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * 
            FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS 
           WHERE CONSTRAINT_NAME ='FK_RR_DATA_Revenue_COA_CNF_AccountConfigItem_COAAccountConfigItemId')
BEGIN 
  ALTER TABLE RR_Data_revenue   
      DROP CONSTRAINT FK_RR_DATA_Revenue_COA_CNF_AccountConfigItem_COAAccountConfigItemId; 
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'LicenceCode' AND
                Object_ID  = Object_ID(N'RR_Data_revenue'))
BEGIN 
  ALTER TABLE RR_Data_revenue DROP COLUMN 
  	COAAccountConfigItemID
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'COA_CNF_AccountConfigItem')) 
DROP TABLE COA_CNF_AccountConfigItem
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * 
            FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS 
           WHERE CONSTRAINT_NAME ='FK_RR_DATA_Revenue_COA_CNF_AccountConfig_COAAccountConfigId')
BEGIN 
  ALTER TABLE RR_Data_revenue   
      DROP CONSTRAINT FK_RR_DATA_Revenue_COA_CNF_AccountConfig_COAAccountConfigId; 
END


				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'COA_CNF_AccountConfig')) 
DROP TABLE COA_CNF_AccountConfig
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'COA_CNF_AccountConfig')
BEGIN
	Create table [COA_CNF_AccountConfig]
	(
		[COAAccountConfigId] Integer Identity(1,1) NOT NULL, UNIQUE ([COAAccountConfigId]),
		[COAAccountId] Integer NOT NULL,
		[RevenueRecognitionRuleId] Integer NOT NULL,
		[AccountingType] Smallint NOT NULL,
		[Price] Float NULL,
		[Percentage] Float NULL,
		[RemainingValues] Bit NULL,
	Primary Key ([COAAccountConfigId])
	) 
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int

EXEC Otn_Add_ForeingKey
	@ForeingKeyTable = N'RR_DATA_Revenue', @ForeingKeyReferenceTable  = N'COA_CNF_AccountConfig',
	@ForeingKeyColumn = N'COAAccountConfigId', @ForeingKeyReferenceColumn = N'COAAccountConfigId',
	@result = @retval OUTPUT
SELECT @retval;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int  

EXEC Otn_Add_ForeingKey 
	@ForeingKeyTable = N'COA_CNF_AccountConfig', 
        @ForeingKeyReferenceTable  = N'COA_CNF_Account',
	@ForeingKeyColumn = N'COAAccountId', @ForeingKeyReferenceColumn = N'COAAccountId',
	@result = @retval OUTPUT
SELECT @retval;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int  

EXEC Otn_Add_ForeingKey 
	@ForeingKeyTable = N'COA_CNF_AccountConfig', @ForeingKeyReferenceTable  = N'RR_CNF_RevenueRecognitionRule',
	@ForeingKeyColumn = N'RevenueRecognitionRuleId', @ForeingKeyReferenceColumn = N'RevenueRecognitionRuleId',
	@result = @retval OUTPUT
SELECT @retval;
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>jlaguardia</ADDEDBY>
			<SQLVERSION>2206</SQLVERSION>
			<RMTRACKLINK>68988</RMTRACKLINK>
			<REASON>+Add table CNF_Notification 
+Add AllowNotification fields to CNF_Performance and CNF_Event</REASON>
			<TABLENAMES>CNF_Event=EventId
CNF_Performance=PerformanceId
CNF_Notification=NotificationId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'CNF_Notification'))

BEGIN
Create table [CNF_Notification]
(
	[NotificationId] Integer Identity(1,1) NOT NULL,
	[DocTemplateId] Integer NOT NULL,
	[EntityTable] Integer NULL,
	[EntityId] Integer NULL,
	[TimeType] Smallint NULL,
	[TimeValue] Float NULL,
Primary Key ([NotificationId])
) 
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'AllowNotification' AND
                Object_ID  = Object_ID(N'CNF_Event'))
BEGIN
  ALTER TABLE CNF_Event ADD 
	[AllowNotification] smallint
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'AllowNotification' AND
                Object_ID  = Object_ID(N'CNF_Performance'))
BEGIN
  ALTER TABLE CNF_Performance ADD 
	[AllowNotification] smallint
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fesposito</ADDEDBY>
			<SQLVERSION>2205</SQLVERSION>
			<RMTRACKLINK>68972</RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT 1 
                 FROM DATA_COUNTER
                WHERE CounterType = 16
                  AND IdentifierAK = 'SHIFT4.INVOICENO'
                  AND ReferenceTime = 'NEVER')
BEGIN
  INSERT INTO DATA_COUNTER (CounterType, IdentifierAK, ReferenceTime, Counter) 
  VALUES (16, 'SHIFT4.INVOICENO', 'NEVER', (SELECT (COALESCE(MAX(PaymentId), 0)+1) FROM DATA_Payment))
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>dapicella</ADDEDBY>
			<SQLVERSION>2204</SQLVERSION>
			<RMTRACKLINK>52454</RMTRACKLINK>
			<REASON>CNF_License
[0] remove column
[1] add column</REASON>
			<TABLENAMES>CNF_License=LicenseId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'LicenceCode' AND
                Object_ID  = Object_ID(N'CNF_License'))
BEGIN 
  ALTER TABLE CNF_License DROP COLUMN 
  	Description, 
	LicenseType, 
	LicenseSubType, 
	LicenceCode, 
	ImportDate
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'License' AND
                Object_ID  = Object_ID(N'CNF_License'))
BEGIN
  ALTER TABLE CNF_License ADD 
	[LastUpdateDate] Datetime NOT NULL,
	[License] [nvarchar](MAX) NOT NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>2203</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>Add New Sp for create the Account CSV
[0] remove if exist
[1] recreate it</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE type = 'P' AND name = 'AccountListByDmgCategoryCode')
  DROP PROCEDURE AccountListByDmgCategoryCode

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create PROCEDURE [dbo].[AccountListByDmgCategoryCode]
	-- Add the parameters for the stored procedure here
	@DmgCatCode varchar(MAx)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)


select @cols = STUFF((SELECT ',' + QUOTENAME(DM.FieldName + '_' + cast(DM.ObjType as varchar(MAX))) 
from
  CNF_DmgCategory2Mask as C2M with(nolock)
  inner join CNF_DataMask as DM with(nolock) on (DM.MaskId=C2M.MaskId)
  where C2M.dmgcategoryid = (select dmgcategoryid from CNF_DmgCategory where DmgCategoryCode = @DmgcatCode)
                              FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
		print @cols

set @query = N'SELECT BOSId, Barcode, DataCreazione, ' + @cols + N' from 
             (
select
  AC.AccountId as BOSId,
  MI.IdentifierCode as Barcode,
  AC.InsDateTime as DataCreazione,
  DM.FieldName + ''_'' + cast(DM.ObjType as varchar(MAX)) as ColumnName,
  case when DM.masktableid is null then 
  case when (DM.ObjType not in(1,3,6,8,9,10,11,12,13,14,15,21,55,56,57,549,31)) then DD.MaskData
       when (DM.ObjType = 1) then AC.FirstName
       when (DM.ObjType = 3) then AC.SurName
       when (DM.ObjType = 6) then AC.Address1
       when (DM.ObjType = 8) then AC.City
       when (DM.ObjType = 9) then AC.State
       when (DM.ObjType = 10) then AC.ZipCode
       when (DM.ObjType = 11) then AC.Country
       when (DM.ObjType = 12) then AC.HomePhone
       when (DM.ObjType = 13) then AC.BusinessPhone
       when (DM.ObjType = 14) then AC.Fax
       when (DM.ObjType = 15) then AC.MobilePhone
       when (DM.ObjType = 21) then AC.EmailAddress1
       when (DM.ObjType = 55) then AC.ExternalCode1
       when (DM.ObjType = 56) then AC.DisplayField1
       when (DM.ObjType = 57) then AC.DisplayField2
       when (DM.ObjType = 549) then AC.Password
       when (DM.ObjType = 31) then AC.CompanyName end 
	   else (SELECT Itemdescription from CNF_MaskTableItem where CNF_MaskTableItem.MaskTableId = DM.masktableid and CNF_MaskTableItem.ItemCode = 
  case when (DM.ObjType not in(1,3,6,8,9,10,11,12,13,14,15,21,55,56,57,549,31)) then DD.MaskData
       when (DM.ObjType = 1) then AC.FirstName
       when (DM.ObjType = 3) then AC.SurName
       when (DM.ObjType = 6) then AC.Address1
       when (DM.ObjType = 8) then AC.City
       when (DM.ObjType = 9) then AC.State
       when (DM.ObjType = 10) then AC.ZipCode
       when (DM.ObjType = 11) then AC.Country
       when (DM.ObjType = 12) then AC.HomePhone
       when (DM.ObjType = 13) then AC.BusinessPhone
       when (DM.ObjType = 14) then AC.Fax
       when (DM.ObjType = 15) then AC.MobilePhone
       when (DM.ObjType = 21) then AC.EmailAddress1
       when (DM.ObjType = 55) then AC.ExternalCode1
       when (DM.ObjType = 56) then AC.DisplayField1
       when (DM.ObjType = 57) then AC.DisplayField2
       when (DM.ObjType = 549) then AC.Password
       when (DM.ObjType = 31) then AC.CompanyName end ) end as Value
from
  CNF_DmgCategory2Mask as C2M with(nolock)
  inner join CNF_DataMask as DM with(nolock) on (DM.MaskId=C2M.MaskId)
  inner join DATA_Account as AC with(nolock) on (AC.DmgCategoryId=C2M.DmgCategoryId)
  left join DATA_Ticket as TI with(nolock) on (AC.AccountId=TI.AccountId)
  left join DATA_ticket2Media as T2M on (TI.TicketId=T2M.TicketId)
  left join DATA_MediaIdentifier as MI with(nolock) on (MI.MediaId=T2M.MediaId)
  left join DATA_DmgData as DD with(nolock)  on (DD.ObjType=DM.ObjType and DD.FKey=AC.AccountId and DD.DmgType = 1 and DD.ObjType not in (1,3,6,8,9,10,11,12,13,14,15,21,55,56,57,549,31))
  where AC.dmgcategoryid = (select dmgcategoryid from CNF_DmgCategory where DmgCategoryCode = '''+@DmgcatCode+''')

            ) x
            pivot 
            (
                max(value)
                for ColumnName in (' + @cols + N')
            ) p order by DataCreazione'

exec sp_executesql @query;


END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>marioarosio</ADDEDBY>
			<SQLVERSION>2202</SQLVERSION>
			<RMTRACKLINK>68001</RMTRACKLINK>
			<REASON>_M_: Adding "Creation Date", "Last Modification Date" and "UserID" (the one that has modified it) columns in the summary in these tables:
CNF_Promotion
CNF_PromotionItem
CNF_PromotionItemRule</REASON>
			<TABLENAMES>CNF_Promotion=PromotionId
CNF_PromotionItem=PromotionItemId
CNF_PromotionItemRule=PromotionItemRuleId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'CreationDate' AND
                Object_ID  = Object_ID(N'CNF_Promotion'))
BEGIN
  ALTER TABLE CNF_Promotion ADD 
	[CreationDate] Datetime,
	[LastModificationDate] Datetime,
	[UserID] Integer
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'CreationDate' AND
                Object_ID  = Object_ID(N'CNF_PromotionItem'))
BEGIN
  ALTER TABLE CNF_PromotionItem ADD 
	[CreationDate] Datetime,
	[LastModificationDate] Datetime,
	[UserID] Integer
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'CreationDate' AND
                Object_ID  = Object_ID(N'CNF_PromotionItemRule'))
BEGIN
  ALTER TABLE CNF_PromotionItemRule ADD 
	[CreationDate] Datetime,
	[LastModificationDate] Datetime,
	[UserID] Integer
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_Promotion'
	          AND CONSTRAINT_NAME = N'fk_CNF_Promotion_UserID')          
BEGIN
  ALTER TABLE [CNF_Promotion] WITH CHECK 
  ADD  CONSTRAINT [fk_CNF_Promotion_UserID] FOREIGN KEY([UserID])
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_PromotionItem'
	          AND CONSTRAINT_NAME = N'fk_CNF_PromotionItem_UserID')          
BEGIN
  ALTER TABLE [CNF_PromotionItem] WITH CHECK 
  ADD  CONSTRAINT [fk_CNF_PromotionItem_UserID] FOREIGN KEY([UserID])
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_PromotionItemRule'
	          AND CONSTRAINT_NAME = N'fk_CNF_PromotionItemRule_UserID')          
BEGIN
  ALTER TABLE [CNF_PromotionItemRule] WITH CHECK 
  ADD  CONSTRAINT [fk_CNF_PromotionItemRule_UserID] FOREIGN KEY([UserID])
  REFERENCES [CNF_User] ([UserId])
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fesposito</ADDEDBY>
			<SQLVERSION>2201</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>Add Unmerged column</REASON>
			<TABLENAMES>DATA_MergeAccountLog=MergeAccountLogId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Unmerged' AND
                Object_ID  = Object_ID(N'DATA_MergeAccountLog'))
BEGIN
  ALTER TABLE DATA_MergeAccountLog ADD 
    [Unmerged] Smallint,
    [UnmergeDate] DATETIME
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fesposito</ADDEDBY>
			<SQLVERSION>2200</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>Add EntityIdColumnName</REASON>
			<TABLENAMES>DATA_MergeAccountLogItem=MergeAccountLogItemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'EntityIdColumnName' AND
                Object_ID  = Object_ID(N'DATA_MergeAccountLogItem'))
BEGIN
  ALTER TABLE DATA_MergeAccountLogItem ADD 
    [EntityIdColumnName] Nvarchar(50) NOT NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>marioarosio</ADDEDBY>
			<SQLVERSION>2199</SQLVERSION>
			<RMTRACKLINK>68458</RMTRACKLINK>
			<REASON>Create brand new table CNF_CustomColor to save the user defined custom color for BOS</REASON>
			<TABLENAMES>CNF_CustomColor=CustomColorId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_CustomColor]
(
	[CustomColorId] Tinyint Identity(1,1) NOT NULL, UNIQUE ([CustomColorId]),
	[ColorA] Char(6) NULL,
	[ColorB] Char(6) NULL,
	[ColorC] Char(6) NULL,
	[ColorD] Char(6) NULL,
	[ColorE] Char(6) NULL,
	[ColorF] Char(6) NULL,
	[ColorG] Char(6) NULL,
	[ColorH] Char(6) NULL,
	[ColorI] Char(6) NULL,
	[ColorJ] Char(6) NULL,
	[ColorK] Char(6) NULL,
	[ColorL] Char(6) NULL,
	[ColorM] Char(6) NULL,
	[ColorN] Char(6) NULL,
	[ColorO] Char(6) NULL,
	[ColorP] Char(6) NULL,
Primary Key ([CustomColorId])
) </SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>kdixon</ADDEDBY>
			<SQLVERSION>2198</SQLVERSION>
			<RMTRACKLINK>64619</RMTRACKLINK>
			<REASON>Insert Default data into COA tables</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (select * 
               from COA_CNF_AccountType 
               where Code = 'ASSET')

BEGIN
	INSERT INTO [dbo].[COA_CNF_AccountType]
			   ([COAAccountTypeAK]
			   ,[Code]
			   ,[Name]
			   ,[Description]
			   ,[SystemAccount]
			   ,[Enabled])
		 VALUES
			   (SUBSTRING(CONVERT(VARCHAR(36), NEWID()), 1, 32)
			   ,'ASSET'
			   ,'Asset'
			   ,'Asset'
			   ,1
			   ,1)
END








				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (select * 
               from COA_CNF_AccountType 
               where Code = 'EQUITY')

BEGIN
	INSERT INTO [dbo].[COA_CNF_AccountType]
			   ([COAAccountTypeAK]
			   ,[Code]
			   ,[Name]
			   ,[Description]
			   ,[SystemAccount]
			   ,[Enabled])
		 VALUES
			   (SUBSTRING(CONVERT(VARCHAR(36), NEWID()), 1, 32)
			   ,'EQUITY'
			   ,'Equity'
			   ,'Equity'
			   ,1
			   ,1)
END 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (select * 
               from COA_CNF_AccountType 
               where Code = 'EXPENSE')

BEGIN
	INSERT INTO [dbo].[COA_CNF_AccountType]
			   ([COAAccountTypeAK]
			   ,[Code]
			   ,[Name]
			   ,[Description]
			   ,[SystemAccount]
			   ,[Enabled])
		 VALUES
			   (SUBSTRING(CONVERT(VARCHAR(36), NEWID()), 1, 32)
			   ,'EXPENSE'
			   ,'Expense'
			   ,'Expense'
			   ,1
			   ,1)
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (select * 
               from COA_CNF_AccountType 
               where Code = 'LIABILITY')

BEGIN
INSERT INTO [dbo].[COA_CNF_AccountType]
           ([COAAccountTypeAK]
           ,[Code]
           ,[Name]
           ,[Description]
           ,[SystemAccount]
           ,[Enabled])
     VALUES
           (SUBSTRING(CONVERT(VARCHAR(36), NEWID()), 1, 32)
           ,'LIABILITY'
           ,'Liability'
           ,'Liability'
           ,1
           ,1)
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (select * 
               from COA_CNF_AccountType 
               where Code = 'REVENUE')

BEGIN
INSERT INTO [dbo].[COA_CNF_AccountType]
           ([COAAccountTypeAK]
           ,[Code]
           ,[Name]
           ,[Description]
           ,[SystemAccount]
           ,[Enabled])
     VALUES
           (SUBSTRING(CONVERT(VARCHAR(36), NEWID()), 1, 32)
           ,'REVENUE'
           ,'Revenue'
           ,'Revenue'
           ,1
           ,1)
END 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (select * 
               from COA_CNF_Account
               where Code = 'SUSPEND')

BEGIN
INSERT INTO [dbo].[COA_CNF_Account]
           ([COAAccountTypeId]
           ,[ParentAccountId]
           ,[COAAccountAK]
           ,[Code]
           ,[Name]
           ,[Description]
           ,[SystemAccount]
           ,[FromDate]
           ,[ToDate]
           ,[Enabled])
     VALUES
           ((select COAAccountTypeID
               from COA_CNF_AccountType 
               where Code = 'ASSET')
           ,NULL
           ,SUBSTRING(CONVERT(VARCHAR(36), NEWID()), 1, 32)
           ,'SUSPEND'
           ,'Suspend'
           ,'Suspend'
           ,1
           ,GETDATE()
           ,DateAdd(YY, 25, getdate())
           ,1)
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (select * 
               from COA_CNF_Account
               where Code = 'PYMTMETHOD')

BEGIN
INSERT INTO [dbo].[COA_CNF_Account]
           ([COAAccountTypeId]
           ,[ParentAccountId]
           ,[COAAccountAK]
           ,[Code]
           ,[Name]
           ,[Description]
           ,[SystemAccount]
           ,[FromDate]
           ,[ToDate]
           ,[Enabled])
     VALUES
           ((select COAAccountTypeID
               from COA_CNF_AccountType 
               where Code = 'ASSET')
           ,NULL
           ,SUBSTRING(CONVERT(VARCHAR(36), NEWID()), 1, 32)
           ,'PYMTMETHOD'
           ,'Payment Method'
           ,'Payment Method'
           ,1
           ,GETDATE()
           ,DateAdd(YY, 25, getdate())
           ,1)
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (select * 
               from COA_CNF_Account
               where Code = 'TAXES')

BEGIN
INSERT INTO [dbo].[COA_CNF_Account]
           ([COAAccountTypeId]
           ,[ParentAccountId]
           ,[COAAccountAK]
           ,[Code]
           ,[Name]
           ,[Description]
           ,[SystemAccount]
           ,[FromDate]
           ,[ToDate]
           ,[Enabled])
     VALUES
           ((select COAAccountTypeID
               from COA_CNF_AccountType 
               where Code = 'LIABILITY')
           ,NULL
     ,SUBSTRING(CONVERT(VARCHAR(36), NEWID()), 1, 32)
           ,'TAXES'
           ,'Taxes'
           ,'Taxes'
           ,1
           ,GETDATE()
           ,DateAdd(YY, 25, getdate())
           ,1)
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (select * 
               from COA_CNF_Account
               where Code = 'DISCOUNTS')

BEGIN
INSERT INTO [dbo].[COA_CNF_Account]
           ([COAAccountTypeId]
           ,[ParentAccountId]
           ,[COAAccountAK]
           ,[Code]
           ,[Name]
           ,[Description]
           ,[SystemAccount]
           ,[FromDate]
           ,[ToDate]
           ,[Enabled])
     VALUES
           ((select COAAccountTypeID
               from COA_CNF_AccountType 
               where Code = 'EXPENSE')
           ,NULL
     ,SUBSTRING(CONVERT(VARCHAR(36), NEWID()), 1, 32)
           ,'DISCOUNTS'
           ,'Discounts'
           ,'Discounts'
           ,1
           ,GETDATE()
           ,DateAdd(YY, 25, getdate())
           ,1)
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (select * 
               from COA_CNF_Account
               where Code = 'DEFREVENUE')

BEGIN
INSERT INTO [dbo].[COA_CNF_Account]
           ([COAAccountTypeId]
           ,[ParentAccountId]
           ,[COAAccountAK]
           ,[Code]
           ,[Name]
           ,[Description]
           ,[SystemAccount]
           ,[FromDate]
           ,[ToDate]
           ,[Enabled])
     VALUES
           ((select COAAccountTypeID
               from COA_CNF_AccountType 
               where Code = 'LIABILITY')
           ,NULL
           ,SUBSTRING(CONVERT(VARCHAR(36), NEWID()), 1, 32)
           ,'DEFREVENUE'
           ,'Deferred Revenue'
           ,'Deferred Revenue'
           ,1
           ,GETDATE()
           ,DateAdd(YY, 25, getdate())
           ,1)
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>jlaguardia</ADDEDBY>
			<SQLVERSION>2197</SQLVERSION>
			<RMTRACKLINK>68305</RMTRACKLINK>
			<REASON>+Added 6 fields to CNF_Event:
  +DefaultFromTime DATETIME
  +DefaultToTime DATETIME
  +DefaultInterval Integer
  +DefaultTimeOpening Integer
  +DefaultTimeLimit Integer
  +DefaultMinOnScreen Integer</REASON>
			<TABLENAMES>CNF_Event=EventId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'DefaultFromTime' AND
                Object_ID  = Object_ID(N'CNF_Event'))
BEGIN
  ALTER TABLE CNF_Event ADD 
    DefaultFromTime DATETIME,
    DefaultToTime DATETIME,
    DefaultInterval Integer,
    DefaultTimeOpening Integer,
    DefaultTimeLimit Integer,
    DefaultMinOnScreen Integer
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>blumsden</ADDEDBY>
			<SQLVERSION>2196</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>Creating Table DATA_MergeAccountLog
[0] Create DATA_MergeAccountLog

Creating Table DATA_MergeAccountLogItem
[1] Create DATA_MergeAccountLogItem

Add Foreign Key to DATA_MergeAccountLog
[2] Adding Foreign Key OldAccountId
[3] Adding Foreign Key NewAccountId

Add Foreign Key to DATA_MergeAccountLogItem
[4] Adding Foreign Key MergeAccountLogId</REASON>
			<TABLENAMES>DATA_MergeAccountLog=MergeAccountLogId
DATA_MergeAccountLogItem=MergeAccountLogItemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (select * 
               from sys.tables 
               where NAME = 'DATA_MergeAccountLog')

BEGIN
Create table [DATA_MergeAccountLog]
(
	[MergeAccountLogId] Integer Identity(1,1) NOT NULL,
	[OldAccountId] Integer NOT NULL,
	[NewAccountId] Integer NOT NULL,
	[MergeDate] Datetime NOT NULL,
Primary Key ([MergeAccountLogId])
) 
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (select * 
               from sys.tables 
               where NAME = 'DATA_MergeAccountLogItem')

BEGIN
Create table [DATA_MergeAccountLogItem]
(
	[MergeAccountLogItemId] Integer Identity(1,1) NOT NULL,
	[MergeAccountLogId] Integer NOT NULL,
	[EntityType] Integer NOT NULL,
	[EntityId] Integer NOT NULL,
	[ColumnName] Nvarchar(50) NOT NULL,
Primary Key ([MergeAccountLogItemId])
) 
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'DATA_MergeAccountLog'
	          AND CONSTRAINT_NAME = N'fk_DATA_MergeAccountLog_OldAccountId')          
BEGIN
  ALTER TABLE [DATA_MergeAccountLog] WITH CHECK 
  ADD  CONSTRAINT [fk_DATA_MergeAccountLog_OldAccountId] FOREIGN KEY([OldAccountId])
  REFERENCES [DATA_Account] ([AccountId])
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'DATA_MergeAccountLog'
	          AND CONSTRAINT_NAME = N'fk_DATA_MergeAccountLog_NewAccountId')          
BEGIN
  ALTER TABLE [DATA_MergeAccountLog] WITH CHECK 
  ADD  CONSTRAINT [fk_DATA_MergeAccountLog_NewAccountId] FOREIGN KEY([NewAccountId])
  REFERENCES [DATA_Account] ([AccountId])
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'DATA_MergeAccountLogItem'
	          AND CONSTRAINT_NAME = N'fk_DATA_MergeAccountLogItem_MergeAccountLogId')          
BEGIN
  ALTER TABLE [DATA_MergeAccountLogItem] WITH CHECK 
  ADD  CONSTRAINT [fk_DATA_MergeAccountLogItem_MergeAccountLogId] FOREIGN KEY([MergeAccountLogId])
  REFERENCES [DATA_MergeAccountLog] ([MergeAccountLogId])
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fesposito</ADDEDBY>
			<SQLVERSION>2195</SQLVERSION>
			<RMTRACKLINK>68811</RMTRACKLINK>
			<REASON> update CNF_Driver set 
   DriverAk = 'TDrvPrnZebraGeneric', 
   DllName = 'DrvPrnZebraGeneric.dll',
   Description = 'Zebra Generic Printer' 
 where FamilyType = 167  </REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT> update CNF_Driver set 
   DriverAk = 'TPrnZebraGeneric', 
   DllName = 'DrvPrnZebraGeneric.dll',
   Description = 'Zebra Generic Printer' 
 where FamilyType = 167  </SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>kdixon</ADDEDBY>
			<SQLVERSION>2194</SQLVERSION>
			<RMTRACKLINK>64619</RMTRACKLINK>
			<REASON>0 - 7 Drop Old Chart of Account and revenue recognition tables.
8 - 11 Recreate Chart of Account tables
12- 15 Recreate Revenue Recognition Tables
16 - 20 Create Foreign Keys for Chart of Account Tables
21 - Foreign Key RR_CNF_Validity
22-25 - Foreign Key RR_CNF_Product
26 - 41 - Foreign Key RR_DATA_Revenue</REASON>
			<TABLENAMES>COA_CNF_AccountType=COAAccountTypeId
COA_CNF_Account=COAAccountId
COA_CNF_AccountConfigItem=COAAccountConfigItemId
COA_CNF_AccountConfig=COAAccountConfigId
RR_DATA_Revenue=RevenueRecognitionDataId
RR_CNF_RevenueRecognitionRule=RevenueRecognitionRuleId
RR_CNF_Validity=RevenueRecognitionValidityId
RR_CNF_Product=RevenueRecognitionProductId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'RR_Data_Revenue')) 
DROP TABLE RR_Data_Revenue
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'rr_cnf_product')) 
DROP TABLE rr_cnf_product
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'rr_cnf_validity')) 
DROP TABLE rr_cnf_validity
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'COA_CNF_AccountConfigItem')) 
DROP TABLE COA_CNF_AccountConfigItem
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'COA_CNF_AccountConfig')) 
DROP TABLE COA_CNF_AccountConfig
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'rr_cnf_revenuerecognitionrule')) 
DROP TABLE rr_cnf_revenuerecognitionrule
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'COA_CNF_Account')) 
DROP TABLE COA_CNF_Account
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'COA_CNF_AccountType')) 
DROP TABLE COA_CNF_AccountType
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'COA_CNF_AccountType')
BEGIN
Create table [COA_CNF_AccountType]
(
	[COAAccountTypeId] Integer Identity(1,1) NOT NULL,
	[COAAccountTypeAK] Varchar(32) NOT NULL, UNIQUE ([COAAccountTypeAK]),
	[Code] Nvarchar(10) NOT NULL,
	[Name] Nvarchar(50) NULL,
	[Description] Nvarchar(100) NULL,
	[SystemAccount] Smallint NULL,
	[Enabled] Smallint NOT NULL,
Primary Key ([COAAccountTypeId])
) 
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'COA_CNF_Account')
BEGIN
Create table [COA_CNF_Account]
(
	[COAAccountId] Integer Identity(1,1) NOT NULL,
	[COAAccountTypeId] Integer NOT NULL,
	[ParentAccountId] Integer NULL,
	[COAAccountAK] Varchar(32) NOT NULL, UNIQUE ([COAAccountAK]),
	[Code] Nvarchar(10) NOT NULL,
	[Name] Nvarchar(50) NULL,
	[Description] Nvarchar(100) NULL,
	[SystemAccount] Smallint NOT NULL,
	[FromDate] Datetime NULL,
	[ToDate] Datetime NULL,
	[Enabled] Smallint NOT NULL,
Primary Key ([COAAccountId])
) 
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'COA_CNF_AccountConfigItem')
BEGIN
Create table [COA_CNF_AccountConfigItem]
(
	[COAAccountConfigItemId] Integer Identity(1,1) NOT NULL, UNIQUE ([COAAccountConfigItemId]),
	[COAAccountConfigId] Integer NOT NULL,
	[SiteId] Integer NOT NULL,
	[COAAccountId] Integer NOT NULL,
	[Value] Float NULL,
	[RemaningValues] Bit NULL,
Primary Key ([COAAccountConfigItemId])
)  
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'COA_CNF_AccountConfig')
BEGIN
	Create table [COA_CNF_AccountConfig]
	(
		[COAAccountConfigId] Integer Identity(1,1) NOT NULL, UNIQUE ([COAAccountConfigId]),
		[RevenueRecognitionRuleId] Integer NOT NULL,
	Primary Key ([COAAccountConfigId])
	) 
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'RR_DATA_Revenue')
BEGIN
Create table [RR_DATA_Revenue]
(
	[RevenueRecognitionDataId] Bigint Identity(1,1) NOT NULL, UNIQUE ([RevenueRecognitionDataId]),
	[COAAccountId] Integer NOT NULL,
	[RevenueRecognitionRuleId] Integer NOT NULL,
	[RRCode] Nvarchar(10) NULL,
	[RRCalcTypeWhen] Smallint NOT NULL,
	[RRCalcTypeWhere] Smallint NULL,
	[RRCalcTypeMethod] Smallint NOT NULL,
	[RRCalcTypePeriod] Smallint NOT NULL,
	[RRCalcTypeSplit] Smallint NOT NULL,
	[COAAccountConfigId] Integer NOT NULL,
	[COAAccountConfigItemId] Integer NOT NULL,
	[COAAccountType] Smallint NOT NULL,
	[COAAccountCode] Nvarchar(10) NULL,
	[TransactionId] Integer NOT NULL,
	[SaleId] Integer NOT NULL,
	[SaleItemId] Integer NOT NULL,
	[MatrixCellId] Integer NOT NULL,
	[MatrixCellCode] Varchar(32) NULL,
	[UsageId] Integer NULL,
	[TicketId] Integer NULL,
	[SiteId] Integer NOT NULL,
	[LocationId] Integer NULL,
	[OperatingAreaId] Integer NOT NULL,
	[WorkstationId] Integer NOT NULL,
	[UserGroupId] Integer NOT NULL,
	[UserId] Integer NOT NULL,
	[FCalcDate] Datetime NOT NULL,
	[FRevenueDate] Datetime NOT NULL,
	[Quantity] Integer Default 0 NOT NULL,
	[UnitAmount] Float NOT NULL,
	[GrossAmount] Float NOT NULL,
	[NetAmount] Float NOT NULL,
	[Price] Float NULL,
	[Percentage] Float NULL,
	[RemaningValues] Bit NULL,
	[RevenueAmount] Float NOT NULL,
Primary Key ([RevenueRecognitionDataId])
) 
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'RR_CNF_RevenueRecognitionRule')
BEGIN
Create table [RR_CNF_RevenueRecognitionRule]
(
	[RevenueRecognitionRuleId] Integer Identity(1,1) NOT NULL, UNIQUE ([RevenueRecognitionRuleId]),
	[RevenueRecognitionRuleAK] Varchar(32) NOT NULL, UNIQUE ([RevenueRecognitionRuleAK]),
	[Code] Nvarchar(10) NOT NULL,
	[Description] Nvarchar(100) NULL,
	[RRCalcTypeWhen] Smallint NOT NULL,
	[RRCalcTypeWhere] Smallint NULL,
	[RRCalcTypeMethod] Smallint NOT NULL,
	[RRCalcTypePeriod] Smallint NOT NULL,
	[RRCalcTypeSplit] Smallint NOT NULL,
	[FromDate] Datetime NULL,
	[ToDate] Datetime NULL,
	[FixedQuantity] Integer NULL,
	[CreationDate] Datetime NOT NULL,
	[LastUpdate] Datetime NOT NULL,
	[Enabled] Smallint NOT NULL,
Primary Key ([RevenueRecognitionRuleId])
)
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'RR_CNF_Validity')
BEGIN
Create table [RR_CNF_Validity]
(
	[RevenueRecognitionValidityId] Integer Identity(1,1) NOT NULL, UNIQUE ([RevenueRecognitionValidityId]),
	[RevenueRecognitionRuleId] Integer NOT NULL,
	[FromDate] Smalldatetime NOT NULL,
	[ToDate] Smalldatetime NOT NULL,
	[AlwaysVaild] Smallint Default 1 NOT NULL,
	[CreationDate] Datetime NOT NULL,
	[LastUpdate] Datetime NOT NULL,
	[Enabled] Smallint Default 1 NOT NULL,
Primary Key ([RevenueRecognitionValidityId])
) 
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'RR_CNF_Product')
BEGIN
Create table [RR_CNF_Product]
(
	[RevenueRecognitionProductId] Integer Identity(1,1) NOT NULL, UNIQUE ([RevenueRecognitionProductId]),
	[RevenueRecognitionRuleId] Integer NOT NULL,
	[MatrixSheetId] Integer NULL,
	[MatrixCellId] Integer NULL,
	[AttributeId] Integer NULL,
Primary Key ([RevenueRecognitionProductId])
) 
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'COA_CNF_Account'
	          AND CONSTRAINT_NAME = N'fk_COA_CNF_Account_COAAccountTypeId')          
BEGIN
  ALTER TABLE [COA_CNF_Account] WITH CHECK 
  ADD  CONSTRAINT [fk_COA_CNF_Account_COAAccountTypeId] FOREIGN KEY([COAAccountTypeId])
  REFERENCES [COA_CNF_AccountType] ([COAAccountTypeId])
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int  

EXEC Otn_Add_ForeingKey 
	@ForeingKeyTable = N'COA_CNF_AccountConfig', @ForeingKeyReferenceTable  = N'RR_CNF_RevenueRecognitionRule',
	@ForeingKeyColumn = N'RevenueRecognitionRuleId', @ForeingKeyReferenceColumn = N'RevenueRecognitionRuleId',
	@result = @retval OUTPUT
SELECT @retval;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int  

EXEC Otn_Add_ForeingKey 
	@ForeingKeyTable = N'COA_CNF_AccountConfigItem', @ForeingKeyReferenceTable  = N'COA_CNF_AccountConfig',
	@ForeingKeyColumn = N'COAAccountConfigId', @ForeingKeyReferenceColumn = N'COAAccountConfigId',
	@result = @retval OUTPUT
SELECT @retval;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int  

EXEC Otn_Add_ForeingKey 
	@ForeingKeyTable = N'COA_CNF_AccountConfigItem', @ForeingKeyReferenceTable  = N'CNF_Site',
	@ForeingKeyColumn = N'SiteId', @ForeingKeyReferenceColumn = N'SiteId',
	@result = @retval OUTPUT
SELECT @retval;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int  

EXEC Otn_Add_ForeingKey 
	@ForeingKeyTable = N'COA_CNF_AccountConfigItem', 
        @ForeingKeyReferenceTable  = N'COA_CNF_Account',
	@ForeingKeyColumn = N'COAAccountId', @ForeingKeyReferenceColumn = N'COAAccountId',
	@result = @retval OUTPUT
SELECT @retval;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int  

EXEC Otn_Add_ForeingKey 
	@ForeingKeyTable = N'RR_CNF_Validity', @ForeingKeyReferenceTable  = N'RR_CNF_RevenueRecognitionRule',
	@ForeingKeyColumn = N'RevenueRecognitionRuleId', @ForeingKeyReferenceColumn = N'RevenueRecognitionRuleId',
	@result = @retval OUTPUT
SELECT @retval;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int  

EXEC Otn_Add_ForeingKey 
	@ForeingKeyTable = N'RR_CNF_Product', @ForeingKeyReferenceTable  = N'RR_CNF_RevenueRecognitionRule',
	@ForeingKeyColumn = N'RevenueRecognitionRuleId', @ForeingKeyReferenceColumn = N'RevenueRecognitionRuleId',
	@result = @retval OUTPUT
SELECT @retval;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int 

EXEC Otn_Add_ForeingKey
	@ForeingKeyTable = N'RR_CNF_Product', @ForeingKeyReferenceTable  = N'CNF_MatrixSheet',
	@ForeingKeyColumn = N'MatrixSheetId', @ForeingKeyReferenceColumn = N'MatrixSheetId',
	@result = @retval OUTPUT
SELECT @retval;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int 

EXEC Otn_Add_ForeingKey 
	@ForeingKeyTable = N'RR_CNF_Product', @ForeingKeyReferenceTable  = N'CNF_MatrixCell',
	@ForeingKeyColumn = N'MatrixCellId', @ForeingKeyReferenceColumn = N'MatrixCellId',
	@result = @retval OUTPUT
SELECT @retval;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int 

EXEC Otn_Add_ForeingKey
	@ForeingKeyTable = N'RR_CNF_Product', @ForeingKeyReferenceTable  = N'CNF_Attribute',
	@ForeingKeyColumn = N'AttributeId', @ForeingKeyReferenceColumn = N'AttributeId',
	@result = @retval OUTPUT
SELECT @retval;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int  

EXEC Otn_Add_ForeingKey 
	@ForeingKeyTable = N'RR_DATA_Revenue', @ForeingKeyReferenceTable  = N'CNF_MatrixCell',
	@ForeingKeyColumn = N'MatrixCellId', @ForeingKeyReferenceColumn = N'MatrixCellId',
	@result = @retval OUTPUT
SELECT @retval;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int

EXEC Otn_Add_ForeingKey
	@ForeingKeyTable = N'RR_DATA_Revenue', @ForeingKeyReferenceTable  = N'DATA_Sale',
	@ForeingKeyColumn = N'SaleId', @ForeingKeyReferenceColumn = N'SaleId',
	@result = @retval OUTPUT
SELECT @retval;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int

EXEC Otn_Add_ForeingKey
	@ForeingKeyTable = N'RR_DATA_Revenue', @ForeingKeyReferenceTable  = N'DATA_SaleItem',
	@ForeingKeyColumn = N'SaleItemId', @ForeingKeyReferenceColumn = N'SaleItemId',
	@result = @retval OUTPUT
SELECT @retval;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int

EXEC Otn_Add_ForeingKey
	@ForeingKeyTable = N'RR_DATA_Revenue', @ForeingKeyReferenceTable  = N'DATA_Transaction',
	@ForeingKeyColumn = N'TransactionId', @ForeingKeyReferenceColumn = N'TransactionId',
	@result = @retval OUTPUT
SELECT @retval;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int

EXEC Otn_Add_ForeingKey
	@ForeingKeyTable = N'RR_DATA_Revenue', @ForeingKeyReferenceTable  = N'DATA_TicketUsage',
	@ForeingKeyColumn = N'UsageId', @ForeingKeyReferenceColumn = N'UsageId',
	@result = @retval OUTPUT
SELECT @retval;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int

EXEC Otn_Add_ForeingKey
	@ForeingKeyTable = N'RR_DATA_Revenue', @ForeingKeyReferenceTable  = N'DATA_Ticket',
	@ForeingKeyColumn = N'TicketId', @ForeingKeyReferenceColumn = N'TicketId',
	@result = @retval OUTPUT
SELECT @retval;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int

EXEC Otn_Add_ForeingKey
	@ForeingKeyTable = N'RR_DATA_Revenue', @ForeingKeyReferenceTable  = N'CNF_Site',
	@ForeingKeyColumn = N'SiteId', @ForeingKeyReferenceColumn = N'SiteId',
	@result = @retval OUTPUT
SELECT @retval;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int

EXEC Otn_Add_ForeingKey
	@ForeingKeyTable = N'RR_DATA_Revenue', @ForeingKeyReferenceTable  = N'CNF_Location',
	@ForeingKeyColumn = N'LocationId', @ForeingKeyReferenceColumn = N'LocationId',
	@result = @retval OUTPUT
SELECT @retval;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int

EXEC Otn_Add_ForeingKey
	@ForeingKeyTable = N'RR_DATA_Revenue', @ForeingKeyReferenceTable  = N'CNF_OperatingArea',
	@ForeingKeyColumn = N'OperatingAreaId', @ForeingKeyReferenceColumn = N'OperatingAreaId',
	@result = @retval OUTPUT
SELECT @retval;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int

EXEC Otn_Add_ForeingKey
	@ForeingKeyTable = N'RR_DATA_Revenue', @ForeingKeyReferenceTable  = N'CNF_Workstation',
	@ForeingKeyColumn = N'WorkstationId', @ForeingKeyReferenceColumn = N'WorkstationId',
	@result = @retval OUTPUT
SELECT @retval;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int

EXEC Otn_Add_ForeingKey
	@ForeingKeyTable = N'RR_DATA_Revenue', @ForeingKeyReferenceTable  = N'CNF_UserGroup',
	@ForeingKeyColumn = N'UserGroupId', @ForeingKeyReferenceColumn = N'UserGroupId',
	@result = @retval OUTPUT
SELECT @retval;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int

EXEC Otn_Add_ForeingKey
	@ForeingKeyTable = N'RR_DATA_Revenue', @ForeingKeyReferenceTable  = N'CNF_User',
	@ForeingKeyColumn = N'UserId', @ForeingKeyReferenceColumn = N'UserId',
	@result = @retval OUTPUT
SELECT @retval;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int

EXEC Otn_Add_ForeingKey
	@ForeingKeyTable = N'RR_DATA_Revenue', @ForeingKeyReferenceTable  = N'RR_CNF_RevenueRecognitionRule',
	@ForeingKeyColumn = N'RevenueRecognitionRuleId', @ForeingKeyReferenceColumn = N'RevenueRecognitionRuleId',
	@result = @retval OUTPUT
SELECT @retval;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int

EXEC Otn_Add_ForeingKey
	@ForeingKeyTable = N'RR_DATA_Revenue', @ForeingKeyReferenceTable  = N'COA_CNF_Account',
	@ForeingKeyColumn = N'COAAccountId', @ForeingKeyReferenceColumn = N'COAAccountId',
	@result = @retval OUTPUT
SELECT @retval;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int

EXEC Otn_Add_ForeingKey
	@ForeingKeyTable = N'RR_DATA_Revenue', @ForeingKeyReferenceTable  = N'COA_CNF_AccountConfig',
	@ForeingKeyColumn = N'COAAccountConfigId', @ForeingKeyReferenceColumn = N'COAAccountConfigId',
	@result = @retval OUTPUT
SELECT @retval;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int

EXEC Otn_Add_ForeingKey
	@ForeingKeyTable = N'RR_DATA_Revenue', @ForeingKeyReferenceTable  = N'COA_CNF_AccountConfigItem',
	@ForeingKeyColumn = N'COAAccountConfigItemId', @ForeingKeyReferenceColumn = N'COAAccountConfigItemId',
	@result = @retval OUTPUT
SELECT @retval;
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>2193</SQLVERSION>
			<RMTRACKLINK>66121</RMTRACKLINK>
			<REASON>Add Field SoccerLtaTaskId on Table SIAE_Event

[0] Add Field 
[1] Create foreign key table SIAE_CNF_SoccerLtaTask</REASON>
			<TABLENAMES>SIAE_Event=EventId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>

IF NOT EXISTS (SELECT * FROM sys.columns
               WHERE Name = N'SoccerLtaTaskId' AND
               Object_ID  = Object_ID(N'SIAE_Event'))
BEGIN
  ALTER TABLE SIAE_Event ADD SoccerLtaTaskId int NULL
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>
IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'SIAE_Event'
	          AND CONSTRAINT_NAME = N'fkSIAE_CNF_SoccerLtaTask_SIAE_Event_TaskId')          
BEGIN
  ALTER TABLE [SIAE_Event] WITH CHECK 
  ADD  CONSTRAINT [fkSIAE_CNF_SoccerLtaTask_SIAE_Event_TaskId] FOREIGN KEY([SoccerLtaTaskId])
  REFERENCES [SIAE_CNF_SoccerLtaTask] ([TaskId])
END

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>jlaguardia</ADDEDBY>
			<SQLVERSION>2192</SQLVERSION>
			<RMTRACKLINK>68714</RMTRACKLINK>
			<REASON>+Added DenyCreateOnPos  column (smallint ) for Vouchers. 0 = false, 1 = true. 
*default to 0/false since the option is to DENY creation.</REASON>
			<TABLENAMES>DATA_Voucher=VoucherId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'CreateOnPos' AND
                Object_ID  = Object_ID(N'DATA_Voucher'))
BEGIN
  ALTER TABLE DATA_Voucher ADD DenyCreateOnPos smallint 
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>kdixon</ADDEDBY>
			<SQLVERSION>2191</SQLVERSION>
			<RMTRACKLINK>64619</RMTRACKLINK>
			<REASON>0 - 7 Drop Old Chart of Account and revenue recognition tables.
8 - 11 Recreate Chart of Account tables
12- 15 Recreate Revenue Recognition Tables
16 - 20 Create Foreign Keys for Chart of Account Tables
21 - Foreign Key RR_CNF_Validity
22-25 - Foreign Key RR_CNF_Product
26 - 41 - Foreign Key RR_DATA_Revenue


			</REASON>
			<TABLENAMES>COA_CNF_AccountType=COAAccountTypeId
COA_CNF_Account=COAAccountId
COA_CNF_AccountConfigItem=COAAccountConfigItemId
COA_CNF_AccountConfig=COAAccountConfigId
RR_DATA_Revenue=RevenueRecognitionDataId
RR_CNF_RevenueRecognitionRule=RevenueRecognitionRuleId
RR_CNF_Validity=RevenueRecognitionValidityId
RR_CNF_Product=RevenueRecognitionProductId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'CNF_COA_Account')) 
DROP TABLE CNF_COA_Account
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'CNF_COA_AccountType')) 
DROP TABLE CNF_COA_AccountType
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'rr_data_revenue')) 
DROP TABLE rr_data_revenue
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'rr_cnf_product')) 
DROP TABLE rr_cnf_product
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'rr_cnf_validity')) 
DROP TABLE rr_cnf_validity
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'rr_cnf_costcenterconfigitem')) 
DROP TABLE rr_cnf_costcenterconfigitem
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'rr_cnf_costcenterconfig')) 
DROP TABLE rr_cnf_costcenterconfig
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'rr_cnf_revenuerecognition')) 
DROP TABLE rr_cnf_revenuerecognition
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'COA_CNF_AccountType')
BEGIN
	Create table [COA_CNF_AccountType]
	(
		[COAAccountTypeId] Integer Identity(1,1) NOT NULL,
		[COAAccountTypeAK] Varchar(32) NOT NULL, UNIQUE ([COAAccountTypeAK]),
		[Code] Nvarchar(10) NOT NULL,
		[Name] Nvarchar(50) NULL,
		[Description] Nvarchar(100) NULL,
                [SystemAccount] Smallint NOT NULL,
		[Enabled] Smallint NOT NULL,
	Primary Key ([COAAccountTypeId])
	) 
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'COA_CNF_Account')
BEGIN
	Create table [COA_CNF_Account]
	(
		[COAAccountId] Integer Identity(1,1) NOT NULL,
		[COAAccountTypeId] Integer NOT NULL,
		[ParentAccountId] Integer NULL,
		[COAAccountAK] Varchar(32) NOT NULL, UNIQUE ([COAAccountAK]),
		[Code] Nvarchar(10) NOT NULL,
		[Name] Nvarchar(50) NULL,
		[Description] Nvarchar(100) NULL,
		[SystemAccount] Smallint NOT NULL,
		[FromDate] Datetime NULL,
		[ToDate] Datetime NULL,
		[Enabled] Smallint NOT NULL,
	Primary Key ([COAAccountId])
	) 
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'COA_CNF_AccountConfigItem')
BEGIN
	Create table [COA_CNF_AccountConfigItem]
	(
		[COAAccountConfigItemId] Integer NOT NULL, UNIQUE ([COAAccountConfigItemId]),
		[COAAccountConfigId] Integer NOT NULL,
		[SiteId] Integer NOT NULL,
		[COAAccountId] Integer NOT NULL,
		[Value] Float NULL,
		[RemaningValues] Bit NULL,
	Primary Key ([COAAccountConfigItemId])
	) 
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'COA_CNF_AccountConfig')
BEGIN
	Create table [COA_CNF_AccountConfig]
	(
		[COAAccountConfigId] Integer NOT NULL, UNIQUE ([COAAccountConfigId]),
		[RevenueRecognitionRuleId] Integer NOT NULL,
	Primary Key ([COAAccountConfigId])
	) 
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'RR_DATA_Revenue')
BEGIN
	Create table [RR_DATA_Revenue]
	(
		[RevenueRecognitionDataId] Bigint NOT NULL, UNIQUE ([RevenueRecognitionDataId]),
		[COAAccountId] Integer NOT NULL,
		[RevenueRecognitionRuleId] Integer NOT NULL,
		[RRCode] Nvarchar(10) NULL,
		[RRCalcTypeWhen] Smallint NOT NULL,
		[RRCalcTypeWhere] Smallint NULL,
		[RRCalcTypeMethod] Smallint NOT NULL,
		[RRCalcTypePeriod] Smallint NOT NULL,
		[RRCalcTypeSplit] Smallint NOT NULL,
		[COAAccountConfigId] Integer NOT NULL,
		[COAAccountConfigItemId] Integer NOT NULL,
		[COAAccountType] Smallint NOT NULL,
		[COAAccountCode] Nvarchar(10) NULL,
		[TransactionId] Integer NOT NULL,
		[SaleId] Integer NOT NULL,
		[SaleItemId] Integer NOT NULL,
		[MatrixCellId] Integer NOT NULL,
		[MatrixCellCode] Varchar(32) NULL,
		[UsageId] Integer NULL,
		[TicketId] Integer NULL,
		[SiteId] Integer NOT NULL,
		[LocationId] Integer NULL,
		[OperatingAreaId] Integer NOT NULL,
		[WorkstationId] Integer NOT NULL,
		[UserGroupId] Integer NOT NULL,
		[UserId] Integer NOT NULL,
		[FCalcDate] Datetime NOT NULL,
		[FRevenueDate] Datetime NOT NULL,
		[Quantity] Integer Default 0 NOT NULL,
		[UnitAmount] Float NOT NULL,
		[GrossAmount] Float NOT NULL,
		[NetAmount] Float NOT NULL,
		[Price] Float NULL,
		[Percentage] Float NULL,
		[RemaningValues] Bit NULL,
		[RevenueAmount] Float NOT NULL,
	Primary Key ([RevenueRecognitionDataId])
	) 
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'RR_CNF_RevenueRecognitionRule')
BEGIN
	Create table [RR_CNF_RevenueRecognitionRule]
	(
		[RevenueRecognitionRuleId] Integer NOT NULL, UNIQUE ([RevenueRecognitionRuleId]),
		[RevenueRecognitionRuleAK] Varchar(32) NOT NULL, UNIQUE ([RevenueRecognitionRuleAK]),
		[Code] Nvarchar(10) NOT NULL,
		[Description] Nvarchar(100) NULL,
		[RRCalcTypeWhen] Smallint NOT NULL,
		[RRCalcTypeWhere] Smallint NULL,
		[RRCalcTypeMethod] Smallint NOT NULL,
		[RRCalcTypePeriod] Smallint NOT NULL,
		[RRCalcTypeSplit] Smallint NOT NULL,
		[FromDate] Datetime NULL,
		[ToDate] Datetime NULL,
		[FixedQuantity] Integer NULL,
		[CreationDate] Datetime NOT NULL,
		[LastUpdate] Datetime NOT NULL,
		[Enabled] Smallint NOT NULL,
	Primary Key ([RevenueRecognitionRuleId])
	)
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'RR_CNF_Validity')
BEGIN
	Create table [RR_CNF_Validity]
	(
		[RevenueRecognitionValidityId] Integer NOT NULL, UNIQUE ([RevenueRecognitionValidityId]),
		[RevenueRecognitionRuleId] Integer NOT NULL,
		[FromDate] Smalldatetime NOT NULL,
		[ToDate] Smalldatetime NOT NULL,
		[AlwaysVaild] Smallint Default 1 NOT NULL,
		[CreationDate] Datetime NOT NULL,
		[LastUpdate] Datetime NOT NULL,
		[Enabled] Smallint Default 1 NOT NULL,
	Primary Key ([RevenueRecognitionValidityId])
	) 
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'RR_CNF_Product')
BEGIN
	Create table [RR_CNF_Product]
	(
		[RevenueRecognitionProductId] Integer NOT NULL, UNIQUE ([RevenueRecognitionProductId]),
		[RevenueRecognitionRuleId] Integer NOT NULL,
		[MatrixSheetId] Integer NULL,
		[MatrixCellId] Integer NULL,
		[AttributeId] Integer NULL,
	Primary Key ([RevenueRecognitionProductId])
	)
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'COA_CNF_Account'
	          AND CONSTRAINT_NAME = N'fk_COA_CNF_Account_COAAccountTypeId')          
BEGIN
  ALTER TABLE [COA_CNF_Account] WITH CHECK 
  ADD  CONSTRAINT [fk_COA_CNF_Account_COAAccountTypeId] FOREIGN KEY([COAAccountTypeId])
  REFERENCES [COA_CNF_AccountType] ([COAAccountTypeId])
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int  

EXEC Otn_Add_ForeingKey 
	@ForeingKeyTable = N'COA_CNF_AccountConfig', @ForeingKeyReferenceTable  = N'RR_CNF_RevenueRecognitionRule',
	@ForeingKeyColumn = N'RevenueRecognitionRuleId', @ForeingKeyReferenceColumn = N'RevenueRecognitionRuleId',
	@result = @retval OUTPUT
SELECT @retval;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int  

EXEC Otn_Add_ForeingKey 
	@ForeingKeyTable = N'COA_CNF_AccountConfigItem', @ForeingKeyReferenceTable  = N'COA_CNF_AccountConfig',
	@ForeingKeyColumn = N'COAAccountConfigId', @ForeingKeyReferenceColumn = N'COAAccountConfigId',
	@result = @retval OUTPUT
SELECT @retval;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int  

EXEC Otn_Add_ForeingKey 
	@ForeingKeyTable = N'COA_CNF_AccountConfigItem', @ForeingKeyReferenceTable  = N'CNF_Site',
	@ForeingKeyColumn = N'SiteId', @ForeingKeyReferenceColumn = N'SiteId',
	@result = @retval OUTPUT
SELECT @retval;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int  

EXEC Otn_Add_ForeingKey 
	@ForeingKeyTable = N'COA_CNF_AccountConfigItem', @ForeingKeyReferenceTable  = N'COA_CNF_Account',
	@ForeingKeyColumn = N'COAAccountId', @ForeingKeyReferenceColumn = N'COAAccountId',
	@result = @retval OUTPUT
SELECT @retval;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int  

EXEC Otn_Add_ForeingKey 
	@ForeingKeyTable = N'RR_CNF_Validity', @ForeingKeyReferenceTable  = N'RR_CNF_RevenueRecognitionRule',
	@ForeingKeyColumn = N'RevenueRecognitionRuleId', @ForeingKeyReferenceColumn = N'RevenueRecognitionRuleId',
	@result = @retval OUTPUT
SELECT @retval;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int  

EXEC Otn_Add_ForeingKey 
	@ForeingKeyTable = N'RR_CNF_Product', @ForeingKeyReferenceTable  = N'RR_CNF_RevenueRecognitionRule',
	@ForeingKeyColumn = N'RevenueRecognitionRuleId', @ForeingKeyReferenceColumn = N'RevenueRecognitionRuleId',
	@result = @retval OUTPUT
SELECT @retval;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int 

EXEC Otn_Add_ForeingKey
	@ForeingKeyTable = N'RR_CNF_Product', @ForeingKeyReferenceTable  = N'CNF_MatrixSheet',
	@ForeingKeyColumn = N'MatrixSheetId', @ForeingKeyReferenceColumn = N'MatrixSheetId',
	@result = @retval OUTPUT
SELECT @retval;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int 

EXEC Otn_Add_ForeingKey 
	@ForeingKeyTable = N'RR_CNF_Product', @ForeingKeyReferenceTable  = N'CNF_MatrixCell',
	@ForeingKeyColumn = N'MatrixCellId', @ForeingKeyReferenceColumn = N'MatrixCellId',
	@result = @retval OUTPUT
SELECT @retval;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int 

EXEC Otn_Add_ForeingKey
	@ForeingKeyTable = N'RR_CNF_Product', @ForeingKeyReferenceTable  = N'CNF_Attribute',
	@ForeingKeyColumn = N'AttributeId', @ForeingKeyReferenceColumn = N'AttributeId',
	@result = @retval OUTPUT
SELECT @retval;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int  

EXEC Otn_Add_ForeingKey 
	@ForeingKeyTable = N'RR_DATA_Revenue', @ForeingKeyReferenceTable  = N'CNF_MatrixCell',
	@ForeingKeyColumn = N'MatrixCellId', @ForeingKeyReferenceColumn = N'MatrixCellId',
	@result = @retval OUTPUT
SELECT @retval;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int

EXEC Otn_Add_ForeingKey
	@ForeingKeyTable = N'RR_DATA_Revenue', @ForeingKeyReferenceTable  = N'DATA_Sale',
	@ForeingKeyColumn = N'SaleId', @ForeingKeyReferenceColumn = N'SaleId',
	@result = @retval OUTPUT
SELECT @retval;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int

EXEC Otn_Add_ForeingKey
	@ForeingKeyTable = N'RR_DATA_Revenue', @ForeingKeyReferenceTable  = N'DATA_SaleItem',
	@ForeingKeyColumn = N'SaleItemId', @ForeingKeyReferenceColumn = N'SaleItemId',
	@result = @retval OUTPUT
SELECT @retval;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int

EXEC Otn_Add_ForeingKey
	@ForeingKeyTable = N'RR_DATA_Revenue', @ForeingKeyReferenceTable  = N'DATA_Transaction',
	@ForeingKeyColumn = N'TransactionId', @ForeingKeyReferenceColumn = N'TransactionId',
	@result = @retval OUTPUT
SELECT @retval;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int

EXEC Otn_Add_ForeingKey
	@ForeingKeyTable = N'RR_DATA_Revenue', @ForeingKeyReferenceTable  = N'DATA_TicketUsage',
	@ForeingKeyColumn = N'UsageId', @ForeingKeyReferenceColumn = N'UsageId',
	@result = @retval OUTPUT
SELECT @retval;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int

EXEC Otn_Add_ForeingKey
	@ForeingKeyTable = N'RR_DATA_Revenue', @ForeingKeyReferenceTable  = N'DATA_Ticket',
	@ForeingKeyColumn = N'TicketId', @ForeingKeyReferenceColumn = N'TicketId',
	@result = @retval OUTPUT
SELECT @retval;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int

EXEC Otn_Add_ForeingKey
	@ForeingKeyTable = N'RR_DATA_Revenue', @ForeingKeyReferenceTable  = N'CNF_Site',
	@ForeingKeyColumn = N'SiteId', @ForeingKeyReferenceColumn = N'SiteId',
	@result = @retval OUTPUT
SELECT @retval;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int

EXEC Otn_Add_ForeingKey
	@ForeingKeyTable = N'RR_DATA_Revenue', @ForeingKeyReferenceTable  = N'CNF_Location',
	@ForeingKeyColumn = N'LocationId', @ForeingKeyReferenceColumn = N'LocationId',
	@result = @retval OUTPUT
SELECT @retval;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int

EXEC Otn_Add_ForeingKey
	@ForeingKeyTable = N'RR_DATA_Revenue', @ForeingKeyReferenceTable  = N'CNF_OperatingArea',
	@ForeingKeyColumn = N'OperatingAreaId', @ForeingKeyReferenceColumn = N'OperatingAreaId',
	@result = @retval OUTPUT
SELECT @retval;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int

EXEC Otn_Add_ForeingKey
	@ForeingKeyTable = N'RR_DATA_Revenue', @ForeingKeyReferenceTable  = N'CNF_Workstation',
	@ForeingKeyColumn = N'WorkstationId', @ForeingKeyReferenceColumn = N'WorkstationId',
	@result = @retval OUTPUT
SELECT @retval;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int

EXEC Otn_Add_ForeingKey
	@ForeingKeyTable = N'RR_DATA_Revenue', @ForeingKeyReferenceTable  = N'CNF_UserGroup',
	@ForeingKeyColumn = N'UserGroupId', @ForeingKeyReferenceColumn = N'UserGroupId',
	@result = @retval OUTPUT
SELECT @retval;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int

EXEC Otn_Add_ForeingKey
	@ForeingKeyTable = N'RR_DATA_Revenue', @ForeingKeyReferenceTable  = N'CNF_User',
	@ForeingKeyColumn = N'UserId', @ForeingKeyReferenceColumn = N'UserId',
	@result = @retval OUTPUT
SELECT @retval;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int

EXEC Otn_Add_ForeingKey
	@ForeingKeyTable = N'RR_DATA_Revenue', @ForeingKeyReferenceTable  = N'RR_CNF_RevenueRecognitionRule',
	@ForeingKeyColumn = N'RevenueRecognitionRuleId', @ForeingKeyReferenceColumn = N'RevenueRecognitionRuleId',
	@result = @retval OUTPUT
SELECT @retval;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int

EXEC Otn_Add_ForeingKey
	@ForeingKeyTable = N'RR_DATA_Revenue', @ForeingKeyReferenceTable  = N'COA_CNF_Account',
	@ForeingKeyColumn = N'COAAccountId', @ForeingKeyReferenceColumn = N'COAAccountId',
	@result = @retval OUTPUT
SELECT @retval;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int

EXEC Otn_Add_ForeingKey
	@ForeingKeyTable = N'RR_DATA_Revenue', @ForeingKeyReferenceTable  = N'COA_CNF_AccountConfig',
	@ForeingKeyColumn = N'COAAccountConfigId', @ForeingKeyReferenceColumn = N'COAAccountConfigId',
	@result = @retval OUTPUT
SELECT @retval;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int

EXEC Otn_Add_ForeingKey
	@ForeingKeyTable = N'RR_DATA_Revenue', @ForeingKeyReferenceTable  = N'COA_CNF_AccountConfigItem',
	@ForeingKeyColumn = N'COAAccountConfigItemId', @ForeingKeyReferenceColumn = N'COAAccountConfigItemId',
	@result = @retval OUTPUT
SELECT @retval;
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AndreaDavanzo</ADDEDBY>
			<SQLVERSION>2190</SQLVERSION>
			<RMTRACKLINK>68587</RMTRACKLINK>
			<REASON>Created table in order to store the VRO Control Panel
[1] Create table</REASON>
			<TABLENAMES>SIAE_VroControlPanel=VroControlPanelId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * 
               FROM INFORMATION_SCHEMA.TABLES 
               WHERE TABLE_SCHEMA = 'dbo' 
                AND  TABLE_NAME = 'SIAE_VroControlPanel')
BEGIN
  Create table [SIAE_VroControlPanel]
  (
	[VroControlPanelId] Integer Identity(1,1) NOT NULL,
	[VroPanel] Integer Default 0 NOT NULL,
	[VroConfiguration] xml NOT NULL,
  Primary Key ([VroControlPanelId])
  )
END </SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>marcoviscusi</ADDEDBY>
			<SQLVERSION>2189</SQLVERSION>
			<RMTRACKLINK>67857</RMTRACKLINK>
			<REASON>Added Column Active to DATA_SaleItem2Performance</REASON>
			<TABLENAMES>DATA_SaleItem2Performance=SaleItem2PerformanceId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Active' AND
                Object_ID  = Object_ID(N'DATA_SaleItem2Performance'))
BEGIN
  ALTER TABLE DATA_SaleItem2Performance ADD Active smallint NOT NULL Default 1
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>2188</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>Create configuration tables related to Export LTA for External Access Control (Soccer environment)

[0] - Create Table SIAE_CNF_SoccerLtaTask
[1] - Create Table SIAE_CNF_SoccerLtaTaskItem
[2] - Create Table SIAE_CNF_SoccerLtaTaskItemRule

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

FOREIGN KEY

[3] - Table SIAE_CNF_SoccerLtaTaskItem-&gt; SIAE_CNF_SoccerLtaTask-&gt; TaskId

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

[4] - Table SIAE_CNF_SoccerLtaTaskItemRule-&gt; SIAE_CNF_SoccerLtaTaskItem-&gt; TaskItemId

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

			</REASON>
			<TABLENAMES>SIAE_CNF_SoccerLtaTask=TaskId
SIAE_CNF_SoccerLtaTaskItem=TaskItemId
SIAE_CNF_SoccerLtaTaskItemRule=TaskItemRuleId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'SIAE_CNF_SoccerLtaTask')
BEGIN
	CREATE TABLE [dbo].[SIAE_CNF_SoccerLtaTask](
		TaskId [int] IDENTITY(1,1) NOT NULL,
		TaskCode [nvarchar](10) NOT NULL,
		TaskName [nvarchar](50) NOT NULL,
		TaskDesc [nvarchar](100) NULL,
		AccessControlSystem [smallint] NOT NULL,
		ItemPerRequest [smallint] NOT NULL,
		InsDateTime [datetime] NOT NULL,
		UpdDateTime [datetime] NOT NULL
PRIMARY KEY (TaskId) 
	)
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'SIAE_CNF_SoccerLtaTaskItem')
BEGIN
	CREATE TABLE [dbo].[SIAE_CNF_SoccerLtaTaskItem](
		TaskItemId [int] IDENTITY(1,1) NOT NULL,
		TaskId [int] NOT NULL,
		SendType [smallint] NOT NULL,
		Enabled [smallint] NOT NULL,
	PRIMARY KEY (TaskItemId) 
	)
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>
IF NOT EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'SIAE_CNF_SoccerLtaTaskItemRule')
BEGIN

	CREATE TABLE [dbo].SIAE_CNF_SoccerLtaTaskItemRule(
		TaskItemRuleId [int] IDENTITY(1,1) NOT NULL,
		TaskItemId [int] NOT NULL,
		Priority [smallint] NOT NULL,
		RuleType [smallint] NOT NULL,
		RuleFilter [smallint] NULL,
		Offset [smallint] NULL,
		HourFrom [dateTime] NULL,
		HourTo [dateTime] NULL,
		RetryIfError [smallint] NULL,
		ProbeActive [smallint] NULL,
		NotifyError [smallint] NULL
	PRIMARY KEY (TaskItemRuleId) 
	)

END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'SIAE_CNF_SoccerLtaTaskItem'
	          AND CONSTRAINT_NAME = N'fk_SIAE_CNF_SoccerLtaTask_TaskId')          
BEGIN
  ALTER TABLE [SIAE_CNF_SoccerLtaTaskItem] WITH CHECK 
  ADD  CONSTRAINT [fk_SIAE_CNF_SoccerLtaTask_TaskId] FOREIGN KEY([TaskId])
  REFERENCES [SIAE_CNF_SoccerLtaTask] ([TaskId])
END




				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'SIAE_CNF_SoccerLtaTaskItemRule'
	          AND CONSTRAINT_NAME = N'fk_SIAE_CNF_SoccerLtaTaskItem_TaskItemId')          
BEGIN
  ALTER TABLE [SIAE_CNF_SoccerLtaTaskItemRule] WITH CHECK 
  ADD  CONSTRAINT [fk_SIAE_CNF_SoccerLtaTaskItem_TaskItemId] FOREIGN KEY([TaskItemId])
  REFERENCES [SIAE_CNF_SoccerLtaTaskItem] ([TaskItemId])
END

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>2187</SQLVERSION>
			<RMTRACKLINK>66121</RMTRACKLINK>
			<REASON>Store procedure realigned on table SIAE_DATA_SoccerLtaTaskItem</REASON>
			<TABLENAMES>SIAE_DATA_SoccerLtaTaskItem=TaskItemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>select 1 from SIAE_DATA_SoccerLtaTaskItem with(nolock)
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>mkimball</ADDEDBY>
			<SQLVERSION>2186</SQLVERSION>
			<RMTRACKLINK>63489</RMTRACKLINK>
			<REASON>Add the ability for a client to upload a LOGO so that can be pulled into reports.

Adding default BOS logo to be used for reports.</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS(select 1 from ARC_Document where contextType = 5 and documentType = 0 and repositoryType = 5 and filename = 'bestunionlogo00001.png' and userid = 1 and version = 0)
   delete from ARC_Document where contextType = 5 and documentType = 0 and repositoryType = 5 and filename = 'bestunionlogo00001.png' and userid = 1 and version = 0

Declare @p1 VARCHAR(38)
Declare @p2 DateTime
Set @p1 = '{' + CONVERT(VARCHAR(36), NEWID()) + '}'
Set @p2 = GETDATE()

Insert INTO ARC_Document 
(DocumentAK, DocumentGUID, ContextType, LastUpdate, DocumentType, RepositoryType
 , FileName, UserId, Version, Description, DocData )
VALUES (NULL, @p1, 5, @p2, 0, 5, 'bestunionlogo00001.png', 1, 0, '', [encoded data, 43679 characters])
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Damiani</ADDEDBY>
			<SQLVERSION>2185</SQLVERSION>
			<RMTRACKLINK>68292</RMTRACKLINK>
			<REASON>Modify Table CNF_Driver
[0] Add column Enabled
[1] Update new column with 0 default value 
[2] Add NOT NULL ccolumn constraint</REASON>
			<TABLENAMES>CNF_Driver=DriverId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (
  SELECT * 
  FROM   sys.columns 
  WHERE  object_id = OBJECT_ID(N'[CNF_Driver]') 
         AND name = 'Enabled'
) ALTER TABLE CNF_Driver
  ADD Enabled smallint</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>UPDATE CNF_Driver SET Enabled = 1 WHERE Enabled IS NULL</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE CNF_Driver ALTER COLUMN Enabled smallint NOT NULL</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>2184</SQLVERSION>
			<RMTRACKLINK>66121</RMTRACKLINK>
			<REASON>
Table SIAE_DATA_SoccerLtaTaskItem 
[0] Remove Foreiign Key Task2PerfItemId -&gt; Table SIAE_SoccerLtaTask2PerfItem
[4] Remove field  Task2PerfItemId 
[1] Add new field SendType smallint
[2] Add new field  Task2PerfId Integer
[3] Add Foreiign key Task2PerfId -&gt; Table SIAE_SoccerLtaTask2Performance</REASON>
			<TABLENAMES>SIAE_DATA_SoccerLtaTaskItem=TaskItemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>
DECLARE @retval int  
EXEC Otn_Remove_ForeingKey
	@ForeingKeyTable = N'SIAE_DATA_SoccerLtaTaskItem',
	@ForeingKeyReferenceTable = N'SIAE_SoccerLtaTask2PerfItem',
	@ForeingKeyColumn = N'Task2PerfItemId',
	@result = @retval OUTPUT
SELECT @retval;</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>


IF NOT EXISTS (
  SELECT * 
  FROM   sys.columns 
  WHERE  object_id = OBJECT_ID(N'[dbo].[SIAE_DATA_SoccerLtaTaskItem]') 
         AND name = 'SendType'
)
BEGIN
	ALTER TABLE SIAE_DATA_SoccerLtaTaskItem
	ADD SendType smallint not null
END


				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>

IF NOT EXISTS (
  SELECT * 
  FROM   sys.columns 
  WHERE  object_id = OBJECT_ID(N'[dbo].[SIAE_DATA_SoccerLtaTaskItem]') 
         AND name = 'Task2PerfId'
)
BEGIN
	ALTER TABLE SIAE_DATA_SoccerLtaTaskItem
	ADD Task2PerfId int not null
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>
IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'SIAE_DATA_SoccerLtaTaskItem'
	        AND CONSTRAINT_NAME = N'fk_SIAE_DATA_SoccerLtaTaskItem_SIAE_SoccerLtaTask2Performance_Task2PerfId')          
BEGIN
  ALTER TABLE [SIAE_DATA_SoccerLtaTaskItem] WITH CHECK 
  ADD  CONSTRAINT [fk_SIAE_DATA_SoccerLtaTaskItem_SIAE_SoccerLtaTask2Performance_Task2PerfId] FOREIGN KEY([Task2PerfId])
  REFERENCES [SIAE_SoccerLtaTask2Performance] ([Task2PerfId])
END


				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>

IF EXISTS (
  SELECT * 
  FROM   sys.columns 
  WHERE  object_id = OBJECT_ID(N'[dbo].[SIAE_DATA_SoccerLtaTaskItem]') 
         AND name = 'Task2PerfItemId'
)
BEGIN
	ALTER TABLE SIAE_DATA_SoccerLtaTaskItem
	drop column Task2PerfItemId 
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>2183</SQLVERSION>
			<RMTRACKLINK>66121</RMTRACKLINK>
			<REASON>Create tables related to Export LTA for External Access Control (Soccer environment)
[0] - Create Table SIAE_SoccerLtaTask2Performance
[1] - Create Table SIAE_SoccerLtaTask2PerfItem
[2] - Create Table SIAE_SoccerLtaTask2PerfItemRule
[3] - Create Table SIAE_DATA_SoccerLtaTaskItem

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

FOREIGN KEY

[4] - Table SIAE_SoccerLtaTask2Performance -&gt; CNF_Performance -&gt; PerformanceId
[5] - Table SIAE_SoccerLtaTask2Performance -&gt; CNF_Workstation -&gt; WorkstationId
[6]  - Table SIAE_SoccerLtaTask2Performance -&gt; CNF_User -&gt; UserId

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

[7] - Table SIAE_SoccerLtaTask2PerfItem -&gt; SIAE_SoccerLtaTask2Performance  -&gt; Task2PerfId

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

[8] - Table SIAE_SoccerLtaTask2PerfItemRule -&gt; SIAE_SoccerLtaTask2PerfItem -&gt; Task2PerfItemId

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

[9] - Table SIAE_DATA_SoccerLtaTaskItem -&gt; DATA_Transaction -&gt; TransactionId
[10] - Table SIAE_DATA_SoccerLtaTaskItem -&gt; SIAE_SoccerLtaTask2PerfItem -&gt; Task2PerfItemId

			</REASON>
			<TABLENAMES>SIAE_SoccerLtaTask2Performance=Task2PerfId
SIAE_SoccerLtaTask2PerfItem=Task2PerfItemId
SIAE_SoccerLtaTask2PerfItemRule=PerfItemRuleId
SIAE_DATA_SoccerLtaTaskItem=TaskItemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>
IF NOT EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'SIAE_SoccerLtaTask2Performance')
BEGIN

Create table [SIAE_SoccerLtaTask2Performance]
(
	[Task2PerfId] Integer Identity(1,1) NOT NULL,
	[UserId] Integer NULL,
	[WorkstationId] Integer NULL,
	[PerformanceId] Integer NOT NULL,
	[PerfDateTime] Datetime NOT NULL,
	[PerformanceName] Nvarchar(100) NULL,
	[AccessControlSystem] Smallint NOT NULL,
	[ItemPerRequest] Smallint NOT NULL,
	[DateTimeFirstRun] Datetime NULL,
	[DateTimeLastRun] Datetime NULL,
Primary Key ([Task2PerfId])
) 

END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>
IF NOT EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'SIAE_SoccerLtaTask2PerfItem')
BEGIN

Create table [SIAE_SoccerLtaTask2PerfItem]
(
	[Task2PerfItemId] Integer Identity(1,1) NOT NULL,
	[Task2PerfId] Integer NOT NULL,
	[SendType] Smallint NOT NULL,
	[Active] Smallint NOT NULL,
Primary Key ([Task2PerfItemId])
) 

END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>
IF NOT EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'SIAE_SoccerLtaTask2PerfItemRule')
BEGIN

Create table [SIAE_SoccerLtaTask2PerfItemRule]
(
	[PerfItemRuleId] Integer Identity(1,1) NOT NULL,
	[Task2PerfItemId] Integer NOT NULL,
	[Priority] Smallint NOT NULL,
	[RuleType] Smallint NOT NULL,
	[RuleFilter] Smallint NULL,
	[Offset] Smallint NULL,
	[HourFrom] Datetime NULL,
	[HourTo] Datetime NULL,
	[ProbeActive] Smallint NOT NULL,
Primary Key ([PerfItemRuleId])
) 

END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>
IF NOT EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'SIAE_DATA_SoccerLtaTaskItem')
BEGIN

Create table [SIAE_DATA_SoccerLtaTaskItem]
(
	[TaskItemId] Integer Identity(1,1) NOT NULL,
	[TransactionId] Integer NULL,
	[Task2PerfItemId] Integer NOT NULL,
	[ReferenceTable] Smallint NOT NULL,
	[ReferenceId] Integer NOT NULL,
	[UpdateCount] Smallint NOT NULL,
	[DateTimeLastUpdate] Datetime NOT NULL,
	[LastRequestStatus] Smallint NOT NULL,
	[LastResponseStatus] Integer NULL,
	[DateTimeLastRequest] Datetime NULL,
	[LastRequestXml] Nvarchar(MAX) NULL,
	[DateTimeLastResponse] Datetime NULL,
	[LastResponseXml] Nvarchar(MAX) NULL,
Primary Key ([TaskItemId])
)

END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>
IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'SIAE_SoccerLtaTask2Performance'
	          AND CONSTRAINT_NAME = N'fk_CNF_Performance_PerformanceId')          
BEGIN
  ALTER TABLE [SIAE_SoccerLtaTask2Performance] WITH CHECK 
  ADD  CONSTRAINT [fk_CNF_Performance_PerformanceId] FOREIGN KEY([PerformanceId])
  REFERENCES [CNF_Performance] ([PerformanceId])
END




				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'SIAE_SoccerLtaTask2Performance'
	          AND CONSTRAINT_NAME = N'fk_CNF_Workstation_WorkstationId')          
BEGIN
  ALTER TABLE [SIAE_SoccerLtaTask2Performance] WITH CHECK 
  ADD  CONSTRAINT [fk_CNF_Workstation_WorkstationId] FOREIGN KEY([WorkstationId])
  REFERENCES [CNF_Workstation] ([WorkstationId])
END

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'SIAE_SoccerLtaTask2Performance'
	          AND CONSTRAINT_NAME = N'fk_CNF_User_UserId')          
BEGIN
  ALTER TABLE [SIAE_SoccerLtaTask2Performance] WITH CHECK 
  ADD  CONSTRAINT [fk_CNF_User_UserId] FOREIGN KEY([UserId])
  REFERENCES [CNF_User] ([UserId])
END

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'SIAE_SoccerLtaTask2PerfItem'
	          AND CONSTRAINT_NAME = N'fk_SIAE_SoccerLtaTask2Performance_Task2PerfId')          
BEGIN
  ALTER TABLE [SIAE_SoccerLtaTask2PerfItem] WITH CHECK 
  ADD  CONSTRAINT [fk_SIAE_SoccerLtaTask2Performance_Task2PerfId] FOREIGN KEY([Task2PerfId])
  REFERENCES [SIAE_SoccerLtaTask2Performance] ([Task2PerfId])
END


				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>
IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'SIAE_SoccerLtaTask2PerfItemRule'
	          AND CONSTRAINT_NAME = N'fk_SIAE_SoccerLtaTask2PerfItem_Task2PerfItemId')          
BEGIN
  ALTER TABLE [SIAE_SoccerLtaTask2PerfItemRule] WITH CHECK 
  ADD  CONSTRAINT [fk_SIAE_SoccerLtaTask2PerfItem_Task2PerfItemId] FOREIGN KEY([Task2PerfItemId])
  REFERENCES [SIAE_SoccerLtaTask2PerfItem] ([Task2PerfItemId])
END



				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>
IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'SIAE_DATA_SoccerLtaTaskItem'
	          AND CONSTRAINT_NAME = N'fk_DATA_Transaction_TransactionId')          
BEGIN
  ALTER TABLE [SIAE_DATA_SoccerLtaTaskItem] WITH CHECK 
  ADD  CONSTRAINT [fk_DATA_Transaction_TransactionId] FOREIGN KEY([TransactionId])
  REFERENCES [DATA_Transaction] ([TransactionId])
END




				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>
IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'SIAE_DATA_SoccerLtaTaskItem'
	          AND CONSTRAINT_NAME = N'fk_SIAE_DATA_SoccerLtaTaskItem_SIAE_SoccerLtaTask2PerfItem_Task2PerfItemId')          
BEGIN
  ALTER TABLE [SIAE_DATA_SoccerLtaTaskItem] WITH CHECK 
  ADD  CONSTRAINT [fk_SIAE_DATA_SoccerLtaTaskItem_SIAE_SoccerLtaTask2PerfItem_Task2PerfItemId] FOREIGN KEY([Task2PerfItemId])
  REFERENCES [SIAE_SoccerLtaTask2PerfItem] ([Task2PerfItemId])
END



				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>kdixon</ADDEDBY>
			<SQLVERSION>2182</SQLVERSION>
			<RMTRACKLINK>64619</RMTRACKLINK>
			<REASON>Added Startdate and EndDate to cnf_coa_account</REASON>
			<TABLENAMES>CNF_COA_Account=AccountId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'StartDate' AND
                Object_ID  = Object_ID(N'CNF_COA_Account'))
BEGIN
	Alter table CNF_COA_Account
	ADD StartDate datetime NULL
End
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'EndDate' AND
                Object_ID  = Object_ID(N'CNF_COA_Account'))
BEGIN
	Alter table CNF_COA_Account
	ADD EndDate datetime NULL
End

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>mkimball</ADDEDBY>
			<SQLVERSION>2181</SQLVERSION>
			<RMTRACKLINK>63489</RMTRACKLINK>
			<REASON>[0] Added FK from CNF_DmgCategory to CNF_Site
[1] Added FK from CNF_DmgCategory to CNF_System</REASON>
			<TABLENAMES>CNF_Site=SiteId
CNF_System=SystemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'DmgCategoryId' AND
                Object_ID  = Object_ID(N'CNF_Site'))
BEGIN
  ALTER TABLE CNF_Site ADD DmgCategoryId Integer NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_Site'
	          AND CONSTRAINT_NAME = N'fk_CNF_Site_DmgCategoryId')          
BEGIN
  ALTER TABLE [CNF_Site] WITH CHECK 
  ADD  CONSTRAINT [fk_CNF_Site_DmgCategoryId] FOREIGN KEY([DmgCategoryId])
  REFERENCES [CNF_DmgCategory] ([DmgCategoryId])
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'DmgCategoryId' AND
                Object_ID  = Object_ID(N'CNF_System'))
BEGIN
  ALTER TABLE CNF_System ADD DmgCategoryId Integer NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_System'
	          AND CONSTRAINT_NAME = N'fk_CNF_System_DmgCategoryId')          
BEGIN
  ALTER TABLE [CNF_System] WITH CHECK 
  ADD  CONSTRAINT [fk_CNF_System_DmgCategoryId] FOREIGN KEY([DmgCategoryId])
  REFERENCES [CNF_DmgCategory] ([DmgCategoryId])
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AndreaDavanzo</ADDEDBY>
			<SQLVERSION>2180</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>Create table DATA_Media2Performances
[0] Create table
[1] Create foreign key DATA_Media
[2] Create foreign key CNF_Performance
[3] Create foreign key DATA_Account
[4] Create index MediaId and PeformanceId
[5] Create index MediaId, PerformanceId and AccountId
[6] Create index MediaId and AccountId</REASON>
			<TABLENAMES>DATA_Media2Performances=Media2PerformancesId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT (EXISTS (SELECT * 
                FROM INFORMATION_SCHEMA.TABLES 
                WHERE TABLE_SCHEMA = 'dbo' 
                 AND  TABLE_NAME = 'DATA_Media2Performances'))
BEGIN                                                 
  Create table [DATA_Media2Performances]
  (
	[Media2PerformancesId] Integer Identity(1,1) NOT NULL,
	[MediaId] Integer NOT NULL,
	[PerformanceId] Integer NOT NULL,
	[AccountId] Integer NOT NULL,
	[VoidType] Smallint Default 0 NOT NULL,
  Primary Key ([Media2PerformancesId])
  )
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int  
EXEC Otn_Add_ForeingKey 
	@ForeingKeyTable = N'DATA_Media2Performances', @ForeingKeyReferenceTable  = N'DATA_Media',
	@ForeingKeyColumn = N'MediaId', @ForeingKeyReferenceColumn = N'MediaId',
	@result = @retval OUTPUT
SELECT @retval;</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int  
EXEC Otn_Add_ForeingKey 
	@ForeingKeyTable = N'DATA_Media2Performances', @ForeingKeyReferenceTable  = N'CNF_Performance',
	@ForeingKeyColumn = N'PerformanceId', @ForeingKeyReferenceColumn = N'PerformanceId',
	@result = @retval OUTPUT
SELECT @retval;</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int  
EXEC Otn_Add_ForeingKey 
	@ForeingKeyTable = N'DATA_Media2Performances', @ForeingKeyReferenceTable  = N'DATA_Account',
	@ForeingKeyColumn = N'AccountId', @ForeingKeyReferenceColumn = N'AccountId',
	@result = @retval OUTPUT
SELECT @retval;</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * 
               FROM sys.indexes  
               WHERE name='Idx_DATA_M2P_Media_Perf' AND object_id = OBJECT_ID('DATA_Media2Performances'))
BEGIN
  Create Index [Idx_DATA_M2P_Media_Perf] ON [DATA_Media2Performances] ([MediaId] ,[PerformanceId] )
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * 
               FROM sys.indexes  
               WHERE name='Idx_DATA_M2P_Media_Perf_Account' AND object_id = OBJECT_ID('DATA_Media2Performances'))
BEGIN
  Create Index [Idx_DATA_M2P_Media_Perf_Account] ON [DATA_Media2Performances] ([MediaId] ,[PerformanceId] ,[AccountId] )
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * 
               FROM sys.indexes  
               WHERE name='Idx_DATA_M2P_Media_Account' AND object_id = OBJECT_ID('DATA_Media2Performances'))
BEGIN
  Create Index [Idx_DATA_M2P_Media_Account] ON [DATA_Media2Performances] ([MediaId] ,[AccountId] )
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>pdalben</ADDEDBY>
			<SQLVERSION>2179</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>Reverted add cnew column</REASON>
			<TABLENAMES>CNF_PromotionItemRule=PromotionItemRuleId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
               WHERE Name = N'BasedOnValidity' AND
               Object_ID  = Object_ID(N'CNF_PromotionItemRule'))
BEGIN
  ALTER TABLE CNF_PromotionItemRule DROP COLUMN BasedOnValidity
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>pdalben</ADDEDBY>
			<SQLVERSION>2178</SQLVERSION>
			<RMTRACKLINK>66842</RMTRACKLINK>
			<REASON>empty</REASON>
			<TABLENAMES>CNF_PromotionItemRule=PromotionItemRuleId</TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>kdixon</ADDEDBY>
			<SQLVERSION>2177</SQLVERSION>
			<RMTRACKLINK>64619</RMTRACKLINK>
			<REASON>Adding ParentAccountId and SystemAccount columns to the table CNF_COA_Account</REASON>
			<TABLENAMES>CNF_COA_Account=AccountId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (
  SELECT * 
  FROM   sys.columns 
  WHERE  object_id = OBJECT_ID(N'[dbo].[CNF_COA_Account]') 
         AND name = 'ParentAccountID'
)
BEGIN
	ALTER TABLE CNF_COA_Account
	ADD ParentAccountID int null
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (
  SELECT * 
  FROM   sys.columns 
  WHERE  object_id = OBJECT_ID(N'[dbo].[CNF_COA_Account]') 
         AND name = 'SystemAccount'
)
BEGIN
	ALTER TABLE CNF_COA_Account
	ADD SystemAccount int not null default 0
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>2176</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>--CNF_MatrixCell2Delivery
[0] Drop table CNF_MatrixCell2Delivery
[1] Recreate Table CNF_MatrixCell2Delivery
[2] Add FK on Delivery
[3] Add FK on MatrixCell

--CNF_Delivery
			</REASON>
			<TABLENAMES>CNF_MatrixCell2Delivery=MatrixCell2DeliveryId
CNF_Delivery=DeliveryId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>drop table CNF_MatrixCell2Delivery</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_MatrixCell2Delivery]
(
	[MatrixCell2DeliveryId] Integer Identity(1,1) NOT NULL, UNIQUE ([MatrixCell2DeliveryId]),
	[MatrixCellId] Integer NOT NULL,
	[DeliveryId] Integer NOT NULL,
Primary Key ([MatrixCell2DeliveryId])
) </SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> Alter table CNF_MatrixCell2Delivery 
 add  foreign key(DeliveryId) references CNF_Delivery (DeliveryId)</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_MatrixCell2Delivery 
  add  foreign key(MatrixCellId) references CNF_MatrixCell (MatrixCellId)</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Delivery
  add ForceFlag Smallint NOT NULL default 0</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Delivery
 add Approved Smallint NOT NULL default 0



				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> alter table CNF_Delivery
   add Paid Smallint NOT NULL default 0</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> alter table CNF_Delivery
   add	Encode Smallint NOT NULL default 0</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> alter table CNF_Delivery
 add Validated Smallint NOT NULL default 0</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> alter table CNF_Delivery
   add Completed Smallint NOT NULL default 0</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>dapicella</ADDEDBY>
			<SQLVERSION>2175</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>Add Rolling Days Discount</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF not EXISTS (SELECT * FROM CNF_Promotion
                WHERE PromotionType = 400)
BEGIN
INSERT INTO CNF_Promotion
           (Description
           ,Active
           ,Code
           ,PromotionType
           ,CreatableOnPos
           ,SupervisorOverride)
     VALUES
           ('ROLLING DAYS DISCOUNT',
		     1,
			 'ROLLINGDAYS',
			 400,
			 0,
			 0 )

INSERT INTO CNF_PromotionItem
           (PromotionId
           ,Description
           ,RuleType)
     VALUES
           ((SELECT Promotionid from CNF_Promotion where PromotionType = 400),
            'Rolling Days Discount',
            'Advanced')

INSERT INTO CNF_PromotionItemRule
           (PromotionItemId
           ,AnyProduct
           ,ApplyDiscountToAllItem)
     VALUES
           (( SELECT top 1 PromotionItemId from CNF_PromotionItem order by PromotionItemId desc )
		   ,0
		   ,0)

END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AndreaDavanzo</ADDEDBY>
			<SQLVERSION>2174</SQLVERSION>
			<RMTRACKLINK>61570</RMTRACKLINK>
			<REASON>Created new table SIAE_VroAccounts
0) Create table
1) FK
2) Create index</REASON>
			<TABLENAMES>SIAE_VroAccounts=VroAccountsId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'SIAE_VroAccounts'))        
BEGIN                                                 
  Create table [SIAE_VroAccounts]
  (
	[VroAccountsId] Integer Identity(1,1) NOT NULL,
	[AccountId] Integer NOT NULL,
	[VroId] Nvarchar(10) NOT NULL,
  Primary Key ([VroAccountsId])
  )
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int  
EXEC Otn_Add_ForeingKey 
	@ForeingKeyTable = N'SIAE_VroAccounts', @ForeingKeyReferenceTable  = N'DATA_Account',
	@ForeingKeyColumn = N'AccountId', @ForeingKeyReferenceColumn = N'AccountId',
	@result = @retval OUTPUT
SELECT @retval;</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * 
               FROM sys.indexes  
               WHERE name='Idx_DATA_Account_VroAccount' AND object_id = OBJECT_ID('SIAE_VroAccounts'))
BEGIN
  Create Index [Idx_DATA_Account_VroAccount] ON [SIAE_VroAccounts] ([AccountId] ,[VroId] )
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>pdalben</ADDEDBY>
			<SQLVERSION>2173</SQLVERSION>
			<RMTRACKLINK>61942</RMTRACKLINK>
			<REASON>CNF_PaymentMethod added new field
0 - MaximumAmount
			</REASON>
			<TABLENAMES>CNF_PaymentMethod=PaymentMethodId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
               WHERE Name = N'MaximumAmount' AND
               Object_ID  = Object_ID(N'CNF_PaymentMethod'))
BEGIN
  ALTER TABLE CNF_PaymentMethod ADD MaximumAmount Float NULL
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>2172</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>Rename wrong Key Name</REASON>
			<TABLENAMES>CNF_MatrixCell2Delivery=MatrixCell2DeliveryId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>EXEC sp_rename 'CNF_MatrixCell2Delivery.MatrixCell2DelieveyId', 'MatrixCell2Deliveryid', 'COLUMN';  
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>2171</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>[CNF_MatrixCell2Delivery]
[0] create Table
[1] add FK DeliveryId
[2] add FK MatrixCellid
[CNF_Delivery]
[3] Add field MatrixCellId as null
[4] Add FK on MatrixCellId
[6] update MatrixcellId
[5] Add field MatrixCellId as not null

			</REASON>
			<TABLENAMES>CNF_Delivery=DeliveryId
CNF_MatrixCell2Delivery=MatrixCell2DelieveyId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT> Create table CNF_MatrixCell2Delivery
(
	MatrixCell2DelieveyId Integer Identity(1,1) NOT NULL, UNIQUE ([MatrixCell2DelieveyId]),
	MatrixCellId Integer NOT NULL,
	DeliveryId Integer NOT NULL,
Primary Key (MatrixCell2DelieveyId)
) </SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> Alter table CNF_MatrixCell2Delivery 
 add  foreign key(DeliveryId) references CNF_Delivery (DeliveryId)
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_MatrixCell2Delivery 
  add  foreign key(MatrixCellId) references CNF_MatrixCell (MatrixCellId)
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Delivery
  add MatrixCellId Integer NULL</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_Delivery 
  add  foreign key(MatrixCellId) references CNF_MatrixCell (MatrixCellId) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_Delivery set matrixCellid = (select top 1 MatrixCellId from CNF_MatrixCell)</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> alter table CNF_Delivery
   alter column MatrixCellId Integer NOT NULL</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>2170</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>CNF_Delivery
[0] add field enabled null
[1] set default value
[2] set enabled as not null
[3] add Name </REASON>
			<TABLENAMES>CNF_Delivery=DeliveryId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT> alter table CNF_Delivery 
   add Enabled integer null</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_Delivery 
Set Enabled = 1</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Delivery 
  alter column Enabled integer not null</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>  alter table CNF_Delivery 
   add Name Nvarchar(50) NULL</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> update CNF_Delivery 
Set Name = Code</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Delivery 
  alter column Name Nvarchar(50) not null</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>kdixon</ADDEDBY>
			<SQLVERSION>2169</SQLVERSION>
			<RMTRACKLINK>64619</RMTRACKLINK>
			<REASON>Chart of Accounts with Revenue Recognition Project

Delete and recreate of wrong patch 2166</REASON>
			<TABLENAMES>CNF_COA_AccountType=AccountTypeId
CNF_COA_Account=AccountId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'CNF_COA_Account')) 
DROP TABLE CNF_COA_Account
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'CNF_COA_AccountType')) 
DROP TABLE CNF_COA_AccountType
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_COA_AccountType]
(
	[AccountTypeId] Integer Identity(1,1) NOT NULL,
	[AccountTypeAK] Varchar(32) NOT NULL, UNIQUE ([AccountTypeAK]),
	[Code] Nvarchar(10) NOT NULL,
	[Name] Nvarchar(50) NULL,
	[Description] Nvarchar(100) NULL,
	[Enabled] Smallint NOT NULL,
Primary Key ([AccountTypeId])
)
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_COA_Account]
(
	[AccountId] Integer Identity(1,1) NOT NULL,
	[AccountTypeId] Integer NOT NULL,
	[AccountAK] Varchar(32) NOT NULL, UNIQUE ([AccountAK]),
	[Code] Nvarchar(10) NOT NULL,
	[Name] Nvarchar(50) NULL,
	[Description] Nvarchar(100) NULL,
	[Enabled] Smallint NOT NULL,
Primary Key ([AccountId])
)
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_COA_Account'
	          AND CONSTRAINT_NAME = N'fk_CNF_COA_Account_AccountTypeId')          
BEGIN
  ALTER TABLE [CNF_COA_Account] WITH CHECK 
  ADD  CONSTRAINT [fk_CNF_COA_Account_AccountTypeId] FOREIGN KEY([AccountTypeId])
  REFERENCES [CNF_COA_AccountType] ([AccountTypeId])
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>mkimball</ADDEDBY>
			<SQLVERSION>2168</SQLVERSION>
			<RMTRACKLINK>67696</RMTRACKLINK>
			<REASON>Add Enabled field to the CNF_Merchant</REASON>
			<TABLENAMES>CNF_Merchant=MerchantId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
  WHERE Name = N'Enabled' AND
        Object_ID  = Object_ID(N'CNF_Merchant'))
BEGIN
  ALTER TABLE CNF_Merchant ADD Enabled Smallint NOT NULL DEFAULT 1
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>jlaguardia</ADDEDBY>
			<SQLVERSION>2167</SQLVERSION>
			<RMTRACKLINK>65598</RMTRACKLINK>
			<REASON>Removed null and default constraints from ResetFlag</REASON>
			<TABLENAMES>DATA_AptRotationCount=AptRotationCountId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @Command nvarchar(max)

SELECT @Command = 'ALTER TABLE DATA_AptRotationCount drop constraint ' + name
 from sys.default_constraints
 where parent_object_id = object_id('DATA_AptRotationCount')
  and parent_column_id = columnproperty(object_id('DATA_AptRotationCount'), 'ResetFlag', 'ColumnId')

IF @Command is not null
    EXECUTE sp_executeSQL @Command  </SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>  IF EXISTS (SELECT * FROM sys.columns
               WHERE Name = N'ResetFlag' AND
               Object_ID  = Object_ID(N'DATA_AptRotationCount'))
  BEGIN
    ALTER TABLE DATA_AptRotationCount ALTER COLUMN ResetFlag smallint NULL
  END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>kdixon</ADDEDBY>
			<SQLVERSION>2166</SQLVERSION>
			<RMTRACKLINK>64619</RMTRACKLINK>
			<REASON>Chart of Accounts with Revenue Recognition Project

Deleted and recreated again in patch 2169</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>  IF NOT (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'CNF_COA_AccountType'))

BEGIN

Create table [CNF_COA_AccountType]
(
	[AccountTypeId] Integer Identity(1,1) NOT NULL,
	[AccountTypeAK] Varchar(32) NOT NULL, UNIQUE ([AccountTypeAK]),
	[AccountTypeCode] Varchar(10) NOT NULL,
	[AccountTypeDescription] Nvarchar(100) NULL,
	[Enabled] Smallint NOT NULL,
Primary Key ([AccountTypeId])
) 

END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'CNF_COA_Account'))

BEGIN

Create table [CNF_COA_Account]
(
	[AccountId] Integer Identity(1,1) NOT NULL,
	[AccountTypeId] Integer NOT NULL,
	[AccountAK] Varchar(32) NOT NULL, UNIQUE ([AccountAK]),
	[AccountCode] Varchar(10) NOT NULL,
	[AccountDescription] Nvarchar(100) NULL,
	[Enabled] Smallint NOT NULL,
Primary Key ([AccountId],[AccountTypeId])
) 

END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_COA_Account'
	          AND CONSTRAINT_NAME = N'fk_CNF_COA_Account_AccountTypeId')          
BEGIN
	ALTER TABLE [CNF_COA_Account]  WITH CHECK 
	ADD  CONSTRAINT [fk_CNF_COA_Account_AccountTypeId] FOREIGN KEY([AccountTypeId])
	REFERENCES [CNF_COA_AccountType] ([AccountTypeId])
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>smcdonald</ADDEDBY>
			<SQLVERSION>2165</SQLVERSION>
			<RMTRACKLINK>66119</RMTRACKLINK>
			<REASON>Remove Default from "Obsolete" column in CNF_Driver</REASON>
			<TABLENAMES>CNF_Driver=DriverId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @Command nvarchar(max)

SELECT @Command = 'ALTER TABLE CNF_Driver drop constraint ' + name
 from sys.default_constraints
 where parent_object_id = object_id('CNF_Driver')
  and parent_column_id = columnproperty(object_id('CNF_Driver'), 'Obsolete', 'ColumnId')

IF @Command is not null
    EXECUTE sp_executeSQL @Command  </SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>jlaguardia</ADDEDBY>
			<SQLVERSION>2164</SQLVERSION>
			<RMTRACKLINK>65598</RMTRACKLINK>
			<REASON>Add ResetFlag column to DATA_AptRotationCount</REASON>
			<TABLENAMES>DATA_AptRotationCount=AptRotationCountId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>  IF NOT EXISTS (SELECT * FROM sys.columns
               WHERE Name = N'ResetFlag' AND
               Object_ID  = Object_ID(N'DATA_AptRotationCount'))
  BEGIN
    ALTER TABLE DATA_AptRotationCount ADD ResetFlag SmallInt NOT NULL DEFAULT 0
  END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>  UPDATE DATA_AptRotationCount
    SET ResetFlag = 0
  WHERE ResetFlag IS NULL</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Steve McDonald</ADDEDBY>
			<SQLVERSION>2163</SQLVERSION>
			<RMTRACKLINK>66119</RMTRACKLINK>
			<REASON>Add column "Obsolete" to CNF_Driver</REASON>
			<TABLENAMES>CNF_Driver=DriverId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
               WHERE Name = N'Obsolete' AND
               Object_ID  = Object_ID(N'CNF_Driver'))
BEGIN
  ALTER TABLE CNF_Driver ADD Obsolete SmallInt NULL DEFAULT 0
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>UPDATE CNF_Driver
SET Obsolete = 0
WHERE Obsolete IS NULL</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Federico Caramella</ADDEDBY>
			<SQLVERSION>2162</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>steve missing ..</REASON>
			<TABLENAMES>CNF_Driver=DriverId</TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Programmatore</ADDEDBY>
			<SQLVERSION>2161</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.11.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************
			</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Programmatore</ADDEDBY>
			<SQLVERSION>2160</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.11.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************
			</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Programmatore</ADDEDBY>
			<SQLVERSION>2159</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.11.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************
			</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Programmatore</ADDEDBY>
			<SQLVERSION>2158</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.11.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************
			</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Programmatore</ADDEDBY>
			<SQLVERSION>2157</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.11.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************
			</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Programmatore</ADDEDBY>
			<SQLVERSION>2156</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.11.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************
			</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Programmatore</ADDEDBY>
			<SQLVERSION>2155</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.11.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************
			</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Programmatore</ADDEDBY>
			<SQLVERSION>2154</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.11.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************
			</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Programmatore</ADDEDBY>
			<SQLVERSION>2153</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.11.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************
			</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Programmatore</ADDEDBY>
			<SQLVERSION>2152</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.11.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************
			</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Programmatore</ADDEDBY>
			<SQLVERSION>2151</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.11.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************
			</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Programmatore</ADDEDBY>
			<SQLVERSION>2150</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.11.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************
			</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Programmatore</ADDEDBY>
			<SQLVERSION>2149</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.11.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************
			</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Programmatore</ADDEDBY>
			<SQLVERSION>2148</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.11.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************
			</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Programmatore</ADDEDBY>
			<SQLVERSION>2147</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.11.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************
			</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Programmatore</ADDEDBY>
			<SQLVERSION>2146</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.11.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************
			</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Programmatore</ADDEDBY>
			<SQLVERSION>2145</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.11.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************
			</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Programmatore</ADDEDBY>
			<SQLVERSION>2144</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.11.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************
			</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Programmatore</ADDEDBY>
			<SQLVERSION>2143</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.11.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************
			</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Steve McDonald</ADDEDBY>
			<SQLVERSION>2142</SQLVERSION>
			<RMTRACKLINK>66119</RMTRACKLINK>
			<REASON>Add column "Obsolete" to CNF_Driver</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
               WHERE Name = N'Obsolete' AND
               Object_ID  = Object_ID(N'CNF_Driver'))
BEGIN
  ALTER TABLE CNF_Driver ADD Obsolete SmallInt NULL DEFAULT 0
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>UPDATE CNF_Driver
SET Obsolete = 0
WHERE Obsolete IS NULL</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Federico Caramella</ADDEDBY>
			<SQLVERSION>2141</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>Extended Info Update</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE DATA_ExtendedInfo ADD SaleItemId Integer NULL
ALTER TABLE DATA_ExtendedInfo ADD TicketId Integer NULL
ALTER TABLE DATA_ExtendedInfo ADD Fkey Integer NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>SELECT mm.* 
INTO #temptable
from (
SELECT DATA_SaleItem2Dmg.SaleItem2DmgId as FKey, DmgCategoryId, SaleItemId, NULL AS TicketId 
from DATA_SaleItem2Dmg 
where DATA_SaleItem2Dmg.SaleItemId IS NOT NULL
UNION (
SELECT DATA_Ticket.TicketId as FKey, DmgCategoryId, NULL SaleItemId, TicketId 
from DATA_Ticket 
WHERE DATA_Ticket.DmgCategoryId IS NOT NULL) 

) as mm

	INSERT INTO DATA_ExtendedInfo (DmgCategoryId, ExtendedInfoAK, SaleItemId, TicketId, FKey)
	SELECT DmgCategoryId, (SELECT top 1 SiteCode from CNF_Site) + '.EXI' + cast(ROW_NUMBER() over ( order by fkey ) as Varchar), SaleItemId, TicketId, FKey FROM #temptable order by fkey 

      INSERT INTO DATA_ExtendedInfo2Ticket (ExtendedInfoId, TicketId) 
	  SELECT ExtendedInfoId, DATA_ExtendedInfo.TicketId FROM DATA_ExtendedInfo WHERE DATA_ExtendedInfo.TicketId Is not Null

	  UPDATE DATA_DmgData SET DATA_DmgData.FKey = m.ExtendedInfoId 
	  FROM DATA_ExtendedInfo m WHERE DATA_DmgData.FKey = m.FKEY AND DATA_DmgData.DmgType = 10 AND m.TicketId IS NOT NULL

      INSERT INTO DATA_ExtendedInfo2SaleItem(ExtendedInfoId, SaleItemId) 
	  SELECT ExtendedInfoId, DATA_ExtendedInfo.SaleItemId FROM DATA_ExtendedInfo WHERE DATA_ExtendedInfo.SaleItemId Is not Null

	  UPDATE DATA_DmgData SET DATA_DmgData.FKey = m.ExtendedInfoId, DATA_DmgData.DmgType = 10 
	  FROM DATA_ExtendedInfo m WHERE DATA_DmgData.FKey = m.FKEY AND DATA_DmgData.DmgType = 12 AND m.SaleItemId IS NOT NULL

ALTER TABLE DATA_ExtendedInfo DROP COLUMN SaleItemId 
ALTER TABLE DATA_ExtendedInfo DROP COLUMN TicketId 
ALTER TABLE DATA_ExtendedInfo DROP COLUMN Fkey 

DROP TABLE #temptable;</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>pdalben</ADDEDBY>
			<SQLVERSION>2140</SQLVERSION>
			<RMTRACKLINK>674476</RMTRACKLINK>
			<REASON>Changed DriverName from DrvPrnZebraZW220 to DrvPrnZebraGeneric</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT> update CNF_Driver set 
   DriverAk = 'TDrvPrnZebraGeneric', 
   DllName = 'DrvPrnZebraGeneric.dll',
   Description = 'Zebra Generic Printer' 
 where FamilyType = 167   </SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_DEVICE set 
  Description = 'Zebra Generic Printer' 
where DriverId = (select DriverId from CNF_Driver where FamilyType = 167)</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AndreaDavanzo</ADDEDBY>
			<SQLVERSION>2139</SQLVERSION>
			<RMTRACKLINK>61570</RMTRACKLINK>
			<REASON>[0] Drop column TdT_TypeId from SIAE_System
[1] Create column ProducerId in CNF_MatrixCellInfo
[2] Added FK for ProducerId
[3] Added column ExternalId in SIAE_Producer</REASON>
			<TABLENAMES>SIAE_System=SystemId
CNF_MatrixCellInfo=MatrixCellInfoId
SIAE_Producer=ProducerId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
           WHERE Name = N'TdT_TypeId' AND
           Object_ID  = Object_ID(N'SIAE_System'))
BEGIN
  ALTER TABLE SIAE_System DROP COLUMN TdT_TypeId
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
               WHERE Name = N'ProducerId' AND
               Object_ID  = Object_ID(N'CNF_MatrixCellInfo'))
BEGIN
  ALTER TABLE CNF_MatrixCellInfo ADD ProducerId Integer NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int  
EXEC Otn_Add_ForeingKey 
	@ForeingKeyTable = N'CNF_MatrixCellInfo', @ForeingKeyReferenceTable  = N'SIAE_Producer',
	@ForeingKeyColumn = N'ProducerId', @ForeingKeyReferenceColumn = N'ProducerId',
	@result = @retval OUTPUT
SELECT @retval;</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
               WHERE Name = N'ExternalId' AND
               Object_ID  = Object_ID(N'SIAE_Producer'))
BEGIN
  ALTER TABLE SIAE_Producer ADD ExternalId varchar(10) NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>2138</SQLVERSION>
			<RMTRACKLINK>Various</RMTRACKLINK>
			<REASON>CNF_StatisticalGroup
[0] add field DMG Category Id
[1] add FK
CNF_perfomanceCategory
[2] add field DMG Category Id
[3] add FK</REASON>
			<TABLENAMES>CNF_StatisticalGroup=StatisticalGroupId
CNF_PerformanceCategory=PerformanceCategoryId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_performanceCategory
  add DmgCategoryId integer null</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_performanceCategory] 
add  foreign key([DmgCategoryId]) references [CNF_DmgCategory] ([DmgCategoryId])</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_StatisticalGroup
  add DmgCategoryId integer null</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_StatisticalGroup] 
add  foreign key([DmgCategoryId]) references [CNF_DmgCategory] ([DmgCategoryId])</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>2137</SQLVERSION>
			<RMTRACKLINK>Various</RMTRACKLINK>
			<REASON>[0] Add table DATA_ExtendedInfo + Add FK on (DmgCategoryId) 
[1] Add table DATA_ExtendedInfo2SaleItemId + Add FK on (ExtendedInfoId - SaleItemId ) + Index (SaleItemId)
[2] Add table DATA_ExtendedInfo2TicketId + Add FK on (ExtendedInfoId - TicketId ) + Index (TicketId)
[3] Add table CNF_DocTemplate2IdentifierType+ Add FK on (DocTemplateId )
[4] Create AKs
[5] Add LanguageAk to CNF_Language
[6] Add StatisticalGroupAk to CNF_StatisticalGroup
[7] Add PerformanceCategoryAK to CNF_PerformanceCategory</REASON>
			<TABLENAMES>DATA_ExtendedInfo=ExtendedInfoId
DATA_ExtendedInfo2SaleItem=ExtendedInfo2SaleItemId
DATA_ExtendedInfo2Ticket=ExtendedInfo2TicketId
CNF_DocTemplate2IdentifierType=DocTemplate2IdentifierTypeId
CNF_Language=LanguageId
CNF_StatisticalGroup=StatisticalGroupId
CNF_PerformanceCategory=PerformanceCategoryId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'DATA_ExtendedInfo'))

BEGIN

Create table [DATA_ExtendedInfo]
(
	[ExtendedInfoId] Integer Identity(1,1) NOT NULL,
	[ExtendedInfoAK] Varchar(32) NOT NULL,
	[DmgCategoryId] Integer NOT NULL,
Primary Key ([ExtendedInfoID])
)


Alter table [DATA_ExtendedInfo] 
  add  foreign key([DmgCategoryId]) references [CNF_DmgCategory] ([DmgCategoryId])


END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'DATA_ExtendedInfo2SaleItem'))

BEGIN

Create table [DATA_ExtendedInfo2SaleItem]
(
	[ExtendedInfo2SaleItemId] Integer Identity(1,1) NOT NULL,
	[ExtendedInfoId] Integer NOT NULL,
	[SaleItemId] Integer NOT NULL,
Primary Key ([ExtendedInfo2SaleItemId])
) 


Create Index [Idx_DATA_Extenedednfo2SI_SaleItemId] ON [DATA_ExtendedInfo2SaleItem] ([SaleItemId] ) 


Alter table [DATA_ExtendedInfo2SaleItem] add  foreign key([ExtendedInfoId]) references [DATA_ExtendedInfo] ([ExtendedInfoId])


Alter table [DATA_ExtendedInfo2SaleItem] add  foreign key([SaleItemId]) references [DATA_SaleItem] ([SaleItemId])


END

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'DATA_ExtendedInfo2Ticket'))

BEGIN

Create table [DATA_ExtendedInfo2Ticket]
(
	[ExtendedInfo2TicketId] Integer Identity(1,1) NOT NULL,
	[ExtendedInfoId] Integer NOT NULL,
	[TicketId] Integer NOT NULL,
Primary Key ([ExtendedInfo2TicketId])
) 


Create Index [IDX_ExtendedInfo2TI_TicketId] ON [DATA_ExtendedInfo2Ticket] ([TicketId] ) 


Alter table [DATA_ExtendedInfo2Ticket] add  foreign key([ExtendedInfoId]) references [DATA_ExtendedInfo] ([ExtendedInfoId])


Alter table [DATA_ExtendedInfo2Ticket] add  foreign key([TicketId]) references [DATA_Ticket] ([TicketId])


END

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'CNF_DocTemplate2IdentifierType'))

BEGIN

Create table [CNF_DocTemplate2IdentifierType]
(
	[DocTemplate2IdentifierTypeId] Integer Identity(1,1) NOT NULL,
	[DocTemplateId] Integer NOT NULL,
	[IdentifierType] Smallint NULL,
Primary Key ([DocTemplate2IdentifierTypeId])
) 


Alter table [CNF_DocTemplate2IdentifierType] add  foreign key([DocTemplateId]) references [CNF_DocTemplate] ([DocTemplateId])


END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'LanguageAK' AND
                Object_ID  = Object_ID(N'CNF_Language'))
BEGIN
  ALTER TABLE CNF_Language ADD LanguageAK varchar(32) NULL 
END

IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'StatisticalGroupAK' AND
                Object_ID  = Object_ID(N'CNF_StatisticalGroup'))
BEGIN
  ALTER TABLE CNF_StatisticalGroup ADD StatisticalGroupAK varchar(32) NULL
END  

IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'PerformanceCategoryAK' AND
                Object_ID  = Object_ID(N'CNF_PerformanceCategory'))
BEGIN
  ALTER TABLE CNF_PerformanceCategory ADD PerformanceCategoryAK varchar(32) NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_Language set LanguageAK = 
(select top 1 SystemCode from CNF_System where Enabled = 1) + '.LAN'+ CAST(LanguageId AS Varchar(MAX))
where  LanguageAK is null

INSERT INTO DATA_Counter
           (CounterType
           ,IdentifierAK
           ,ReferenceTime
           ,Counter
           ,LastUpdateGuid)
     VALUES
           (27,
           (select top 1 SystemCode from CNF_System where Enabled = 1) +'.LAN',
           'NEVER',
           (select ISNULL(MAX(LanguageId),0) from CNF_Language),
           NULL)


ALTER TABLE CNF_Language alter column LanguageAK varchar(32) not NULL


				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>
update CNF_StatisticalGroup set StatisticalGroupAK = 
(select top 1 SystemCode from CNF_System where Enabled = 1) + '.STA'+ CAST(StatisticalGroupId AS Varchar(MAX))
where StatisticalGroupAK is null

INSERT INTO DATA_Counter
           (CounterType
           ,IdentifierAK
           ,ReferenceTime
           ,Counter
           ,LastUpdateGuid)
     VALUES
           (28,
           (select top 1 SystemCode from CNF_System where Enabled = 1) +'.STA',
           'NEVER',
           (select ISNULL(MAX(StatisticalGroupId),0) from CNF_StatisticalGroup),
           NULL)


ALTER TABLE CNF_StatisticalGroup alter column StatisticalGroupAK varchar(32) not NULL


				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_PerformanceCategory set PerformanceCategoryAK = 
(select top 1 SystemCode from CNF_System where Enabled = 1) +'.PCA'+ CAST(PerformanceCategoryId AS Varchar(MAX))
where PerformanceCategoryAK is null

INSERT INTO DATA_Counter
           (CounterType
           ,IdentifierAK
           ,ReferenceTime
           ,Counter
           ,LastUpdateGuid)
     VALUES
           (29,
           (select top 1 SystemCode from CNF_System where Enabled = 1) +'.PCA',
           'NEVER',
           (select ISNULL(MAX(PerformanceCategoryId),0) from CNF_PerformanceCategory),
           NULL)


ALTER TABLE CNF_PerformanceCategory alter column PerformanceCategoryAK varchar(32) not NULL


				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>dapicella</ADDEDBY>
			<SQLVERSION>2136</SQLVERSION>
			<RMTRACKLINK>67124</RMTRACKLINK>
			<REASON>Table CNF_Attribute
[0] Adding column Description

Table CNF_AttributeTemplate
[1] Alter column Description
[2] Adding column Name
[3] Populate Name with Description

Table DATA_Ticket
[4] Adding column FirstUsageId
[5] Foreing Key DATA_Ticket

Table DATA_TicketUsage
[6] Adding trigger InsertFirtsUsage
[7] Populate FirstUsageId

			</REASON>
			<TABLENAMES>CNF_Attribute=AttributeId
CNF_AttributeTemplate=AttributeTemplateId
DATA_Ticket=TicketId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Description' AND
                Object_ID  = Object_ID(N'CNF_Attribute'))
BEGIN
  ALTER TABLE CNF_Attribute ADD Description Nvarchar(100) NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Description' AND
                Object_ID  = Object_ID(N'CNF_AttributeTemplate'))
BEGIN
  ALTER TABLE CNF_AttributeTemplate ALTER COLUMN Description Nvarchar(100) NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Name' AND
                Object_ID  = Object_ID(N'CNF_AttributeTemplate'))
BEGIN
  ALTER TABLE CNF_AttributeTemplate ADD Name Nvarchar(60) NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>UPDATE CNF_AttributeTemplate
SET Name = Description</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'FirstUsageId' AND
                Object_ID  = Object_ID(N'DATA_Ticket'))
BEGIN
  ALTER TABLE DATA_Ticket ADD FirstUsageId Integer NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int  
EXEC Otn_Add_ForeingKey 
	@ForeingKeyTable = N'DATA_Ticket', @ForeingKeyReferenceTable  = N'DATA_TicketUsage',
	@ForeingKeyColumn = N'FirstUsageId', @ForeingKeyReferenceColumn = N'UsageId',
	@result = @retval OUTPUT
SELECT @retval;</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>EXEC dbo.sp_executesql @statement = N'	CREATE TRIGGER InsertFirtsUsage ON  DATA_TicketUsage 
											   AFTER INSERT 
											AS 
											BEGIN
												-- SET NOCOUNT ON added to prevent extra result sets from
												-- interfering with SELECT statements.
												SET NOCOUNT ON;
												DECLARE @UsageId integer
												DECLARE @TicketId integer
												DECLARE @ValidateResult integer
												DECLARE @UsageType integer

												-- Insert statements for trigger here
												IF NOT EXISTS(SELECT * FROM DELETED)
												BEGIN
													SELECT @UsageId=UsageId, @TicketId=TicketId, @ValidateResult=ValidateResult, @UsageType=UsageType FROM Inserted
													IF (@ValidateResult &lt;= 99) AND (@UsageType=1)
													BEGIN 
														UPDATE DATA_Ticket 
														SET FirstUsageId = ISNULL(FirstUsageId, @UsageId)
														WHERE TicketId = @TicketId
													END
												END

											END'
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>UPDATE DATA_Ticket 
SET FirstUsageId = FU.UsageId
FROM 
	DATA_Ticket
	INNER JOIN (	SELECT
						TU.TicketId,
						MIN(TU.UsageId) UsageId
					FROM
						DATA_TicketUsage TU With(NoLock)
					WHERE
						UsageType = 1
						AND ValidateResult &lt;= 99							
					GROUP BY
						TU.TicketId
				) FU ON FU.TicketId = DATA_Ticket.TicketId</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>dapicella</ADDEDBY>
			<SQLVERSION>2135</SQLVERSION>
			<RMTRACKLINK>67124</RMTRACKLINK>
			<REASON>Table DATA_Sale
[0] Adding column PaidTransactionId 
[1] Adding column EncodedTransactionId
[2] Adding column ValidatedTransactionId
[3] Adding column CompletedTransactionId
[4] Adding column VoidTransactionId

Table RR_CNF_RevenueRecognition
[5] Adding column DateFrom
[6] Adding column DateTo
[7] Adding column FixedQuantity

[8] Populate DATA_Sale New Fields
			</REASON>
			<TABLENAMES>DATA_Sale=SaleId
RR_CNF_RevenueRecognition=RRId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'PaidTransactionId' AND
                Object_ID  = Object_ID(N'DATA_Sale'))
BEGIN
  ALTER TABLE DATA_Sale ADD PaidTransactionId Integer NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'EncodedTransactionId' AND
                Object_ID  = Object_ID(N'DATA_Sale'))
BEGIN
  ALTER TABLE DATA_Sale ADD EncodedTransactionId Integer NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'ValidatedTransactionId' AND
                Object_ID  = Object_ID(N'DATA_Sale'))
BEGIN
  ALTER TABLE DATA_Sale ADD ValidatedTransactionId Integer NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'CompletedTransactionId' AND
                Object_ID  = Object_ID(N'DATA_Sale'))
BEGIN
  ALTER TABLE DATA_Sale ADD CompletedTransactionId Integer NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'VoidTransactionId' AND
                Object_ID  = Object_ID(N'DATA_Sale'))
BEGIN
  ALTER TABLE DATA_Sale ADD VoidTransactionId Integer NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'DateFrom' AND
                Object_ID  = Object_ID(N'RR_CNF_RevenueRecognition'))
BEGIN
  ALTER TABLE RR_CNF_RevenueRecognition ADD DateFrom Datetime NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'DateTo' AND
                Object_ID  = Object_ID(N'RR_CNF_RevenueRecognition'))
BEGIN
  ALTER TABLE RR_CNF_RevenueRecognition ADD DateTo Datetime NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'FixedQuantity' AND
                Object_ID  = Object_ID(N'RR_CNF_RevenueRecognition'))
BEGIN
  ALTER TABLE RR_CNF_RevenueRecognition ADD FixedQuantity Integer NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>UPDATE DATA_Sale
	SET 
	DATA_Sale.PaidTransactionId = UP.PaidTransactionId,
	DATA_Sale.EncodedTransactionId = UP.EncodedTransactionId,
	DATA_Sale.ValidatedTransactionId = UP.ValidatedTransactionId,
	DATA_Sale.CompletedTransactionId = UP.CompletedTransactionId,
	DATA_Sale.VoidTransactionId = UP.VoidTransactionId
FROM
	DATA_Sale 
	INNER JOIN (	SELECT
						SA.SaleId,
						SA.Paid,
						CASE WHEN SA.Paid = 1 THEN MAX(PY.TransactionId) ELSE NULL END PaidTransactionId,
						SA.Encoded,
						CASE WHEN SA.Encoded = 1 THEN MAX(TR2T.TransactionId) ELSE NULL END EncodedTransactionId,
						SA.Validated,
						CASE WHEN SA.Validated = 1 THEN MAX(TR2T.TransactionId) ELSE NULL END ValidatedTransactionId,
						SA.Completed,
						CASE WHEN SA.Completed = 1 THEN MAX(TR.TransactionId) ELSE NULL END CompletedTransactionId,
						ISNULL(MAX(TRV.TransactionId), NULL) VoidTransactionId
					FROM
						DATA_Sale SA With(NoLock)
						LEFT JOIN DATA_Reservation R With(NoLock) ON R.SaleId = SA.SaleId
						LEFT JOIN DATA_Transaction TR With(NoLock) ON TR.TransactionType NOT IN (5, 35) /*Lk_TransactionType_ResDelete, Lk_TransactionType_Purge*/ AND TR.SaleId = SA.SaleId
						LEFT JOIN DATA_Payment PY With(NoLock) ON PY.PaymentStatus = 1 /*Lk_PaymentStatus_Approved*/ AND PY.TransactionId = TR.TransactionId  
						LEFT JOIN DATA_Transaction2Ticket TR2T With(NoLock) ON TR2T.TransactionId = TR.TransactionId
						LEFT JOIN DATA_Transaction TRV With(NoLock) ON TRV.TransactionType IN (5, 35) /*Lk_TransactionType_ResDelete, Lk_TransactionType_Purge*/ AND TRV.SaleId = SA.SaleId
					GROUP BY
						SA.SaleId,
						SA.Paid,
						SA.Encoded,
						SA.Validated,
						SA.Completed
				) UP ON UP.SaleId = DATA_Sale.SaleId</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>2134</SQLVERSION>
			<RMTRACKLINK>65529</RMTRACKLINK>
			<REASON>Table SIAE_Location
[0] - Field "Citta" - Not null removed
[1] - Field "Provincia" - Not null removed

			</REASON>
			<TABLENAMES>SIAE_Location=SiaeLocationId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>


ALTER TABLE SIAE_Location ALTER COLUMN citta NVarChar(20) null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>
ALTER TABLE SIAE_Location ALTER COLUMN Provincia NVarChar(2) null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>mkimball</ADDEDBY>
			<SQLVERSION>2133</SQLVERSION>
			<RMTRACKLINK>67449</RMTRACKLINK>
			<REASON>Add PaymentPlayAK to DATA_PaymentPlan and backfill the old payment plans</REASON>
			<TABLENAMES>DATA_PaymentPlan=PaymentPlanId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'PaymentPlanAK' AND
                Object_ID  = Object_ID(N'DATA_PaymentPlan'))
BEGIN
  ALTER TABLE DATA_PaymentPlan ADD PaymentPlanAK Nvarchar(32) 
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>UPDATE DATA_PaymentPlan
	SET PaymentPlanAK = SUBSTRING(CONVERT(VARCHAR(36), NEWID()), 1, 32)
WHERE PaymentPlanAK IS NULL;</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>blumsden</ADDEDBY>
			<SQLVERSION>2132</SQLVERSION>
			<RMTRACKLINK>64622</RMTRACKLINK>
			<REASON>Adding ParentLocationId field to CNF_Location
[0] Adding column ParentLocationId 

Adding Foreign Key to CNF_Location
[1] Adding Foreign Key ParentLocationId </REASON>
			<TABLENAMES>CNF_Location=LocationId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'ParentLocationId' AND
                Object_ID  = Object_ID(N'CNF_Location'))
BEGIN
  ALTER TABLE CNF_Location ADD ParentLocationId Integer NULL
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_Location'
	          AND CONSTRAINT_NAME = N'fk_CNF_Location_ParentLocationId')          
BEGIN
  ALTER TABLE [CNF_Location] WITH CHECK 
  ADD  CONSTRAINT [fk_CNF_Location_ParentLocationId] FOREIGN KEY([ParentLocationId])
  REFERENCES [CNF_Location] ([LocationId])
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>dapicella</ADDEDBY>
			<SQLVERSION>2131</SQLVERSION>
			<RMTRACKLINK>67124</RMTRACKLINK>
			<REASON>Added new table for Revenue recognition module

[0] - RR_CNF_RevenueRecognition
[1] - RR_CNF_CostCenterConfig
[2] - Foreing Key RR_CNF_CostCenterConfig
[3] - RR_CNF_CostCenterConfigItem
[4] - Foreing Key RR_CNF_CostCenterConfigItem
[5] - Foreing Key RR_CNF_CostCenterConfigItem
[6] - Foreing Key RR_CNF_CostCenterConfigItem
[7] - RR_CNF_Product
[8] - Foreing Key RR_CNF_Product
[9] - Foreing Key RR_CNF_Product
[10] - Foreing Key RR_CNF_Product
[11] - Foreing Key RR_CNF_Product
[12] - RR_CNF_Validity
[13] - Foreing Key RR_CNF_Validity
[14] - RR_DATA_Revenue
[15] - Foreing Key RR_DATA_Revenue
[16] - Foreing Key RR_DATA_Revenue
[17] - Foreing Key RR_DATA_Revenue
[18] - Foreing Key RR_DATA_Revenue
[19] - Foreing Key RR_DATA_Revenue
[20] - Foreing Key RR_DATA_Revenue
[21] - Foreing Key RR_DATA_Revenue
[22] - Foreing Key RR_DATA_Revenue
[23] - Foreing Key RR_DATA_Revenue
[24] - Foreing Key RR_DATA_Revenue
[25] - Foreing Key RR_DATA_Revenue
[26] - Foreing Key RR_DATA_Revenue
[27] - Foreing Key RR_DATA_Revenue
[28] - Foreing Key RR_DATA_Revenue
			</REASON>
			<TABLENAMES>RR_CNF_RevenueRecognition=RRId
RR_CNF_CostCenterConfig=RRCostCenterConfigId
RR_CNF_CostCenterConfigItem=RRCostCenterConfigItemId
RR_CNF_Product=RRProductId
RR_CNF_Validity=RRValidityId
RR_DATA_Revenue=RRDataId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'RR_CNF_RevenueRecognition')
BEGIN
	CREATE TABLE [dbo].[RR_CNF_RevenueRecognition](
		[RRId] [int] IDENTITY(1,1) NOT NULL,
		[RRAK] [varchar](32) NOT NULL,
		[RRCode] [varchar](10) NOT NULL,
		[RRDescription] [nvarchar](100) NULL,
		[RRCalcTypeWhen] [smallint] NOT NULL,
		[RRCalcTypeMethod] [smallint] NOT NULL,
		[RRCalcTypePeriod] [smallint] NOT NULL,
		[RRCalcTypeSplitType] [smallint] NOT NULL,
		[CreationDate] [DATETIME] NOT NULL,
		[LastUpdate] [DATETIME] NOT NULL,
		[Enabled] [smallint] NOT NULL DEFAULT ((1)),
	PRIMARY KEY ([RRId]) 
	)
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'RR_CNF_CostCenterConfig')
BEGIN
	CREATE TABLE [dbo].[RR_CNF_CostCenterConfig](
		[RRCostCenterConfigId] [int] IDENTITY(1,1) NOT NULL,
		[RRId] [int] NOT NULL,
		[CostCenterType] [Smallint] NOT NULL,
	PRIMARY KEY ([RRCostCenterConfigId]) 
	)
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int  

EXEC Otn_Add_ForeingKey 
	@ForeingKeyTable = N'RR_CNF_CostCenterConfig', @ForeingKeyReferenceTable  = N'RR_CNF_RevenueRecognition',
	@ForeingKeyColumn = N'RRId', @ForeingKeyReferenceColumn = N'RRId',
	@result = @retval OUTPUT
SELECT @retval;</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'RR_CNF_CostCenterConfigItem')
BEGIN
	CREATE TABLE [dbo].[RR_CNF_CostCenterConfigItem](
		[RRCostCenterConfigItemId] [int] IDENTITY(1,1) NOT NULL,
		[RRCostCenterConfigId] [int] NOT NULL,
		[CostCenterSubType] [smallint] NOT NULL,
		[SiteId] [int] NULL,
		[CostCenterId] [int] NOT NULL,
		[Price] [float] NULL,
		[Percentage] [float] NULL,
		[RemaningValues] [bit] NULL,
	PRIMARY KEY ([RRCostCenterConfigItemId]) 
	)
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int  
EXEC Otn_Add_ForeingKey 
	@ForeingKeyTable = N'RR_CNF_CostCenterConfigItem', @ForeingKeyReferenceTable  = N'RR_CNF_CostCenterConfig',
	@ForeingKeyColumn = N'RRCostCenterConfigId', @ForeingKeyReferenceColumn = N'RRCostCenterConfigId',
	@result = @retval OUTPUT
SELECT @retval;</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int
EXEC Otn_Add_ForeingKey 
	@ForeingKeyTable = N'RR_CNF_CostCenterConfigItem', @ForeingKeyReferenceTable  = N'CNF_Site',
	@ForeingKeyColumn = N'SiteId', @ForeingKeyReferenceColumn = N'SiteId',
	@result = @retval OUTPUT
SELECT @retval;</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int
EXEC Otn_Add_ForeingKey 
	@ForeingKeyTable = N'RR_CNF_CostCenterConfigItem', @ForeingKeyReferenceTable  = N'CNF_CostCenter',
	@ForeingKeyColumn = N'CostCenterId', @ForeingKeyReferenceColumn = N'CostCenterId',
	@result = @retval OUTPUT
SELECT @retval;</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'RR_CNF_Product')
BEGIN
	CREATE TABLE [dbo].[RR_CNF_Product](
		[RRProductId] [int] IDENTITY(1,1) NOT NULL,
		[RRId] [int] NOT NULL,
		[MatrixSheetId] [int] NULL,
		[MatrixCellId] [int] NULL,
		[AttributeId] [int] NULL,
	PRIMARY KEY ([RRProductId]) 
	)
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int  
EXEC Otn_Add_ForeingKey 
	@ForeingKeyTable = N'RR_CNF_Product', @ForeingKeyReferenceTable  = N'RR_CNF_RevenueRecognition',
	@ForeingKeyColumn = N'RRId', @ForeingKeyReferenceColumn = N'RRId',
	@result = @retval OUTPUT
SELECT @retval;</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int 
EXEC Otn_Add_ForeingKey
	@ForeingKeyTable = N'RR_CNF_Product', @ForeingKeyReferenceTable  = N'CNF_MatrixSheet',
	@ForeingKeyColumn = N'MatrixSheetId', @ForeingKeyReferenceColumn = N'MatrixSheetId',
	@result = @retval OUTPUT
SELECT @retval;</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int 
EXEC Otn_Add_ForeingKey 
	@ForeingKeyTable = N'RR_CNF_Product', @ForeingKeyReferenceTable  = N'CNF_MatrixCell',
	@ForeingKeyColumn = N'MatrixCellId', @ForeingKeyReferenceColumn = N'MatrixCellId',
	@result = @retval OUTPUT
SELECT @retval;</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int 
EXEC Otn_Add_ForeingKey
	@ForeingKeyTable = N'RR_CNF_Product', @ForeingKeyReferenceTable  = N'CNF_Attribute',
	@ForeingKeyColumn = N'AttributeId', @ForeingKeyReferenceColumn = N'AttributeId',
	@result = @retval OUTPUT
SELECT @retval;</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'RR_CNF_Validity')
BEGIN
	CREATE TABLE [dbo].[RR_CNF_Validity](
		[RRValidityId] [int] IDENTITY(1,1) NOT NULL,
		[RRId] [int] NOT NULL,
		[FromDate] [smalldatetime] NOT NULL,
		[ToDate] [smalldatetime] NOT NULL,
		[AlwaysVaild] [smallint] NOT NULL DEFAULT ((1)),
		[CreationDate] [DATETIME] NOT NULL,
		[LastUpdate] [DATETIME] NOT NULL,
		[Enabled] [smallint] NOT NULL DEFAULT ((1)),
	PRIMARY KEY ([RRValidityId]) 
	)
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int  
EXEC Otn_Add_ForeingKey 
	@ForeingKeyTable = N'RR_CNF_Validity', @ForeingKeyReferenceTable  = N'RR_CNF_RevenueRecognition',
	@ForeingKeyColumn = N'RRId', @ForeingKeyReferenceColumn = N'RRId',
	@result = @retval OUTPUT
SELECT @retval;</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'RR_DATA_Revenue')
BEGIN
	CREATE TABLE [dbo].[RR_DATA_Revenue](
		[RRDataId] [Bigint] IDENTITY(1,1) NOT NULL,
		[FCalcDate] [DATETIME] NOT NULL,
		[FRevenueDate] [DATETIME] NOT NULL,
		[MatrixCellId] [int] NOT NULL,	
		[MatrixCellCode] [nvarchar](32) NULL,
		[SaleId] [int] NULL,
		[SaleItemId] [int] NULL,
		[TransactionId] [int] NULL,
		[UsageId] [int] NULL,
		[TicketId] [int] NULL, 
		[Quantity] [int] NOT NULL DEFAULT ((0)),
		[UnitAmount] [float] NOT NULL, 
		[GrossAmount] [float] NOT NULL,	
		[NetAmount] [float] NOT NULL, 
		[SiteId] [int] NOT NULL,
		[LocationId] [int] NOT NULL,
		[OperatingAreaId] [int] NOT NULL,
		[WorkstationId] [int] NOT NULL,
		[UserGroupId] [int] NOT NULL,
		[UserId] [int] NOT NULL,
		[RRId] [int] NOT NULL, 
		[RRCode] [varchar](10) NULL, 
		[RRCalcTypeWhen] [smallint] NOT NULL, 
		[RRCalcTypeMethod] [smallint] NOT NULL,	
		[RRCalcTypePeriod] [smallint] NOT NULL,	
		[RRCalcTypeSplitType] [smallint] NOT NULL, 
		[CostCenterType] [smallint] NOT NULL, 
		[CostCenterId] [int] NOT NULL, 	
		[CostCenterCode] [Nvarchar](10) NULL, 
		[CostCenterSubType] [smallint] NOT NULL, 	
		[Price] [float] NULL, 	
		[Percentage] [float] NULL, 	
		[RemaningValues] [bit] NULL, 	
		[RevenueAmount] [float] NOT NULL,
	PRIMARY KEY ([RRDataId]) 
	)
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int  
EXEC Otn_Add_ForeingKey 
	@ForeingKeyTable = N'RR_DATA_Revenue', @ForeingKeyReferenceTable  = N'CNF_MatrixCell',
	@ForeingKeyColumn = N'MatrixCellId', @ForeingKeyReferenceColumn = N'MatrixCellId',
	@result = @retval OUTPUT
SELECT @retval;</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int
EXEC Otn_Add_ForeingKey
	@ForeingKeyTable = N'RR_DATA_Revenue', @ForeingKeyReferenceTable  = N'DATA_Sale',
	@ForeingKeyColumn = N'SaleId', @ForeingKeyReferenceColumn = N'SaleId',
	@result = @retval OUTPUT
SELECT @retval;</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int
EXEC Otn_Add_ForeingKey
	@ForeingKeyTable = N'RR_DATA_Revenue', @ForeingKeyReferenceTable  = N'DATA_SaleItem',
	@ForeingKeyColumn = N'SaleItemId', @ForeingKeyReferenceColumn = N'SaleItemId',
	@result = @retval OUTPUT
SELECT @retval;</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int
EXEC Otn_Add_ForeingKey
	@ForeingKeyTable = N'RR_DATA_Revenue', @ForeingKeyReferenceTable  = N'DATA_Transaction',
	@ForeingKeyColumn = N'TransactionId', @ForeingKeyReferenceColumn = N'TransactionId',
	@result = @retval OUTPUT
SELECT @retval;</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int
EXEC Otn_Add_ForeingKey
	@ForeingKeyTable = N'RR_DATA_Revenue', @ForeingKeyReferenceTable  = N'DATA_TicketUsage',
	@ForeingKeyColumn = N'UsageId', @ForeingKeyReferenceColumn = N'UsageId',
	@result = @retval OUTPUT
SELECT @retval;</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int
EXEC Otn_Add_ForeingKey
	@ForeingKeyTable = N'RR_DATA_Revenue', @ForeingKeyReferenceTable  = N'DATA_Ticket',
	@ForeingKeyColumn = N'TicketId', @ForeingKeyReferenceColumn = N'TicketId',
	@result = @retval OUTPUT
SELECT @retval;</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int
EXEC Otn_Add_ForeingKey
	@ForeingKeyTable = N'RR_DATA_Revenue', @ForeingKeyReferenceTable  = N'CNF_Site',
	@ForeingKeyColumn = N'SiteId', @ForeingKeyReferenceColumn = N'SiteId',
	@result = @retval OUTPUT
SELECT @retval;</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int
EXEC Otn_Add_ForeingKey
	@ForeingKeyTable = N'RR_DATA_Revenue', @ForeingKeyReferenceTable  = N'CNF_Location',
	@ForeingKeyColumn = N'LocationId', @ForeingKeyReferenceColumn = N'LocationId',
	@result = @retval OUTPUT
SELECT @retval;</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int
EXEC Otn_Add_ForeingKey
	@ForeingKeyTable = N'RR_DATA_Revenue', @ForeingKeyReferenceTable  = N'CNF_OperatingArea',
	@ForeingKeyColumn = N'OperatingAreaId', @ForeingKeyReferenceColumn = N'OperatingAreaId',
	@result = @retval OUTPUT
SELECT @retval;</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int
EXEC Otn_Add_ForeingKey
	@ForeingKeyTable = N'RR_DATA_Revenue', @ForeingKeyReferenceTable  = N'CNF_Workstation',
	@ForeingKeyColumn = N'WorkstationId', @ForeingKeyReferenceColumn = N'WorkstationId',
	@result = @retval OUTPUT
SELECT @retval;</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int
EXEC Otn_Add_ForeingKey
	@ForeingKeyTable = N'RR_DATA_Revenue', @ForeingKeyReferenceTable  = N'CNF_UserGroup',
	@ForeingKeyColumn = N'UserGroupId', @ForeingKeyReferenceColumn = N'UserGroupId',
	@result = @retval OUTPUT
SELECT @retval;</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int
EXEC Otn_Add_ForeingKey
	@ForeingKeyTable = N'RR_DATA_Revenue', @ForeingKeyReferenceTable  = N'CNF_User',
	@ForeingKeyColumn = N'UserId', @ForeingKeyReferenceColumn = N'UserId',
	@result = @retval OUTPUT
SELECT @retval;</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int
EXEC Otn_Add_ForeingKey
	@ForeingKeyTable = N'RR_DATA_Revenue', @ForeingKeyReferenceTable  = N'RR_CNF_RevenueRecognition',
	@ForeingKeyColumn = N'RRId', @ForeingKeyReferenceColumn = N'RRId',
	@result = @retval OUTPUT
SELECT @retval;</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int
EXEC Otn_Add_ForeingKey
	@ForeingKeyTable = N'RR_DATA_Revenue', @ForeingKeyReferenceTable  = N'CNF_CostCenter',
	@ForeingKeyColumn = N'CostCenterId', @ForeingKeyReferenceColumn = N'CostCenterId',
	@result = @retval OUTPUT
SELECT @retval;</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>2130</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>Add new index on tables:
- DATA_Sale
- Data_Ticket

[0] - New index DATA_Sale -&gt; FSaleDate
[1] - New index DATA_Ticket -&gt; FEncodeDate



			</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>
IF NOT EXISTS (SELECT * 
               FROM sys.indexes  
               WHERE name='Idx_DataSale_FSaleDate' AND object_id = OBJECT_ID('DATA_Sale'))
BEGIN
  Create Index [Idx_DataSale_FSaleDate] ON [DATA_Sale] ([FSaleDate])
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>

IF NOT EXISTS (SELECT * 
               FROM sys.indexes  
               WHERE name='Idx_DataTicket_FEncodeDate' AND object_id = OBJECT_ID('DATA_Ticket'))
BEGIN
  Create Index [Idx_DataTicket_FEncodeDate] ON [DATA_Ticket] ([FEncodeDate])
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>2129</SQLVERSION>
			<RMTRACKLINK>65981</RMTRACKLINK>
			<REASON>
CNF_MatrixCellInfo
Add new fields:
 - MaskFieldEditLevelOverride  -  nVarChar(100) null
 - MaskFieldVisibleLevelOverride  -  nVarChar(100) null
 - MaskFieldRequiredLevelOverride - nVarChar(100) null

[0] - Add Field MaskFieldEditLevelOverride
[1] - Add Field MaskFieldVisibleLevel Override 
[2] - Add Field MaskFieldRequiredLevelOverride




			</REASON>
			<TABLENAMES>CNF_MatrixCellInfo=MatrixCellInfoId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>

IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'MaskFieldEditLevelOverride' AND
                Object_ID  = Object_ID(N'CNF_MatrixCellInfo'))
BEGIN
  alter table CNF_MatrixCellInfo add MaskFieldEditLevelOverride nVarChar(100)  null
END

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>
IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'MaskFieldVisibleLevelOverride' AND
                Object_ID  = Object_ID(N'CNF_MatrixCellInfo'))
BEGIN
  alter table CNF_MatrixCellInfo add MaskFieldVisibleLevelOverride nVarChar(100)  null
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>
IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'MaskFieldRequiredLevelOverride' AND
                Object_ID  = Object_ID(N'CNF_MatrixCellInfo'))
BEGIN
  alter table CNF_MatrixCellInfo add MaskFieldRequiredLevelOverride nVarChar(100)  null
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AndreaDavanzo</ADDEDBY>
			<SQLVERSION>2128</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>Fix the renaming of some store procedures with no naming convetion</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>declare @oldval varchar(max)
declare @newval varchar(max)
declare myCurs CURSOR FOR
  select name, REPLACE(name, 'spui_', 'otn_sp_ui_') as name2
  from sys.procedures WHERE SUBSTRING(name,1,5) = 'spui_'

open myCurs
fetch next from myCurs into @oldval, @newval

while (@@FETCH_STATUS = 0)
begin
  EXEC sp_rename @oldval, @newval

  fetch next from myCurs into @oldval, @newval
end

close myCurs
deallocate myCurs</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (select 1 from sys.procedures WHERE name = 'spCalcPMPState')
BEGIN
  EXEC sp_rename 'spCalcPMPState', 'otn_sp_CalcPMPState'
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>mkimball</ADDEDBY>
			<SQLVERSION>2127</SQLVERSION>
			<RMTRACKLINK>66774</RMTRACKLINK>
			<REASON>Add PaymentPlayAK to DATA_PaymentPlan and backfill the old plans</REASON>
			<TABLENAMES>DATA_PaymentPlan=PaymentPlanId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'PaymentPlanAK' AND
                Object_ID  = Object_ID(N'DATA_PaymentPlan'))
BEGIN
  ALTER TABLE DATA_PaymentPlan ADD PaymentPlanAK Nvarchar(32) 
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>UPDATE DATA_PaymentPlan
	SET PaymentPlanAK = SUBSTRING(CONVERT(VARCHAR(36), NEWID()), 1, 32)
WHERE PaymentPlanAK IS NULL;</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fesposito</ADDEDBY>
			<SQLVERSION>2126</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>Renaming all stored procedure fix</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>declare @sql    nvarchar(max)
declare @oldval nvarchar(max)
declare @newval nvarchar(max)
declare myCurs CURSOR FOR
  select name
  from sys.procedures WHERE SUBSTRING(name,1,3) = 'sp_'

open myCurs
fetch next from myCurs into @oldval

while (@@FETCH_STATUS = 0)
begin
  set @newval = 'otn_' + @oldval

  if exists (select 1 from sys.procedures WHERE name = @newval)
  begin
	SET @sql  =	N'DROP PROCEDURE ' + QUOTENAME(@newval);

	EXEC(@sql);
  end

  EXEC sp_rename @oldval, @newval

  fetch next from myCurs into @oldval
end

close myCurs
deallocate myCurs</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fesposito</ADDEDBY>
			<SQLVERSION>2125</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>Add field PaymentCardId on DATA_PaymentAccount</REASON>
			<TABLENAMES>DATA_PaymentAccount=PaymentAccountId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'PaymentCardId' AND
                Object_ID  = Object_ID(N'DATA_PaymentAccount'))
BEGIN
  ALTER TABLE DATA_PaymentAccount ADD PaymentCardId Int 
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'DATA_PaymentAccount'
	          AND CONSTRAINT_NAME = N'fk_DATA_PaymentAccont_PaymentCardId')          
BEGIN
  ALTER TABLE [DATA_PaymentAccount] WITH CHECK 
  ADD  CONSTRAINT [fk_DATA_PaymentAccont_PaymentCardId] FOREIGN KEY([PaymentCardId])
  REFERENCES [CNF_PaymentCard] ([PaymentCardId])
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fesposito</ADDEDBY>
			<SQLVERSION>2124</SQLVERSION>
			<RMTRACKLINK>66099</RMTRACKLINK>
			<REASON>Add RuleAK to CNF_SeasonalRule</REASON>
			<TABLENAMES>CNF_SeasonalRule=SeasonalRuleId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'RuleAK' AND
                Object_ID  = Object_ID(N'CNF_SeasonalRule'))
BEGIN
  ALTER TABLE CNF_SeasonalRule ADD RuleAK Nvarchar(32) 
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fesposito</ADDEDBY>
			<SQLVERSION>2123</SQLVERSION>
			<RMTRACKLINK>66889</RMTRACKLINK>
			<REASON>Populate of CNF_PaymentCardCode</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS(SELECT * FROM CNF_PaymentCardCode) 
BEGIN
  IF EXISTS( Select PaymentCardId From CNF_PaymentCard where UPPER(CCDescription) like '%AMERICAN EXPRESS%' )
  BEGIN
    INSERT INTO CNF_PaymentCardCode ( PaymentCardId, PaymentCardCode )
    VALUES (( Select PaymentCardId From CNF_PaymentCard where UPPER(CCDescription) like '%AMERICAN EXPRESS%' ), 'AMEX');
  END

  IF EXISTS( Select PaymentCardId From CNF_PaymentCard where UPPER(CCDescription) like '%DINERS%' ) 
  BEGIN
    INSERT INTO CNF_PaymentCardCode ( PaymentCardId, PaymentCardCode )
    VALUES ( ( Select PaymentCardId From CNF_PaymentCard where UPPER(CCDescription) like '%DINERS%' ), 'DINERS');
  END

  IF EXISTS( Select PaymentCardId From CNF_PaymentCard where UPPER(CCDescription) like '%DISCOVER%' )
  BEGIN
    INSERT INTO CNF_PaymentCardCode ( PaymentCardId, PaymentCardCode )
    VALUES ( ( Select PaymentCardId From CNF_PaymentCard where UPPER(CCDescription) like '%DISCOVER%' ), 'DISCOVER');
  END

  IF EXISTS( Select PaymentCardId From CNF_PaymentCard where UPPER(CCDescription) like '%JCB%' )
  BEGIN
    INSERT INTO CNF_PaymentCardCode ( PaymentCardId, PaymentCardCode )
    VALUES ( ( Select PaymentCardId From CNF_PaymentCard where UPPER(CCDescription) like '%JCB%' ), 'JCB');
  END

  IF EXISTS( Select PaymentCardId From CNF_PaymentCard where UPPER(CCDescription) like '%MASTERCARD%' )
  BEGIN
    INSERT INTO CNF_PaymentCardCode ( PaymentCardId, PaymentCardCode )
    VALUES ( ( Select PaymentCardId From CNF_PaymentCard where UPPER(CCDescription) like '%MASTERCARD%' ), 'MASTERCARD');
  END

  IF EXISTS( Select PaymentCardId From CNF_PaymentCard where UPPER(CCDescription) like '%VISA%' )
  BEGIN
    INSERT INTO CNF_PaymentCardCode ( PaymentCardId, PaymentCardCode )
    VALUES ( ( Select PaymentCardId From CNF_PaymentCard where UPPER(CCDescription) like '%VISA%' ), 'VISA');
  END

  IF EXISTS( Select PaymentCardId From CNF_PaymentCard where UPPER(CCDescription) like '%MASTERCARD%' )
  BEGIN
    INSERT INTO CNF_PaymentCardCode ( PaymentCardId, PaymentCardCode )
    VALUES ( ( Select PaymentCardId From CNF_PaymentCard where UPPER(CCDescription) like '%MASTERCARD%' ), 'M/C');
  END

  IF EXISTS( Select PaymentCardId From CNF_PaymentCard where UPPER(CCDescription) like '%DINERS%' )
  BEGIN
    INSERT INTO CNF_PaymentCardCode ( PaymentCardId, PaymentCardCode )
    VALUES ( ( Select PaymentCardId From CNF_PaymentCard where UPPER(CCDescription) like '%DINERS%' ), 'DCLB');
  END

  IF EXISTS( Select PaymentCardId From CNF_PaymentCard where UPPER(CCDescription) like '%DISCOVER%' )
  BEGIN
    INSERT INTO CNF_PaymentCardCode ( PaymentCardId, PaymentCardCode )
    VALUES ( ( Select PaymentCardId From CNF_PaymentCard where UPPER(CCDescription) like '%DISCOVER%' ), 'DCVR');
  END

  IF EXISTS( Select PaymentCardId From CNF_PaymentCard where UPPER(CCDescription) like '%MASTERCARD%' )
  BEGIN
    INSERT INTO CNF_PaymentCardCode ( PaymentCardId, PaymentCardCode )
    VALUES ( ( Select PaymentCardId From CNF_PaymentCard where UPPER(CCDescription) like '%MASTERCARD%' ), 'MASTER-CARD');
  END

  IF EXISTS( Select PaymentCardId From CNF_PaymentCard where UPPER(CCDescription) like '%AMERICAN EXPRESS%' )
  BEGIN
    INSERT INTO CNF_PaymentCardCode ( PaymentCardId, PaymentCardCode )
    VALUES ( ( Select PaymentCardId From CNF_PaymentCard where UPPER(CCDescription) like '%AMERICAN EXPRESS%' ), 'AMERICAN-EXPRESS');
  END

  IF EXISTS( Select PaymentCardId From CNF_PaymentCard where UPPER(CCDescription) like '%DINERS%' )
  BEGIN
    INSERT INTO CNF_PaymentCardCode ( PaymentCardId, PaymentCardCode )
    VALUES ( ( Select PaymentCardId From CNF_PaymentCard where UPPER(CCDescription) like '%DINERS%' ), 'DINERS-CLUB');
  END

  IF EXISTS( Select PaymentCardId From CNF_PaymentCard where UPPER(CCDescription) like '%MAESTRO%' )
  BEGIN
    INSERT INTO CNF_PaymentCardCode ( PaymentCardId, PaymentCardCode )
    VALUES ( ( Select PaymentCardId From CNF_PaymentCard where UPPER(CCDescription) like '%MAESTRO%' ), 'MAESTRO');
  END

  IF EXISTS( Select PaymentCardId From CNF_PaymentCard where UPPER(CCDescription) like '%UNIONPAY%' )
  BEGIN
    INSERT INTO CNF_PaymentCardCode ( PaymentCardId, PaymentCardCode )
    VALUES ( ( Select PaymentCardId From CNF_PaymentCard where UPPER(CCDescription) like '%UNIONPAY%' ), 'UNIONPAY');
  END
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AndreaDavanzo</ADDEDBY>
			<SQLVERSION>2122</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>Renaming all stored procedure</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>declare @oldval varchar(max)
declare @newval varchar(max)
declare myCurs CURSOR FOR
  select name
  from sys.procedures WHERE SUBSTRING(name,1,3) = 'sp_'

open myCurs
fetch next from myCurs into @oldval

while (@@FETCH_STATUS = 0)
begin
  set @newval = 'otn_' + @oldval
  EXEC sp_rename @oldval, @newval

  fetch next from myCurs into @oldval
end

close myCurs
deallocate myCurs</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>marcoviscusi</ADDEDBY>
			<SQLVERSION>2121</SQLVERSION>
			<RMTRACKLINK>65858</RMTRACKLINK>
			<REASON>Adding Mandatory field to CNF_Survey </REASON>
			<TABLENAMES>CNF_Survey=SurveyId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Mandatory' AND
                Object_ID  = Object_ID(N'CNF_Survey'))
BEGIN
  ALTER TABLE CNF_Survey ADD Mandatory SmallInt NOT NULL Default 0
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>kdixon</ADDEDBY>
			<SQLVERSION>2120</SQLVERSION>
			<RMTRACKLINK>66242</RMTRACKLINK>
			<REASON>Need to Add a Web Workstation Status Indicator on General Tab</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'WebSalesInd ' AND
                Object_ID  = Object_ID(N'CNF_Workstation'))
BEGIN
  ALTER TABLE CNF_Workstation ALTER COLUMN WebSalesInd Smallint NULL
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>blumsden</ADDEDBY>
			<SQLVERSION>2119</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>Creating Table CNF_PaymentCardCode
[0] Create CNF_PaymentCardCode

Add Foreign Key to CNF_PaymentCardCode
[1] Adding Foreign Key PaymentCardId</REASON>
			<TABLENAMES>CNF_PaymentCardCode=PaymentCardCodeId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (select * 
               from sys.tables 
               where NAME = 'CNF_PaymentCardCode')

BEGIN
Create table [CNF_PaymentCardCode]
(
	[PaymentCardCodeId] Integer Identity(1,1) NOT NULL,
	[PaymentCardId] Integer NOT NULL,
	[PaymentCardCode] Nvarchar(30) NOT NULL,
Primary Key ([PaymentCardCodeId])
) 
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_PaymentCardCode'
	          AND CONSTRAINT_NAME = N'fk_CNF_PaymentCardCode_PaymentCardId')          
BEGIN
  ALTER TABLE [CNF_PaymentCardCode] WITH CHECK 
  ADD  CONSTRAINT [fk_CNF_PaymentCardCode_PaymentCardId] FOREIGN KEY([PaymentCardId])
  REFERENCES [CNF_PaymentCard] ([PaymentCardId])
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AndreaDavanzo</ADDEDBY>
			<SQLVERSION>2118</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>Removed not used tables
[0] Drop CNF_ApprovalFlow2UserGroup
[1] Drop CNF_ApprovalFlag
[2] Drop CNF_ApprovalFlow
[3] Drop CNF_ApprovalEntity
[4..15] Drop All Stored Procedures</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * 
           FROM sys.tables 
           WHERE NAME = 'CNF_ApprovalFlow2UserGroup')
BEGIN
  DROP TABLE CNF_ApprovalFlow2UserGroup
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * 
           FROM sys.tables 
           WHERE NAME = 'CNF_ApprovalFlag')
BEGIN
  DROP TABLE CNF_ApprovalFlag
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * 
           FROM sys.tables 
           WHERE NAME = 'CNF_ApprovalEntity')
BEGIN
  DROP TABLE CNF_ApprovalEntity
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * 
           FROM sys.tables 
           WHERE NAME = 'CNF_ApprovalFlow')
BEGIN
  DROP TABLE CNF_ApprovalFlow
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS(SELECT * 
          FROM sys.procedures
          WHERE name = 'sp_ui_CNF_ApprovalFlow2UserGroup_delete')
BEGIN
  DROP PROCEDURE sp_ui_CNF_ApprovalFlow2UserGroup_delete
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS(SELECT * 
          FROM sys.procedures
          WHERE name = 'sp_ui_CNF_ApprovalFlow2UserGroup_update')
BEGIN
  DROP PROCEDURE sp_ui_CNF_ApprovalFlow2UserGroup_update
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS(SELECT * 
          FROM sys.procedures
          WHERE name = 'sp_ui_CNF_ApprovalFlow2UserGroup_insert')
BEGIN
  DROP PROCEDURE sp_ui_CNF_ApprovalFlow2UserGroup_insert
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS(SELECT * 
          FROM sys.procedures
          WHERE name = 'sp_ui_CNF_ApprovalFlow_delete')
BEGIN
  DROP PROCEDURE sp_ui_CNF_ApprovalFlow_delete
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS(SELECT * 
          FROM sys.procedures
          WHERE name = 'sp_ui_CNF_ApprovalFlow_update')
BEGIN
  DROP PROCEDURE sp_ui_CNF_ApprovalFlow_update
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS(SELECT * 
          FROM sys.procedures
          WHERE name = 'sp_ui_CNF_ApprovalFlow_insert')
BEGIN
  DROP PROCEDURE sp_ui_CNF_ApprovalFlow_insert
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS(SELECT * 
          FROM sys.procedures
          WHERE name = 'sp_ui_CNF_ApprovalFlag_delete')
BEGIN
  DROP PROCEDURE sp_ui_CNF_ApprovalFlag_delete
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS(SELECT * 
          FROM sys.procedures
          WHERE name = 'sp_ui_CNF_ApprovalFlag_update')
BEGIN
  DROP PROCEDURE sp_ui_CNF_ApprovalFlag_update
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS(SELECT * 
          FROM sys.procedures
          WHERE name = 'sp_ui_CNF_ApprovalFlag_insert')
BEGIN
  DROP PROCEDURE sp_ui_CNF_ApprovalFlag_insert
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS(SELECT * 
          FROM sys.procedures
          WHERE name = 'sp_ui_CNF_ApprovalEntity_delete')
BEGIN
  DROP PROCEDURE sp_ui_CNF_ApprovalEntity_delete
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS(SELECT * 
          FROM sys.procedures
          WHERE name = 'sp_ui_CNF_ApprovalEntity_update')
BEGIN
  DROP PROCEDURE sp_ui_CNF_ApprovalEntity_update
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS(SELECT * 
          FROM sys.procedures
          WHERE name = 'sp_ui_CNF_ApprovalEntity_insert')
BEGIN
  DROP PROCEDURE sp_ui_CNF_ApprovalEntity_insert
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>kdixon</ADDEDBY>
			<SQLVERSION>2117</SQLVERSION>
			<RMTRACKLINK>66242 </RMTRACKLINK>
			<REASON>Need to Add a Web Workstation Status Indicator on General Tab</REASON>
			<TABLENAMES>CNF_Workstation=WorkstationId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'WebSalesInd ' AND
                Object_ID  = Object_ID(N'CNF_Workstation'))
BEGIN
  ALTER TABLE CNF_Workstation ADD WebSalesInd SMALLINT NOT NULL DEFAULT 0
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
           WHERE Name = N'WebSalesInd' AND
           Object_ID  = Object_ID(N'CNF_Workstation'))
BEGIN
  UPDATE CNF_Workstation 
     SET WebSalesInd = 0 
   WHERE WebSalesInd IS NULL   

END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>jlaguardia</ADDEDBY>
			<SQLVERSION>2116</SQLVERSION>
			<RMTRACKLINK>65850</RMTRACKLINK>
			<REASON>Added UserGroupId column to DATA_Transaction</REASON>
			<TABLENAMES>DATA_Transaction=TransactionId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'UserGroupId ' AND
                Object_ID  = Object_ID(N'DATA_Transaction'))
BEGIN
  ALTER TABLE DATA_Transaction ADD UserGroupId Integer NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'DATA_Transaction'
	          AND CONSTRAINT_NAME = N'fk_DATA_Transaction_UserGroupId')          
BEGIN
  ALTER TABLE DATA_Transaction WITH CHECK 
  ADD  CONSTRAINT fk_DATA_Transaction_UserGroupId FOREIGN KEY(UserGroupId)
  REFERENCES [CNF_UserGroup] (UserGroupId)
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>blumsden</ADDEDBY>
			<SQLVERSION>2115</SQLVERSION>
			<RMTRACKLINK>66601</RMTRACKLINK>
			<REASON>Fix of PriceTableOption in CNF_PriceTable to NOT NULL </REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
           WHERE Name = N'PriceTableOption' AND
           Object_ID  = Object_ID(N'CNF_PriceTable'))
BEGIN
  UPDATE CNF_PriceTable 
     SET PriceTableOption = 0 
   WHERE PriceTableOption IS NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
           WHERE Name = N'PriceTableOption' AND
           Object_ID  = Object_ID(N'CNF_PriceTable'))
BEGIN
  ALTER TABLE CNF_PriceTable alter column PriceTableOption SMALLINT NOT NULL
END

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>jlaguardia</ADDEDBY>
			<SQLVERSION>2114</SQLVERSION>
			<RMTRACKLINK>62595</RMTRACKLINK>
			<REASON>Correcting mistake with timeformat</REASON>
			<TABLENAMES>DATA_Right=DataRightId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_Right 
   set StrValue = Replace(StrValue, 'nn', 'mm') 
 where RightId in (select RightId 
                     from CNF_Right 
                    where RightAK in ('LongTimeFormat', 'ShortTimeFormat'))
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fulviodipalma</ADDEDBY>
			<SQLVERSION>2113</SQLVERSION>
			<RMTRACKLINK>66202</RMTRACKLINK>
			<REASON>Add Table
CNF_Performance_Permission</REASON>
			<TABLENAMES>CNF_Performance_Permission=PerformancePermissionId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>if not exists (select * from sys.tables WHERE NAME = 'CNF_Performance_Permission')
begin              
Create table [CNF_Performance_Permission]
(
	[PerformancePermissionId] Integer Identity(1,1) NOT NULL,
	[PerformanceId] Integer NOT NULL,
	[SiteId] Integer NULL,
	[OperatingAreaId] Integer NULL,
	[WorkstationId] Integer NULL,
	[UserGroupId] Integer NULL,
	[UserId] Integer NULL,
	[DmgCategoryId] Integer NULL,
	[AccountId] Integer NULL,
	[Allow] Smallint NULL,
Primary Key ([PerformancePermissionId])
) 
end</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if not exists (SELECT
    K_Table = FK.TABLE_NAME,
    FK_Column = CU.COLUMN_NAME,
    PK_Table = PK.TABLE_NAME,
    PK_Column = PT.COLUMN_NAME,
    Constraint_Name = C.CONSTRAINT_NAME
FROM
    INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK
    ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK
    ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU
    ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
INNER JOIN (
            SELECT
                i1.TABLE_NAME,
                i2.COLUMN_NAME
            FROM
                INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1
            INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2
                ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME
            WHERE
                i1.CONSTRAINT_TYPE = 'PRIMARY KEY'
           ) PT
    ON PT.TABLE_NAME = PK.TABLE_NAME

where FK.TABLE_NAME = 'CNF_Performance_Permission' and CU.COLUMN_NAME = 'PerformancePermissionId' )
begin
 Alter table CNF_Performance_Permission add foreign key(PerformanceId) references
 CNF_Performance (PerformanceId) on update no action on delete no action
end

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if not exists (SELECT
    K_Table = FK.TABLE_NAME,
    FK_Column = CU.COLUMN_NAME,
    PK_Table = PK.TABLE_NAME,
    PK_Column = PT.COLUMN_NAME,
    Constraint_Name = C.CONSTRAINT_NAME
FROM
    INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK
    ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK
    ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU
    ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
INNER JOIN (
            SELECT
                i1.TABLE_NAME,
                i2.COLUMN_NAME
            FROM
                INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1
            INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2
                ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME
            WHERE
                i1.CONSTRAINT_TYPE = 'PRIMARY KEY'
           ) PT
    ON PT.TABLE_NAME = PK.TABLE_NAME

where FK.TABLE_NAME = 'CNF_Performance_Permission' and CU.COLUMN_NAME = 'SiteId' )
begin
 Alter table CNF_Performance_Permission add foreign key(SiteId) references 
 CNF_Site (SiteId) on update no action on delete no action
end

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if not exists (SELECT
    K_Table = FK.TABLE_NAME,
    FK_Column = CU.COLUMN_NAME,
    PK_Table = PK.TABLE_NAME,
    PK_Column = PT.COLUMN_NAME,
    Constraint_Name = C.CONSTRAINT_NAME
FROM
    INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK
    ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK
    ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU
    ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
INNER JOIN (
            SELECT
                i1.TABLE_NAME,
                i2.COLUMN_NAME
            FROM
                INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1
            INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2
                ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME
            WHERE
                i1.CONSTRAINT_TYPE = 'PRIMARY KEY'
           ) PT
    ON PT.TABLE_NAME = PK.TABLE_NAME

where FK.TABLE_NAME = 'CNF_Performance_Permission' and CU.COLUMN_NAME = 'OperatingAreaId' )
begin
Alter table CNF_Performance_Permission add foreign key(OperatingAreaId) 
references CNF_OperatingArea (OperatingAreaId) on update no action on delete no action
end



				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if not exists (SELECT
    K_Table = FK.TABLE_NAME,
    FK_Column = CU.COLUMN_NAME,
    PK_Table = PK.TABLE_NAME,
    PK_Column = PT.COLUMN_NAME,
    Constraint_Name = C.CONSTRAINT_NAME
FROM
    INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK
    ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK
    ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU
    ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
INNER JOIN (
            SELECT
                i1.TABLE_NAME,
                i2.COLUMN_NAME
            FROM
                INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1
            INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2
                ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME
            WHERE
                i1.CONSTRAINT_TYPE = 'PRIMARY KEY'
           ) PT
    ON PT.TABLE_NAME = PK.TABLE_NAME

where FK.TABLE_NAME = 'CNF_Performance_Permission' and CU.COLUMN_NAME = 'WorkstationId' )
begin
Alter table CNF_Performance_Permission add foreign key(WorkstationId) 
references CNF_Workstation (WorkstationId) on update no action on delete no action
end

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if not exists (SELECT
    K_Table = FK.TABLE_NAME,
    FK_Column = CU.COLUMN_NAME,
    PK_Table = PK.TABLE_NAME,
    PK_Column = PT.COLUMN_NAME,
    Constraint_Name = C.CONSTRAINT_NAME
FROM
    INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK
    ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK
    ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU
    ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
INNER JOIN (
            SELECT
                i1.TABLE_NAME,
                i2.COLUMN_NAME
            FROM
                INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1
            INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2
                ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME
            WHERE
                i1.CONSTRAINT_TYPE = 'PRIMARY KEY'
           ) PT
    ON PT.TABLE_NAME = PK.TABLE_NAME

where FK.TABLE_NAME = 'CNF_Performance_Permission' and CU.COLUMN_NAME = 'UserGroupId' )
begin
Alter table CNF_Performance_Permission add foreign key(UserGroupId) 
references CNF_UserGroup (UserGroupId) on update no action on delete no action
end


				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if not exists (SELECT
    K_Table = FK.TABLE_NAME,
    FK_Column = CU.COLUMN_NAME,
    PK_Table = PK.TABLE_NAME,
    PK_Column = PT.COLUMN_NAME,
    Constraint_Name = C.CONSTRAINT_NAME
FROM
    INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK
    ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK
    ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU
    ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
INNER JOIN (
            SELECT
                i1.TABLE_NAME,
                i2.COLUMN_NAME
            FROM
                INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1
            INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2
                ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME
            WHERE
                i1.CONSTRAINT_TYPE = 'PRIMARY KEY'
           ) PT
    ON PT.TABLE_NAME = PK.TABLE_NAME

where FK.TABLE_NAME = 'CNF_Performance_Permission' and CU.COLUMN_NAME = 'UserId' )
begin
Alter table CNF_Performance_Permission add foreign key(UserId) 
references CNF_User (UserId) on update no action on delete no action
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if not exists (SELECT
    K_Table = FK.TABLE_NAME,
    FK_Column = CU.COLUMN_NAME,
    PK_Table = PK.TABLE_NAME,
    PK_Column = PT.COLUMN_NAME,
    Constraint_Name = C.CONSTRAINT_NAME
FROM
    INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK
    ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK
    ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU
    ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
INNER JOIN (
            SELECT
                i1.TABLE_NAME,
                i2.COLUMN_NAME
            FROM
                INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1
            INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2
                ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME
            WHERE
                i1.CONSTRAINT_TYPE = 'PRIMARY KEY'
           ) PT
    ON PT.TABLE_NAME = PK.TABLE_NAME

where FK.TABLE_NAME = 'CNF_Performance_Permission' and CU.COLUMN_NAME = 'DmgCategoryId' )
begin
Alter table CNF_Performance_Permission add foreign key(DmgCategoryId) 
references CNF_DmgCategory (DmgCategoryId) on update no action on delete no action
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if not exists (SELECT
    K_Table = FK.TABLE_NAME,
    FK_Column = CU.COLUMN_NAME,
    PK_Table = PK.TABLE_NAME,
    PK_Column = PT.COLUMN_NAME,
    Constraint_Name = C.CONSTRAINT_NAME
FROM
    INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK
    ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK
    ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU
    ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
INNER JOIN (
            SELECT
                i1.TABLE_NAME,
                i2.COLUMN_NAME
            FROM
                INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1
            INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2
                ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME
            WHERE
                i1.CONSTRAINT_TYPE = 'PRIMARY KEY'
           ) PT
    ON PT.TABLE_NAME = PK.TABLE_NAME

where FK.TABLE_NAME = 'CNF_Performance_Permission' and CU.COLUMN_NAME = 'AccountId' )
begin
Alter table CNF_Performance_Permission add foreign key(AccountId) 
references DATA_Account (AccountId) on update no action on delete no action
end

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AndreaDavanzo</ADDEDBY>
			<SQLVERSION>2112</SQLVERSION>
			<RMTRACKLINK>61570</RMTRACKLINK>
			<REASON>Alter table alter column TicketId int NULL</REASON>
			<TABLENAMES>SIAE_VroRelationships=VroRelationshipsId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
           WHERE Name = N'TicketId' AND
           Object_ID  = Object_ID(N'SIAE_VroRelationships'))
BEGIN
  ALTER TABLE SIAE_VroRelationships ALTER COLUMN TicketId int NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>blumsden</ADDEDBY>
			<SQLVERSION>2111</SQLVERSION>
			<RMTRACKLINK>66601 </RMTRACKLINK>
			<REASON>Adding IsSeasonal field to CNF_MatrixSheet
[0] Adding column IsSeasonal

Adding PriceTableOption field to CNF_PriceTable
[1] Adding column PriceTableOption 

Adding SeasonalPriceTableId field to CNF_Performance
[2] Adding column SeasonalPriceTableId</REASON>
			<TABLENAMES>CNF_MatrixSheet=MatrixSheetId
CNF_PriceTable=PriceTableId
CNF_Performance=PerformanceId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'IsSeasonal' AND
                Object_ID  = Object_ID(N'CNF_MatrixSheet'))
BEGIN
  ALTER TABLE CNF_MatrixSheet ADD IsSeasonal SmallInt NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'PriceTableOption' AND
                Object_ID  = Object_ID(N'CNF_PriceTable'))
BEGIN
  ALTER TABLE CNF_PriceTable ADD PriceTableOption SmallInt NOT NULL DEFAULT 0
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'SeasonalPriceTableId ' AND
                Object_ID  = Object_ID(N'CNF_Performance'))
BEGIN
  ALTER TABLE CNF_Performance ADD SeasonalPriceTableId Integer NULL
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_Performance'
	          AND CONSTRAINT_NAME = N'fk_CNF_Performance_SeasonalPriceTableId')          
BEGIN
  ALTER TABLE [CNF_Performance] WITH CHECK 
  ADD  CONSTRAINT [fk_CNF_Performance_SeasonalPriceTableId] FOREIGN KEY([SeasonalPriceTableId])
  REFERENCES [CNF_PriceTable] ([PriceTableId])
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AndreaDavanzo</ADDEDBY>
			<SQLVERSION>2110</SQLVERSION>
			<RMTRACKLINK>61570</RMTRACKLINK>
			<REASON>Created table to keep the relationships between the account ids and the VRO account identity after the verification call
[0] Create table SIAE_VroRelationships
[1..4] Create Indexes</REASON>
			<TABLENAMES>SIAE_VroRelationships=VroRelationshipsId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (select * 
               from sys.tables 
               where NAME = 'SIAE_VroRelationships')
BEGIN
  Create table [SIAE_VroRelationships]
  (
	[VroRelationshipsId] Integer Identity(1,1) NOT NULL,
	[AccountId] Integer NOT NULL,
	[PerformanceId] Integer NOT NULL,
	[VroMessagesId] Integer NOT NULL,
	[SaleItemId] Integer NOT NULL,
	[TicketId] Integer NOT NULL,
	[VroAccountId] Nvarchar(10) NULL,
	[Status] Smallint Default 0 NOT NULL,
	[Date] Datetime NULL,
    Primary Key ([VroRelationshipsId])
  )
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * 
               FROM sys.indexes  
               WHERE name='Idx_VroRel_Account_Perf_SaleItem' AND object_id = OBJECT_ID('SIAE_VroRelationships'))
BEGIN
  Create Index [Idx_VroRel_Account_Perf_SaleItem] ON [SIAE_VroRelationships] ([AccountId] ,[PerformanceId] ,[SaleItemId] )
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * 
               FROM sys.indexes  
               WHERE name='Idx_VroRel_SaleItem_Ticket' AND object_id = OBJECT_ID('SIAE_VroRelationships'))
BEGIN
  Create Index [Idx_VroRel_SaleItem_Ticket] ON [SIAE_VroRelationships] ([SaleItemId] ,[TicketId] )
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * 
               FROM sys.indexes  
               WHERE name='Idx_VroRel_Account_Perf_VroAccountId' AND object_id = OBJECT_ID('SIAE_VroRelationships'))
BEGIN
  Create Index [Idx_VroRel_Account_Perf_VroAccountId] ON [SIAE_VroRelationships] ([AccountId] ,[PerformanceId] ,[VroAccountId] )
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * 
               FROM sys.indexes  
               WHERE name='Idx_VroRel_VroAccountId' AND object_id = OBJECT_ID('SIAE_VroRelationships'))
BEGIN
  Create Index [Idx_VroRel_VroAccountId] ON [SIAE_VroRelationships] ([VroAccountId] )
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>2109</SQLVERSION>
			<RMTRACKLINK>65981</RMTRACKLINK>
			<REASON>
CNF_MatrixCellInfo
Add new fields:
 - MaskFieldEditLevel  -  smallint null
 - MaskFieldVisibleLevel  -  smallint null
 - MaskFieldRequiredLevel - smallint null

[0] - Add Field MaskFieldEditLevel 
[1] - Add Field MaskFieldVisibleLevel  
[2] - Add Field MaskFieldRequiredLevel


			</REASON>
			<TABLENAMES>CNF_MatrixCellInfo=MatrixCellInfoId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>

IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'MaskFieldEditLevel' AND
                Object_ID  = Object_ID(N'CNF_MatrixCellInfo'))
BEGIN
  alter table CNF_MatrixCellInfo add MaskFieldEditLevel smallint  null
END

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>

IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'MaskFieldVisibleLevel' AND
                Object_ID  = Object_ID(N'CNF_MatrixCellInfo'))
BEGIN
  alter table CNF_MatrixCellInfo add MaskFieldVisibleLevel smallint  null
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>


IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'MaskFieldRequiredLevel' AND
                Object_ID  = Object_ID(N'CNF_MatrixCellInfo'))
BEGIN
  alter table CNF_MatrixCellInfo add MaskFieldRequiredLevel smallint  null
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>2108</SQLVERSION>
			<RMTRACKLINK>65979</RMTRACKLINK>
			<REASON>
CNF_DataMask 
Add new field  RequiredLevel smallint null

[0] - Add Field RequiredLevel

			</REASON>
			<TABLENAMES>CNF_DataMask=DataMaskId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>

IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'RequiredLevel' AND
                Object_ID  = Object_ID(N'CNF_DataMask'))
BEGIN
  alter table CNF_DataMask add RequiredLevel smallint  null
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>marcoviscusi</ADDEDBY>
			<SQLVERSION>2107</SQLVERSION>
			<RMTRACKLINK>65987</RMTRACKLINK>
			<REASON>Removed Index WalletKey</REASON>
			<TABLENAMES>DATA_Ticket=TicketId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT name FROM sys.indexes WHERE name =   
            N'IDX_Ticket_WalletKey')  
    DROP INDEX  
        IDX_Ticket_WalletKey   
    ON DATA_Ticket;  
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fulviodipalma</ADDEDBY>
			<SQLVERSION>2106</SQLVERSION>
			<RMTRACKLINK>65984</RMTRACKLINK>
			<REASON>Add Table
CNF_MatrixCellPermission</REASON>
			<TABLENAMES>CNF_MatrixCellPermission=MatrixCellPermissionId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>if not exists (select * from sys.tables WHERE NAME = 'CNF_MatrixCellPermission')
begin              
Create table [CNF_MatrixCellPermission]
(
	[MatrixCellPermissionId] Integer Identity(1,1) NOT NULL,
	[MatrixCellId] Integer NOT NULL,
	[SiteId] Integer NULL,
	[OperatingAreaId] Integer NULL,
	[WorkstationId] Integer NULL,
	[UserGroupId] Integer NULL,
	[UserId] Integer NULL,
	[DmgCategoryId] Integer NULL,
	[AccountId] Integer NULL,
	[Allow] Smallint NULL,
Primary Key ([MatrixCellPermissionId])
) 
end</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if not exists (SELECT
    K_Table = FK.TABLE_NAME,
    FK_Column = CU.COLUMN_NAME,
    PK_Table = PK.TABLE_NAME,
    PK_Column = PT.COLUMN_NAME,
    Constraint_Name = C.CONSTRAINT_NAME
FROM
    INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK
    ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK
    ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU
    ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
INNER JOIN (
            SELECT
                i1.TABLE_NAME,
                i2.COLUMN_NAME
            FROM
                INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1
            INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2
                ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME
            WHERE
                i1.CONSTRAINT_TYPE = 'PRIMARY KEY'
           ) PT
    ON PT.TABLE_NAME = PK.TABLE_NAME

where FK.TABLE_NAME = 'CNF_MatrixCellPermission' and CU.COLUMN_NAME = 'MatrixCellPermissionId' )
begin
Alter table CNF_MatrixCellPermission add foreign key(MatrixCellId) 
references CNF_MatrixCell (MatrixCellId) on update no action on delete no action
end

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if not exists (SELECT
    K_Table = FK.TABLE_NAME,
    FK_Column = CU.COLUMN_NAME,
    PK_Table = PK.TABLE_NAME,
    PK_Column = PT.COLUMN_NAME,
    Constraint_Name = C.CONSTRAINT_NAME
FROM
    INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK
    ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK
    ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU
    ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
INNER JOIN (
            SELECT
                i1.TABLE_NAME,
                i2.COLUMN_NAME
            FROM
                INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1
            INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2
                ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME
            WHERE
                i1.CONSTRAINT_TYPE = 'PRIMARY KEY'
           ) PT
    ON PT.TABLE_NAME = PK.TABLE_NAME

where FK.TABLE_NAME = 'CNF_MatrixCellPermission' and CU.COLUMN_NAME = 'SiteId' )
begin
 Alter table CNF_MatrixCellPermission add foreign key(SiteId) references 
 CNF_Site (SiteId) on update no action on delete no action
end

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if not exists (SELECT
    K_Table = FK.TABLE_NAME,
    FK_Column = CU.COLUMN_NAME,
    PK_Table = PK.TABLE_NAME,
    PK_Column = PT.COLUMN_NAME,
    Constraint_Name = C.CONSTRAINT_NAME
FROM
    INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK
    ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK
    ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU
    ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
INNER JOIN (
            SELECT
                i1.TABLE_NAME,
                i2.COLUMN_NAME
            FROM
                INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1
            INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2
                ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME
            WHERE
                i1.CONSTRAINT_TYPE = 'PRIMARY KEY'
           ) PT
    ON PT.TABLE_NAME = PK.TABLE_NAME

where FK.TABLE_NAME = 'CNF_MatrixCellPermission' and CU.COLUMN_NAME = 'OperatingAreaId' )
begin
Alter table CNF_MatrixCellPermission add foreign key(OperatingAreaId) 
references CNF_OperatingArea (OperatingAreaId) on update no action on delete no action
end



				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if not exists (SELECT
    K_Table = FK.TABLE_NAME,
    FK_Column = CU.COLUMN_NAME,
    PK_Table = PK.TABLE_NAME,
    PK_Column = PT.COLUMN_NAME,
    Constraint_Name = C.CONSTRAINT_NAME
FROM
    INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK
    ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK
    ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU
    ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
INNER JOIN (
            SELECT
                i1.TABLE_NAME,
                i2.COLUMN_NAME
            FROM
                INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1
            INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2
                ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME
            WHERE
                i1.CONSTRAINT_TYPE = 'PRIMARY KEY'
           ) PT
    ON PT.TABLE_NAME = PK.TABLE_NAME

where FK.TABLE_NAME = 'CNF_MatrixCellPermission' and CU.COLUMN_NAME = 'WorkstationId' )
begin
Alter table CNF_MatrixCellPermission add foreign key(WorkstationId) 
references CNF_Workstation (WorkstationId) on update no action on delete no action
end

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if not exists (SELECT
    K_Table = FK.TABLE_NAME,
    FK_Column = CU.COLUMN_NAME,
    PK_Table = PK.TABLE_NAME,
    PK_Column = PT.COLUMN_NAME,
    Constraint_Name = C.CONSTRAINT_NAME
FROM
    INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK
    ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK
    ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU
    ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
INNER JOIN (
            SELECT
                i1.TABLE_NAME,
                i2.COLUMN_NAME
            FROM
                INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1
            INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2
                ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME
            WHERE
                i1.CONSTRAINT_TYPE = 'PRIMARY KEY'
           ) PT
    ON PT.TABLE_NAME = PK.TABLE_NAME

where FK.TABLE_NAME = 'CNF_MatrixCellPermission' and CU.COLUMN_NAME = 'UserGroupId' )
begin
Alter table CNF_MatrixCellPermission add foreign key(UserGroupId) 
references CNF_UserGroup (UserGroupId) on update no action on delete no action
end


				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if not exists (SELECT
    K_Table = FK.TABLE_NAME,
    FK_Column = CU.COLUMN_NAME,
    PK_Table = PK.TABLE_NAME,
    PK_Column = PT.COLUMN_NAME,
    Constraint_Name = C.CONSTRAINT_NAME
FROM
    INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK
    ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK
    ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU
    ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
INNER JOIN (
            SELECT
                i1.TABLE_NAME,
                i2.COLUMN_NAME
            FROM
                INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1
            INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2
                ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME
            WHERE
                i1.CONSTRAINT_TYPE = 'PRIMARY KEY'
           ) PT
    ON PT.TABLE_NAME = PK.TABLE_NAME

where FK.TABLE_NAME = 'CNF_MatrixCellPermission' and CU.COLUMN_NAME = 'UserId' )
begin
Alter table CNF_MatrixCellPermission add foreign key(UserId) 
references CNF_User (UserId) on update no action on delete no action
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if not exists (SELECT
    K_Table = FK.TABLE_NAME,
    FK_Column = CU.COLUMN_NAME,
    PK_Table = PK.TABLE_NAME,
    PK_Column = PT.COLUMN_NAME,
    Constraint_Name = C.CONSTRAINT_NAME
FROM
    INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK
    ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK
    ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU
    ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
INNER JOIN (
            SELECT
                i1.TABLE_NAME,
                i2.COLUMN_NAME
            FROM
                INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1
            INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2
                ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME
            WHERE
                i1.CONSTRAINT_TYPE = 'PRIMARY KEY'
           ) PT
    ON PT.TABLE_NAME = PK.TABLE_NAME

where FK.TABLE_NAME = 'CNF_MatrixCellPermission' and CU.COLUMN_NAME = 'DmgCategoryId' )
begin
Alter table CNF_MatrixCellPermission add foreign key(DmgCategoryId) 
references CNF_DmgCategory (DmgCategoryId) on update no action on delete no action
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if not exists (SELECT
    K_Table = FK.TABLE_NAME,
    FK_Column = CU.COLUMN_NAME,
    PK_Table = PK.TABLE_NAME,
    PK_Column = PT.COLUMN_NAME,
    Constraint_Name = C.CONSTRAINT_NAME
FROM
    INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK
    ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK
    ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU
    ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
INNER JOIN (
            SELECT
                i1.TABLE_NAME,
                i2.COLUMN_NAME
            FROM
                INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1
            INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2
                ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME
            WHERE
                i1.CONSTRAINT_TYPE = 'PRIMARY KEY'
           ) PT
    ON PT.TABLE_NAME = PK.TABLE_NAME

where FK.TABLE_NAME = 'CNF_MatrixCellPermission' and CU.COLUMN_NAME = 'AccountId' )
begin
Alter table CNF_MatrixCellPermission add foreign key(AccountId) 
references DATA_Account (AccountId) on update no action on delete no action
end

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>2105</SQLVERSION>
			<RMTRACKLINK>65679</RMTRACKLINK>
			<REASON>
CNF_MatrixCellInfo 
Add two new fields related to SIAE - Vendita Conto Terzi - ISSUE 65679

[0] - Add Field SiaeVenditaContoTerzi
[1] - update Old Data
[2] - Set Not null

[3] - Add Field SiaeVenditaContoTerziDesc NVARCHAR(40)

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

CNF_Performance 
Add Fields HasCapacity  - NO ISSUE

[4] - Add Field HasCapacity
[5] - update Old Data
[6] - Set Not null

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

CNF_Performance 
Add Fields HasSeat  - NO ISSUE

[7] - Add Field HasSeat
[8] - update Old Data
[9] - Set Not null

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

CNF_Event - Add field IsResourceManagementEvent - NO ISSUE

[10] - Add Fields
[11-12] - update Old Data
[13] - Set Not null

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


CNF_Workstation - Add Field HasApt  - NO ISSUE
[14] - Add Field HasApt  
[15-16] - update Old Data
[17] - Set Not null








			</REASON>
			<TABLENAMES>CNF_MatrixCellInfo=MatrixCellInfoId
CNF_Performance=PerformanceId
CNF_Event=EventId
CNF_Workstation=WorkstationId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>
IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'SiaeVenditaContoTerzi' AND
                Object_ID  = Object_ID(N'CNF_MatrixCellInfo'))
BEGIN
  alter table CNF_MatrixCellInfo add SiaeVenditaContoTerzi smallint  null
END


				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>
update CNF_MatrixCellInfo set SiaeVenditaContoTerzi = 0
where SiaeVenditaContoTerzi is null


				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>
alter table CNF_MatrixCellInfo 
   alter column SiaeVenditaContoTerzi smallint not null

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>

IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'SiaeVenditaContoTerziDesc' AND
                Object_ID  = Object_ID(N'CNF_MatrixCellInfo'))
BEGIN
  alter table CNF_MatrixCellInfo add SiaeVenditaContoTerziDesc NVarChar(40) null
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>
IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'HasCapacity' AND
                Object_ID  = Object_ID(N'CNF_Performance'))
BEGIN
  alter table CNF_Performance add HasCapacity smallint  null
END




				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>
update CNF_Performance set HasCapacity = 0
where HasCapacity is null


				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>

update CNF_Performance set HasCapacity = 1 where PerformanceId in (
select PER.PerformanceId
from 
  CNF_EnvelopeCapacity as EC
  inner join CNF_SeatCategory as SC on (SC.SeatCategoryId = EC.SeatCategoryId)
  inner join CNF_Performance as PER on (PER.PerformanceId = SC.PerformanceId)
  )
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>


alter table CNF_Performance 
   alter column HasCapacity smallint not null

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>

IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'HasSeat' AND
                Object_ID  = Object_ID(N'CNF_Performance'))
BEGIN
  alter table CNF_Performance add HasSeat smallint  null
END

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>


update CNF_Performance set HasSeat = 0
where HasSeat is null</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>

update CNF_Performance set HasSeat = 1 where PerformanceId in (
  select distinct PerformanceId from CNF_Seat
 )   </SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>

alter table CNF_Performance 
   alter column HasSeat smallint not null

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>


IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'IsResourceManagementEvent' AND
                Object_ID  = Object_ID(N'CNF_Event'))
BEGIN
  alter table CNF_Event  add IsResourceManagementEvent smallint  null
END

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>


update CNF_Event set IsResourceManagementEvent = 0
where IsResourceManagementEvent is null

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>


update CNF_Event set IsResourceManagementEvent = 1
where EventId in (

select distinct EventId from RES_CNF_Event where AllocateResource = 1
)

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>

alter table CNF_Event 
   alter column  IsResourceManagementEvent smallint not null

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>


IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'HasApt' AND
                Object_ID  = Object_ID(N'CNF_Workstation'))
BEGIN
  alter table CNF_Workstation add HasApt smallint  null
END


				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>

update CNF_Workstation set HasApt = 0
where HasApt is null</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>


update CNF_Workstation set HAsApt = 1 
where WorkstationId in 
(
  select distinct ParentWorkStationId  from ADM_AccessPoint
)
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>
alter table CNF_Workstation 
  alter column HasApt smallint not null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>jlaguardia</ADDEDBY>
			<SQLVERSION>2104</SQLVERSION>
			<RMTRACKLINK>65797</RMTRACKLINK>
			<REASON>Added 2 columns

Column info:
CNF_User2Group.IsDefault (smallint - 0, 1 or null default)
Purpose:
To identify "default" role where UserId and IsDefault = 1. There should only be 1 value of 1 per UserId

Column info:
DATA_UserLog.UserGroupId (int  FK ref to CNF_UserGroup)
Purpose:
For logging active role for users who access BOS</REASON>
			<TABLENAMES>CNF_User2Group=User2Group
DATA_UserLog=LogID</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
               WHERE Name = N'IsDefault' AND
               Object_ID  = Object_ID(N'CNF_User2Group')) 
  BEGIN
	ALTER TABLE CNF_User2Group 
	ADD IsDefault smallint 
  END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
               WHERE Name = N'UserGroupId' AND
               Object_ID  = Object_ID(N'DATA_UserLog')) 
  BEGIN
	ALTER TABLE DATA_UserLog 
	ADD UserGroupId integer
  END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'DATA_UserLog'
	          AND CONSTRAINT_NAME = N'fk_DATA_UserLog_UserGroupId')          
BEGIN
  ALTER TABLE [DATA_UserLog] WITH CHECK 
  ADD  CONSTRAINT [fk_DATA_UserLog_UserGroupId] FOREIGN KEY([UserGroupId])
  REFERENCES [CNF_UserGroup] ([UserGroupId])
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>2103</SQLVERSION>
			<RMTRACKLINK>64911 </RMTRACKLINK>
			<REASON>[0] Add Index  DATA_SaleItemRules         -&gt; SaleItemId
[1] Add  Index DATA_SalePromotionRule -&gt; SaleItemId
[2] Add Index DATA_SaleItemTax            -&gt; SaleItemdId
[3] Add Index DATA_TransactionTax       -&gt; TransactionId
[4] se User Type according to new LookUp</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT (EXISTS (SELECT *  FROM sys.indexes  WHERE name='Idx_DATA_SaleItemRule_SaleItemId' AND object_id = OBJECT_ID('DATA_SaleItemRule')))
BEGIN
  Create Index [Idx_DATA_SaleItemRule_SaleItemId] ON [DATA_SaleItemRule] ([SaleItemId] )              
 END    
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT (EXISTS (SELECT *  FROM sys.indexes  WHERE name='Idx_Data_SalePromotionRule_SaleItemId' AND object_id = OBJECT_ID('Data_SalePromotionRule')))
BEGIN
  Create Index [Idx_Data_SalePromotionRule_SaleItemId] ON [Data_SalePromotionRule] ([SaleItemId] )              
 END    
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT (EXISTS (SELECT *  FROM sys.indexes  WHERE name='Idx_Data_SaleItemTax_SaleItemId' AND object_id = OBJECT_ID('Data_SaleItemTax')))
BEGIN
  Create Index [Idx_Data_SaleItemTax_SaleItemId] ON [Data_SaleItemTax] ([SaleItemId] )              
 END    

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT (EXISTS (SELECT *  FROM sys.indexes  WHERE name='Idx_Data_TransactionTax_TransactionId' AND object_id = OBJECT_ID('Data_TransactionTax')))
BEGIN
  Create Index [Idx_Data_TransactionTax_TransactionId] ON [Data_TransactionTax] ([TransactionId])              
 END    


				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_User
  set UserType = 1 where userCode &lt;&gt; 'SYSTEM'

update CNF_User
  set UserType = 2 where userCode = 'SYSTEM'</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>blumsden</ADDEDBY>
			<SQLVERSION>2102</SQLVERSION>
			<RMTRACKLINK>66099</RMTRACKLINK>
			<REASON>Modify Table CNF_SeasonalRule
[0] Change DiscountValue to Float</REASON>
			<TABLENAMES>CNF_SeasonalRule=SeasonalRuleId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'DiscountValue' AND
                Object_ID  = Object_ID(N'CNF_SeasonalRule') AND
                system_type_id = 62) 

BEGIN
  ALTER TABLE CNF_SeasonalRule 
   ALTER COLUMN DiscountValue Float
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>marcoviscusi</ADDEDBY>
			<SQLVERSION>2101</SQLVERSION>
			<RMTRACKLINK>65996</RMTRACKLINK>
			<REASON>Create Table CNF_Delivery
[0]Create Table CNF_Delivery
[1]Add Foreign Key DmgCategoryId
[2]Add Foreign Key ExtendedInfoId</REASON>
			<TABLENAMES>CNF_Delivery=DeliveryID</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'CNF_Delivery'))

BEGIN
   Create table [CNF_Delivery]
  (
 	[DeliveryId] Integer Identity(1,1) NOT NULL, UNIQUE ([DeliveryId]),
	[DeliveryAK] [varchar](32) NOT NULL,
	[Code] [nvarchar] (10),
	[Description] [nvarchar](50),
        [Price] [Float] NOT NULL,
        [PriceType] [smallint],
        [DaysBefore] [int],
        [SortOrder] [smallint],
	[DmgCategoryId] [int] NULL,   
	[ExtendedInfoId] [int] NULL   
  Primary Key ([DeliveryId])
  ) 
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE CNF_Delivery  WITH CHECK ADD FOREIGN KEY(DmgCategoryId)
REFERENCES CNF_DmgCategory (DmgCategoryId)</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE CNF_Delivery  WITH CHECK ADD FOREIGN KEY(ExtendedInfoId)
REFERENCES CNF_DmgCategory (DmgCategoryId)</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>blumsden</ADDEDBY>
			<SQLVERSION>2100</SQLVERSION>
			<RMTRACKLINK>66099</RMTRACKLINK>
			<REASON>Create Table CNF_SeasonalRule
[0] Create Table</REASON>
			<TABLENAMES>CNF_SeasonalRule=SeasonalRuleId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND TABLE_NAME = 'CNF_SeasonalRule'))

BEGIN
	Create table [CNF_SeasonalRule]
	(
		[SeasonalRuleId] Integer Identity (1,1) NOT NULL, UNIQUE ([SeasonalRuleId]),
		[Code] nvarchar(10) NOT NULL,
		[Name] nvarchar(50) NOT NULL,
		[Description] ntext NULL,
                [Enabled] SmallInt NOT NULL,
		[IncrementType] SmallInt NULL,
		[IncrementValue] SmallInt NULL,
                [CalculationType] SmallInt NULL,
                [DiscountType] SmallInt NULL,
                [DiscountValue] SmallInt NULL
	Primary Key ([SeasonalRuleId])
	) 
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AndreaDavanzo</ADDEDBY>
			<SQLVERSION>2099</SQLVERSION>
			<RMTRACKLINK>61570</RMTRACKLINK>
			<REASON>Adding ExternalId field to DATA_Media for TdT purpose
[0] Adding column ExternalId</REASON>
			<TABLENAMES>DATA_Media=MediaId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'ExternalId' AND
                Object_ID  = Object_ID(N'DATA_Media'))
BEGIN
  ALTER TABLE DATA_Media ADD ExternalId Integer NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>mkimball</ADDEDBY>
			<SQLVERSION>2098</SQLVERSION>
			<RMTRACKLINK>65498</RMTRACKLINK>
			<REASON>Added a new field (ReprintCounter) to DATA_Ticket</REASON>
			<TABLENAMES>DATA_Ticket=TicketId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'ReprintCounter' AND
                Object_ID  = Object_ID(N'DATA_Ticket'))
BEGIN
  ALTER TABLE DATA_Ticket ADD ReprintCounter Integer NOT NULL DEFAULT 0
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AndreaDavanzo</ADDEDBY>
			<SQLVERSION>2097</SQLVERSION>
			<RMTRACKLINK>61570</RMTRACKLINK>
			<REASON>Adding column TdT_TypeId to the SIAE_System
[0] Add column TdT_TypeId</REASON>
			<TABLENAMES>SIAE_System=SystemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'TdT_TypeId' AND
                Object_ID  = Object_ID(N'SIAE_System'))
BEGIN
  ALTER TABLE SIAE_System ADD TdT_TypeId Integer NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>marcoviscusi</ADDEDBY>
			<SQLVERSION>2096</SQLVERSION>
			<RMTRACKLINK>65996</RMTRACKLINK>
			<REASON>DATA_Ticket
[3] add new filed DeliveryType
[4] set default Value
[5] set field as not Null</REASON>
			<TABLENAMES>DATA_Ticket=TicketId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'DeliveryType' AND
                Object_ID  = Object_ID(N'DATA_Ticket'))
BEGIN
  ALTER TABLE DATA_Ticket ADD DeliveryType Smallint NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>UPDATE DATA_Ticket SET DeliveryType = 0</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> ALTER TABLE DATA_Ticket
  ALTER COLUMN DeliveryType Smallint NOT NULL</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Federico Caramella</ADDEDBY>
			<SQLVERSION>2095</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.9.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Federico Caramella</ADDEDBY>
			<SQLVERSION>2094</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.9.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Federico Caramella</ADDEDBY>
			<SQLVERSION>2093</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Federico Caramella</ADDEDBY>
			<SQLVERSION>2092</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Federico Caramella</ADDEDBY>
			<SQLVERSION>2091</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Federico Caramella</ADDEDBY>
			<SQLVERSION>2090</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Federico Caramella</ADDEDBY>
			<SQLVERSION>2089</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Federico Caramella</ADDEDBY>
			<SQLVERSION>2088</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Federico Caramella</ADDEDBY>
			<SQLVERSION>2087</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Federico Caramella</ADDEDBY>
			<SQLVERSION>2086</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Federico Caramella</ADDEDBY>
			<SQLVERSION>2085</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Federico Caramella</ADDEDBY>
			<SQLVERSION>2084</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Federico Caramella</ADDEDBY>
			<SQLVERSION>2083</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Federico Caramella</ADDEDBY>
			<SQLVERSION>2082</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Federico Caramella</ADDEDBY>
			<SQLVERSION>2081</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Federico Caramella</ADDEDBY>
			<SQLVERSION>2080</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Federico Caramella</ADDEDBY>
			<SQLVERSION>2079</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Federico Caramella</ADDEDBY>
			<SQLVERSION>2078</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.9.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Federico Caramella</ADDEDBY>
			<SQLVERSION>2077</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.9.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Federico Caramella</ADDEDBY>
			<SQLVERSION>2076</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.9.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************
			</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AndreaDavanzo</ADDEDBY>
			<SQLVERSION>2075</SQLVERSION>
			<RMTRACKLINK>61570</RMTRACKLINK>
			<REASON>Create table SIAE_VroMessages
[0] Create table
[1] Create index on RequestType &amp; ExternalId
[2] Create index on RequestDate</REASON>
			<TABLENAMES>SIAE_VroMessages=VroMessagesId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND TABLE_NAME = 'SIAE_VroMessages'))

BEGIN
	Create table [SIAE_VroMessages]
	(
		[VroMessagesId] Integer Identity (1,1) NOT NULL, UNIQUE ([VroMessagesId]),
		[RequestType] Integer NULL,
		[RequestMessage] xml NULL,
		[ResponseMessage] xml NULL,
		[RequestDate] Datetime NULL,
		[ExternalId] Integer NOT NULL,
	Primary Key ([VroMessagesId])
	) 
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.indexes 
               WHERE Name = N'Idx_VroMex_RequestType' AND 
                     object_id = OBJECT_ID(N'SIAE_VroMessages'))
BEGIN
	Create Index [Idx_VroMex_RequestType] ON [SIAE_VroMessages] ([RequestType] ,[ExternalId] ) 
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.indexes 
               WHERE Name = N'Idx_VroMex_Date' AND 
                     object_id = OBJECT_ID(N'SIAE_VroMessages'))
BEGIN
	Create Index [Idx_VroMex_Date] ON [SIAE_VroMessages] ([RequestDate] ) 
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>marcoviscusi</ADDEDBY>
			<SQLVERSION>2074</SQLVERSION>
			<RMTRACKLINK>63658</RMTRACKLINK>
			<REASON>CNF_System
[3] add new filed Cost Tax Exclude
[4] set default Value
[5] set field as not Null</REASON>
			<TABLENAMES>CNF_System=SystemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'CostTaxExcluded' AND
                Object_ID  = Object_ID(N'CNF_System'))
BEGIN
  ALTER TABLE CNF_System ADD CostTaxExcluded Smallint NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>UPDATE CNF_System SET CostTaxExcluded = 0</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> ALTER TABLE CNF_System
  ALTER COLUMN CostTaxExcluded Smallint NOT NULL</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>2073</SQLVERSION>
			<RMTRACKLINK>61574</RMTRACKLINK>
			<REASON>Added column AgeToSkip to the table SIAE_TesseraTifosoRule
[0] Add column AgeToSkip</REASON>
			<TABLENAMES>SIAE_TesseraTifosoRule=TdTRuleId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>  IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'AgeToSkip' AND
                Object_ID  = Object_ID(N'SIAE_TesseraTifosoRule'))
BEGIN
  ALTER TABLE SIAE_TesseraTifosoRule ADD AgeToSkip Integer NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AndreaDavanzo</ADDEDBY>
			<SQLVERSION>2072</SQLVERSION>
			<RMTRACKLINK>61570</RMTRACKLINK>
			<REASON>Added column SiaeGeoEntityId to the table SIAE_Location
[0] Add column SiaeGeoEntityId</REASON>
			<TABLENAMES>SIAE_Location=SiaeLocationId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'SiaeGeoEntityId' AND
                Object_ID  = Object_ID(N'SIAE_Location'))
BEGIN
  ALTER TABLE SIAE_Location ADD SiaeGeoEntityId Integer NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AndreaDavanzo</ADDEDBY>
			<SQLVERSION>2071</SQLVERSION>
			<RMTRACKLINK>61570</RMTRACKLINK>
			<REASON>Add the ExternalId column to the CNF_Performance
[0] Add column ExternalId</REASON>
			<TABLENAMES>CNF_Performance=PerformanceId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'ExternalID' AND
                Object_ID  = Object_ID(N'CNF_Performance'))
BEGIN
  ALTER TABLE CNF_Performance ADD ExternalId NVarChar(20) NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>marcoviscusi</ADDEDBY>
			<SQLVERSION>2070</SQLVERSION>
			<RMTRACKLINK>61768</RMTRACKLINK>
			<REASON>Added PerformanceId to DATA_Media</REASON>
			<TABLENAMES>DATA_Media=MediaId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'PerformanceID' AND
                Object_ID  = Object_ID(N'DATA_Media'))
BEGIN
  ALTER TABLE DATA_Media ADD PerformanceID int NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int  
EXEC Otn_Add_ForeingKey
		@ForeingKeyTable = N'DATA_Media',
		@ForeingKeyReferenceTable  = N'CNF_Performance',
		@ForeingKeyColumn = N'PerformanceId',
		@ForeingKeyReferenceColumn = N'PerformanceId',
		@result = @retval OUTPUT
SELECT @retval;
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>dapicella</ADDEDBY>
			<SQLVERSION>2069</SQLVERSION>
			<RMTRACKLINK>56877</RMTRACKLINK>
			<REASON>CNF_SeatCategory rebuild stored procedure
[0] </REASON>
			<TABLENAMES>CNF_SeatCategory=SeatCategoryId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>SELECT 1</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>jlaguardia</ADDEDBY>
			<SQLVERSION>2068</SQLVERSION>
			<RMTRACKLINK>64145</RMTRACKLINK>
			<REASON>CNF_DataMask
[0]modify FieldName datatype - change from nvarchar(30) to nvarchar(1000)</REASON>
			<TABLENAMES>CNF_DataMask=DataMaskId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>if (
	SELECT CHARACTER_MAXIMUM_LENGTH
	FROM INFORMATION_SCHEMA.COLUMNS
	WHERE 
     TABLE_NAME = 'CNF_DataMask' AND 
     COLUMN_NAME = 'FieldName' 
) = 30
begin
	alter table CNF_DataMask alter column FieldName nvarchar (1000)	
end</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>dapicella</ADDEDBY>
			<SQLVERSION>2067</SQLVERSION>
			<RMTRACKLINK>56877</RMTRACKLINK>
			<REASON>CNF_SeatCategory
[0] add field SeatCategoryType
[1] fill value for SeatCategoryType = Lk_SeatCategoryType_Configuration
[2] fill value for SeatCategoryType = Lk_SeatCategoryType_Performance
[3] set field SeatCategoryType NOT NULL
[4] add field Enable
[5] fill value for Enable = Lk_EnabledType_False
[6] fill value for Enable = Lk_EnabledType_True
[7] set field Enable NOT NULL
[8] remove foreing key on  field AccessConfigurationId
[9] drop column AccessConfigurationId, Quantity and Category
[10] Insert new groupped seat category</REASON>
			<TABLENAMES>CNF_SeatCategory=SeatCategoryId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'SeatCategoryType' AND
                Object_ID  = Object_ID(N'CNF_SeatCategory'))
BEGIN
	ALTER TABLE CNF_SeatCategory ADD SeatCategoryType smallint NULL DEFAULT (1)
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>UPDATE CNF_SeatCategory SET SeatCategoryType = 1 where Temp_SeatCategoryId is null</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>UPDATE CNF_SeatCategory SET SeatCategoryType = 2 where not Temp_SeatCategoryId is null</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Code' AND
                Object_ID  = Object_ID(N'CNF_SeatCategory'))
BEGIN
 ALTER TABLE CNF_SeatCategory ALTER COLUMN SeatCategoryType smallint NOT NULL
 ALTER TABLE CNF_SeatCategory ALTER COLUMN Code varchar(12) NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Enabled' AND
                Object_ID  = Object_ID(N'CNF_SeatCategory'))
BEGIN
	ALTER TABLE CNF_SeatCategory ADD Enabled SmallInt NULL DEFAULT (0)
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>UPDATE CNF_SeatCategory SET Enabled = 0 where Temp_SeatCategoryId is null</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>UPDATE CNF_SeatCategory SET Enabled = 1 where not Temp_SeatCategoryId is null</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'CNF_SeatCategory')
BEGIN
	ALTER TABLE CNF_SeatCategory ALTER COLUMN Enabled SmallInt NOT NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @retval int  
EXEC Otn_Remove_ForeingKey
	@ForeingKeyTable = N'CNF_SeatCategory',
	@ForeingKeyReferenceTable = N'ADM_AccessConfiguration',
	@ForeingKeyColumn = N'AccessConfigurationId',
	@result = @retval OUTPUT
SELECT @retval;</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'AccessConfigurationId' AND
                Object_ID  = Object_ID(N'CNF_SeatCategory'))
BEGIN
	ALTER TABLE CNF_SeatCategory DROP COLUMN AccessConfigurationId;
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Category' AND
                Object_ID  = Object_ID(N'CNF_SeatCategory'))
BEGIN
        ALTER TABLE CNF_SeatCategory DROP COLUMN Category;
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Quantity' AND
                Object_ID  = Object_ID(N'CNF_SeatCategory'))
BEGIN
	ALTER TABLE CNF_SeatCategory DROP COLUMN Quantity;
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>INSERT INTO CNF_SeatCategory
(Code, Name, AttributeId, Color, Weight, ExternalReference, Enabled, SeatCategoryType)
(select 
 Case 
  when not(AttributeId is null) then LEFT(Code + '_A',10)
  else LEFT(Code,10)
 end as Code,  
 Case 
  when not(AttributeId is null) then LEFT(Code + '_A', 30)
  else LEFT(Code, 30)
 end as Name,
 AttributeId, 
 Null as Color, 
 Null as Weight, 
 Null as ExternalReference,
 1 as Enabled,
 1 as SeatCategoryType
from 
 CNF_SeatCategory
where
 Temp_SeatCategoryId is null and Code is not null
group by 
 Code, AttributeId 
)</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>dapicella</ADDEDBY>
			<SQLVERSION>2066</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>CNF_SeatCategory
[0] create standard procedure for remove foreing key Otn_Remove_ForeingKey
[1] create standard procedure Otn_Remove_ForeingKeys_From_Reference_Table
[2] create standard procedure Otn_Remove_ForeingKeys_From_Table
[3] create standard procedure Otn_Add_ForeingKey</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE PROCEDURE Otn_Remove_ForeingKey
	@ForeingKeyTable nvarchar(100),
	@ForeingKeyReferenceTable nvarchar(100),
	@ForeingKeyColumn nvarchar(100),
	@Result int OUTPUT
AS
BEGIN
	DECLARE @dropstmt nvarchar(1000)
	SET @Result = 0

	-- Cursor to generate ALTER TABLE DROP CONSTRAINT statements  
	DECLARE cur CURSOR FOR
		SELECT 'ALTER TABLE ' +  OBJECT_NAME(f.parent_object_id) + ' DROP CONSTRAINT [' + f.name + ']'			
		FROM 
			sys.foreign_keys AS f
			INNER JOIN sys.foreign_key_columns AS fc ON f.object_id = fc.constraint_object_id    
		WHERE 
			f.parent_object_id     = object_id(@ForeingKeyTable)								-- TABELLA DA CUI SI VUOLE RIMUOVERE LA FK
			AND f.referenced_object_id = object_id(@ForeingKeyReferenceTable)					-- TABELLA DEL RIFERIMENTO DELLA FK 
			AND COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = @ForeingKeyColumn;	-- CAMPO FK DA RIMUOVERE
	OPEN cur;
	FETCH cur INTO @dropstmt;

	-- Drop each found foreign key constraint 
	WHILE @@FETCH_STATUS = 0
	BEGIN
		EXEC (@dropstmt);
		SET @Result = @Result + 1
		FETCH cur INTO @dropstmt;
	END

	CLOSE cur;
	DEALLOCATE cur;
END;</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE PROCEDURE Otn_Remove_ForeingKeys_From_Reference_Table
	@ForeingKeyReferenceTable nvarchar(100),
	@Result int OUTPUT
AS
BEGIN
	DECLARE @dropstmt nvarchar(1000)
	SET @Result = 0

	-- Cursor to generate ALTER TABLE DROP CONSTRAINT statements  
	DECLARE cur CURSOR FOR
		SELECT 'ALTER TABLE ' + OBJECT_NAME(parent_object_id) + ' DROP CONSTRAINT [' + name + ']'	
		FROM sys.foreign_keys 
		WHERE OBJECT_NAME(referenced_object_id) = @ForeingKeyReferenceTable;
	OPEN cur;
	FETCH cur INTO @dropstmt;

	-- Drop each found foreign key constraint 
	WHILE @@FETCH_STATUS = 0
	BEGIN
		EXEC (@dropstmt);
		SET @Result = @Result + 1
		FETCH cur INTO @dropstmt;
	END

	CLOSE cur;
	DEALLOCATE cur;
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE PROCEDURE Otn_Remove_ForeingKeys_From_Table
	@ForeingKeyTable nvarchar(100),
	@Result int OUTPUT
AS
BEGIN
	DECLARE @dropstmt nvarchar(1000)
	SET @Result = 0

	-- Cursor to generate ALTER TABLE DROP CONSTRAINT statements  
	DECLARE cur CURSOR FOR
		SELECT 'ALTER TABLE ' + OBJECT_NAME(parent_object_id) + ' DROP CONSTRAINT [' + name + ']'	
		FROM sys.foreign_keys 
		WHERE OBJECT_NAME(parent_object_id) = @ForeingKeyTable;
	OPEN cur;
	FETCH cur INTO @dropstmt;

	-- Drop each found foreign key constraint 
	WHILE @@FETCH_STATUS = 0
	BEGIN
		EXEC (@dropstmt);
		SET @Result = @Result + 1
		FETCH cur INTO @dropstmt;
	END

	CLOSE cur;
	DEALLOCATE cur;
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE PROCEDURE Otn_Add_ForeingKey
	@ForeingKeyTable nvarchar(100),
	@ForeingKeyReferenceTable nvarchar(100),
	@ForeingKeyColumn nvarchar(100),
	@ForeingKeyReferenceColumn nvarchar(100),
	@Result int OUTPUT
AS
BEGIN
	DECLARE @addstmt nvarchar(1000)
	SET @Result = 0

	-- Check if the Foreing Key exist
	IF NOT EXISTS (
		SELECT 
			OBJECT_NAME(f.object_id) as Foreign_Key_Name,
			OBJECT_NAME(f.parent_object_id) as Foreign_Key_Table_Name,
			OBJECT_NAME(f.referenced_object_id) as Foreign_Key_Reference_Table_Name,
			COL_NAME(fc.parent_object_id, fc.parent_column_id) as Foreign_Key_Table_Column_Name,
			COL_NAME(fc.referenced_object_id, fc.referenced_column_id) as Foreign_Key_Reference_Table_Column_Name			
		FROM 
			sys.foreign_keys AS f
			INNER JOIN sys.foreign_key_columns AS fc ON f.object_id = fc.constraint_object_id    
		WHERE 
			f.parent_object_id			= object_id(@ForeingKeyTable)								-- TABELLA DA CUI SI VUOLE AGGIUNGERE LA FK
			AND f.referenced_object_id	= object_id(@ForeingKeyReferenceTable)						-- TABELLA DEL RIFERIMENTO DELLA FK 
			AND COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = @ForeingKeyColumn		-- CAMPO FK DA AGGIUNGERE
			AND COL_NAME(fc.parent_object_id, fc.parent_column_id) = @ForeingKeyReferenceColumn		-- CAMPO FK DA AGGIUNGERE
		)
	BEGIN
	  SET @addstmt = 'ALTER TABLE ' + @ForeingKeyTable + ' WITH CHECK ADD CONSTRAINT ' + 'FK_' + @ForeingKeyTable + '_' + @ForeingKeyReferenceTable + '_' + @ForeingKeyColumn  + 
					' FOREIGN KEY([' + @ForeingKeyColumn + ']) REFERENCES ' + @ForeingKeyReferenceTable + ' ([' + @ForeingKeyReferenceColumn + '])';
	  EXEC (@addstmt);
	  SET @Result = @Result + 1
	END
	ELSE
	BEGIN
		SET @Result = 0
	END
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fulviodipalma</ADDEDBY>
			<SQLVERSION>2065</SQLVERSION>
			<RMTRACKLINK>61589</RMTRACKLINK>
			<REASON>CNF_MatrixCell
[0] add new field ChangeAccountNotAllowed(SmallInt)
[1] set default value
[2] set field as not Null</REASON>
			<TABLENAMES>CNF_MatrixCell=MatrixCellId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_MatrixCell
  add  ChangeAccountNotAllowed Smallint  NULL</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>marcoviscusi</ADDEDBY>
			<SQLVERSION>2064</SQLVERSION>
			<RMTRACKLINK>61718</RMTRACKLINK>
			<REASON>[DATA_TicketStatus]
0 = Modified Field  UserId with NULL
1 = Modified Field  WorkstationId with NULL
2 = Removed the default values for UserId and WorkstationId
3 = Update UserId with Null where = 0
4 = Update WorkstationId with Null where = 0
5 = Added ForeignKey for UserId with CNF_User
6 = Added ForeignKey for WorkstationId with CNF_Workstation</REASON>
			<TABLENAMES>DATA_TicketStatus=TicketStatusID</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE DATA_TicketStatus ALTER COLUMN UserId INT NULL</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE DATA_TicketStatus ALTER COLUMN WorkstationId INT NULL</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>declare @sql nvarchar(max); 
set @sql = ''; 
SELECT @sql+='ALTER TABLE DATA_TicketStatus DROP CONSTRAINT ' + ((SELECT OBJECT_NAME(constid) FROM sysconstraints WHERE OBJECT_NAME(id) = 'DATA_TicketStatus' AND colid IN (SELECT ORDINAL_POSITION FROM INFORMATION_SCHEMA.COLUMNS Where Table_Name = 'DATA_TicketStatus' and COLUMN_NAME = 'UserId'))) + ';'; 
EXEC sp_executesql @sql;
set @sql = ''; 
SELECT @sql+='ALTER TABLE DATA_TicketStatus DROP CONSTRAINT ' + ((SELECT OBJECT_NAME(constid) FROM sysconstraints WHERE OBJECT_NAME(id) = 'DATA_TicketStatus' AND colid IN (SELECT ORDINAL_POSITION FROM INFORMATION_SCHEMA.COLUMNS Where Table_Name = 'DATA_TicketStatus' and COLUMN_NAME = 'WorkstationId'))) + ';'; 
EXEC sp_executesql @sql;</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>UPDATE DATA_TicketStatus SET UserId = NULL WHERE UserId = 0</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>UPDATE DATA_TicketStatus SET WorkstationId = NULL WHERE WorkstationId = 0</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE DATA_TicketStatus  WITH CHECK ADD FOREIGN KEY(UserId)
REFERENCES CNF_USER (UserId)</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE DATA_TicketStatus  WITH CHECK ADD FOREIGN KEY(WorkstationId)
REFERENCES CNF_Workstation (WorkstationId)</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fulviodipalma</ADDEDBY>
			<SQLVERSION>2063</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>+Added new fields to DATA_Ticket
  ProductType(SmallInt)</REASON>
			<TABLENAMES>DATA_Ticket=TicketId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
               WHERE Name = 'ProductType' AND
               Object_ID  = Object_ID('DATA_Ticket'))
BEGIN

alter table DATA_Ticket
    add [ProductType] SmallInt NOT NULL Default 1;

END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>2062</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>CNF_Mask
[0] add new field SystemMask
[1] set default value
[2] set field as not Null

CNF_System
[3] add new filed Soccer Mode
[4] set default Value
[5] set field as not Null</REASON>
			<TABLENAMES>CNF_Mask=MaskId
CNF_System=SystemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Mask
  add  SystemMask Smallint  NULL</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update Cnf_Mask set SystemMask = 0</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Mask
  alter column  SystemMask Smallint not NULL</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_System
  add  SoccerMode Smallint NULL</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_System set SoccerMode = 0</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> alter table CNF_System
  alter column  SoccerMode Smallint not NULL</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>marcoviscusi</ADDEDBY>
			<SQLVERSION>2061</SQLVERSION>
			<RMTRACKLINK>61718</RMTRACKLINK>
			<REASON>[DATA_TicketStatus]
0 = Add Field  UserId
1 = Add Field  EventDateTime
2 = Add Field  WorkstationId</REASON>
			<TABLENAMES>DATA_TicketStatus=TicketStatusID</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'UserId' AND
                Object_ID  = Object_ID(N'DATA_TicketStatus'))
BEGIN
  ALTER TABLE DATA_TicketStatus ADD UserId Integer NOT NULL Default 0
END

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'EventDateTime' AND
                Object_ID  = Object_ID(N'DATA_TicketStatus'))
BEGIN
  ALTER TABLE DATA_TicketStatus ADD EventDateTime DateTime NULL
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'WorkstationId' AND
                Object_ID  = Object_ID(N'DATA_TicketStatus'))
BEGIN
  ALTER TABLE DATA_TicketStatus ADD WorkstationId Integer NOT NULL Default 0
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>2060</SQLVERSION>
			<RMTRACKLINK>61288</RMTRACKLINK>
			<REASON>Add PerdDatetime on SIAE_Log2Performance

0 - Add Field
1 - Realiign Script
			</REASON>
			<TABLENAMES>SIAE_Log2Performance=Log2PerformanceId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>

IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'PerfDateTime' AND
                Object_ID  = Object_ID(N'SIAE_Log2Performance'))
BEGIN
  ALTER TABLE SIAE_Log2Performance ADD PerfDateTime datetime NULL
END

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> 

update SIAE_Log2Performance
set PerfDateTime = (select PerfDateTime from CNF_Performance P with(nolock) where PerformanceId = SIAE_Log2Performance.PerformanceId)
where SIAE_Log2Performance.PerformanceId &gt; 0
and SIAE_Log2Performance.PerfDateTime is null
and SiaeLogId in (
  select SiaeLogId from SIAE_SiaeLog with(nolock) 
  where TipoTitolo in 
    (select A.AttributeId 
     from CNF_Attribute A with(nolock) 
	   INNER JOIN CNF_AttributeTemplate AT with(nolock) ON AT.AttributeTemplateId = A.AttributeTemplateId
     where AT.AttributeTemplateCode = 'SIAE_TA' and A.Code in ('TFN', 'TFF', 'BAB') 
    ))

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fulviodipalma</ADDEDBY>
			<SQLVERSION>2059</SQLVERSION>
			<RMTRACKLINK>63841</RMTRACKLINK>
			<REASON>+Added new fields to CNF_Event
  DefaultDuration(Integer)</REASON>
			<TABLENAMES>CNF_Event=EventId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
               WHERE Name = 'DefaultDuration' AND
               Object_ID  = Object_ID('CNF_Event'))
BEGIN

alter table CNF_Event
    add [DefaultDuration] integer NULL;

END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Esposito</ADDEDBY>
			<SQLVERSION>2058</SQLVERSION>
			<RMTRACKLINK>65347</RMTRACKLINK>
			<REASON>Add of DmgCategoryId on CNF_FlexContract</REASON>
			<TABLENAMES>CNF_FlexContract=FlexContractId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'DmgCategoryId' AND
                Object_ID  = Object_ID(N'CNF_FlexContract'))
BEGIN
  ALTER TABLE CNF_FlexContract ADD DmgCategoryId integer NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_FlexContract'
	          AND CONSTRAINT_NAME = N'fk_CNF_FlexContract_CNF_DmgCategory')          
BEGIN
  ALTER TABLE [CNF_FlexContract] WITH CHECK 
  ADD  CONSTRAINT [fk_CNF_FlexContract_CNF_DmgCategory] FOREIGN KEY([DmgCategoryId])
  REFERENCES [CNF_DmgCategory] ([DmgCategoryId])
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AndreaDavanzo</ADDEDBY>
			<SQLVERSION>2057</SQLVERSION>
			<RMTRACKLINK>65172</RMTRACKLINK>
			<REASON>Added index to the DATA_DmgData
[0] Added index IDX_DmgData_FKey</REASON>
			<TABLENAMES>DATA_DmgData=DmgDataId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.indexes
                WHERE Name = 'IDX_DmgData_FKey' and 
                object_id = OBJECT_ID('DATA_DmgData'))
BEGIN
  CREATE NONCLUSTERED INDEX IDX_DmgData_FKey ON DATA_DmgData (FKey ASC)
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>2056</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>Realign Store Procedure Params</REASON>
			<TABLENAMES>SIAE_TesseraTifosoRule=TdTRuleId
SIAE_TesseraTifosoRule2Entity=TdTRule2EntityId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>
select 1 from SIAE_TesseraTifosoRule with(nolock) </SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>
select 1 from SIAE_TesseraTifosoRule2Entity with(nolock) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AndreaDavanzo</ADDEDBY>
			<SQLVERSION>2055</SQLVERSION>
			<RMTRACKLINK>65136</RMTRACKLINK>
			<REASON>Added foreign key on CNF_Workstation
[0] Adding column DmgCategoryId
[1] Adding foreign key</REASON>
			<TABLENAMES>CNF_Workstation=WorkstationId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'DmgCategoryId' AND
                Object_ID  = Object_ID(N'CNF_Workstation'))
BEGIN
  ALTER TABLE CNF_Workstation ADD DmgCategoryId integer NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_Workstation'
	          AND CONSTRAINT_NAME = N'fk_CNF_Workstation_CNF_DmgCategory')          
BEGIN
  ALTER TABLE [CNF_Workstation] WITH CHECK 
  ADD  CONSTRAINT [fk_CNF_Workstation_CNF_DmgCategory] FOREIGN KEY([DmgCategoryId])
  REFERENCES [CNF_DmgCategory] ([DmgCategoryId])
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AndreaDavanzo</ADDEDBY>
			<SQLVERSION>2054</SQLVERSION>
			<RMTRACKLINK>65136</RMTRACKLINK>
			<REASON>Added foreign key on CNF_OperatingArea
[0] Adding column DmgCategoryId
[1] Adding foreign key</REASON>
			<TABLENAMES>CNF_OperatingArea=OperatingAreaId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'DmgCategoryId' AND
                Object_ID  = Object_ID(N'CNF_OperatingArea'))
BEGIN
  ALTER TABLE CNF_OperatingArea ADD DmgCategoryId integer NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_OperatingArea'
	          AND CONSTRAINT_NAME = N'fk_CNF_OpArea_CNF_DmgCategory')          
BEGIN
  ALTER TABLE [CNF_OperatingArea] WITH CHECK 
  ADD  CONSTRAINT [fk_CNF_OpArea_CNF_DmgCategory] FOREIGN KEY([DmgCategoryId])
  REFERENCES [CNF_DmgCategory] ([DmgCategoryId])
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FCARAMELLA</ADDEDBY>
			<SQLVERSION>2053</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>Add CNF_MaskTableItem_Translation.SortOrder
Add CNF_DataMaskTranslation change fieldname col size (200-&gt;1000)</REASON>
			<TABLENAMES>CNF_MaskTableItem_Translation=MaskTableTranslationId
CNF_DataMaskTranslation=DataMaskTranslationId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'SortOrder' AND
                Object_ID  = Object_ID(N'CNF_MaskTableItem_Translation'))
BEGIN
  ALTER TABLE CNF_MaskTableItem_Translation ADD SortOrder integer NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>  ALTER TABLE CNF_DataMaskTranslation 
    ALTER COLUMN [FieldName] [nvarchar](1000) NULL;</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AndreaDavanzo</ADDEDBY>
			<SQLVERSION>2052</SQLVERSION>
			<RMTRACKLINK>61569</RMTRACKLINK>
			<REASON>Added foreign keys
[0] Add column SaleId on CNF_SaleLimit
[1] Add foreign key on CNF_SaleLimit
[2] Add column SaleRestrictionId on CNF_Performance
[3] Add foreign key in CNF_Performance</REASON>
			<TABLENAMES>CNF_SaleLimit=SaleLimitId
CNF_Performance=PerformanceId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'SaleId' AND
                Object_ID  = Object_ID(N'CNF_SaleLimit'))
BEGIN
  ALTER TABLE CNF_SaleLimit ADD SaleId integer NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_SaleLimit'
	          AND CONSTRAINT_NAME = N'fk_DATA_Sale_CNF_SaleLimit')          
BEGIN
  ALTER TABLE [CNF_SaleLimit] WITH CHECK 
  ADD  CONSTRAINT [fk_DATA_Sale_CNF_SaleLimit] FOREIGN KEY([SaleId])
  REFERENCES [DATA_Sale] ([SaleId])
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'SaleRestrictionId' AND
                Object_ID  = Object_ID(N'CNF_Performance'))
BEGIN
  ALTER TABLE CNF_Performance ADD SaleRestrictionId integer NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_Performance'
	          AND CONSTRAINT_NAME = N'fk_CNF_SaleLimitRestriction_CNF_Performance')          
BEGIN
  ALTER TABLE [CNF_Performance] WITH CHECK 
  ADD  CONSTRAINT [fk_CNF_SaleLimitRestriction_CNF_Performance] FOREIGN KEY([SaleRestrictionId])
  REFERENCES [CNF_SaleRestriction] ([SaleRestrictionId])
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FCARAMELLA</ADDEDBY>
			<SQLVERSION>2051</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>PaymentMethodAK Update</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_PaymentMethod set PaymentMethodAk = 
(select top 1 SystemCode from CNF_System where Enabled = 1) +
'.PAY'+
CAST(PaymentMethodId AS Varchar(MAX))
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>INSERT INTO DATA_Counter
           (CounterType
           ,IdentifierAK
           ,ReferenceTime
           ,Counter
           ,LastUpdateGuid)
     VALUES
           (23,
           (select top 1 SystemCode from CNF_System where Enabled = 1) +'.PAY',
           'NEVER',
           (select ISNULL(MAX(PAymentMethodid),0) from CNF_PaymentMethod),
           NULL)</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>pdalben</ADDEDBY>
			<SQLVERSION>2050</SQLVERSION>
			<RMTRACKLINK>64288</RMTRACKLINK>
			<REASON>Changed DriverName from DrvMercuryIDTech to DrvVantivIDTech</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT> update CNF_Driver set 
   DriverAk = 'TDrvVantivIDTech', 
   DllName = 'DrvVantivIDTech.dll',
   Description = 'External Credit Card - Vantiv IDTech' 
 where FamilyType = 201</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_DEVICE set 
  Description = 'External Credit Card - Vantiv IDTech' 
where DriverId = ((select DriverId from CNF_Driver where FamilyType = 201))</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>pdalben</ADDEDBY>
			<SQLVERSION>2049</SQLVERSION>
			<RMTRACKLINK>64288</RMTRACKLINK>
			<REASON>Changed DriverName from DrvVerifoneVx805 to DrvVantiv</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT> update CNF_Driver set 
   DriverAk = 'TDrvVantiv', 
   DllName = 'DrvVantiv.dll',
   Description = 'Credit Card - Vantiv' 
 where FamilyType = 207</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_DEVICE set 
  Description = 'Credit Card - Vantiv' 
where DriverId = ((select DriverId from CNF_Driver where FamilyType = 207))</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>pdalben</ADDEDBY>
			<SQLVERSION>2048</SQLVERSION>
			<RMTRACKLINK>64286</RMTRACKLINK>
			<REASON>Changed DriverName from DrvIngenicoIsc250 to DrvShift4UTG</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT> update CNF_Driver set 
   DriverAk = 'TDrvShift4UTG', 
   DllName = 'DrvShift4UTG.dll',
   Description = 'Credit Card - Shift4 UTG' 
 where FamilyType = 209</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_DEVICE set 
  Description = 'Credit Card - Shift4 UTG' 
where DriverId = ((select DriverId from CNF_Driver where FamilyType = 209))</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>pdalben</ADDEDBY>
			<SQLVERSION>2047</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>update scipt</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>-- Patch Partially Approved Status in DATA_PaymentCard
update DATA_PaymentCard set Status = 2 where PaymentId in (
select distinct
  PA.PaymentId
from 
                DATA_Payment PA 
inner join      DATA_PaymentCard PC on PA.PaymentId = PC.PaymentId
where 
    Abs(PA.PaymentAmount) = PC.PaymentAmount 
and PA.PaymentStatus = 1
and PC.Status = 16
)</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FCARAMELLA</ADDEDBY>
			<SQLVERSION>2046</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FCARAMELLA</ADDEDBY>
			<SQLVERSION>2045</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FCARAMELLA</ADDEDBY>
			<SQLVERSION>2044</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FCARAMELLA</ADDEDBY>
			<SQLVERSION>2043</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FCARAMELLA</ADDEDBY>
			<SQLVERSION>2042</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FCARAMELLA</ADDEDBY>
			<SQLVERSION>2041</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FCARAMELLA</ADDEDBY>
			<SQLVERSION>2040</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FCARAMELLA</ADDEDBY>
			<SQLVERSION>2039</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FCARAMELLA</ADDEDBY>
			<SQLVERSION>2038</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FCARAMELLA</ADDEDBY>
			<SQLVERSION>2037</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FCARAMELLA</ADDEDBY>
			<SQLVERSION>2036</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FCARAMELLA</ADDEDBY>
			<SQLVERSION>2035</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FCARAMELLA</ADDEDBY>
			<SQLVERSION>2034</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FCARAMELLA</ADDEDBY>
			<SQLVERSION>2033</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FCARAMELLA</ADDEDBY>
			<SQLVERSION>2032</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FCARAMELLA</ADDEDBY>
			<SQLVERSION>2031</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FCARAMELLA</ADDEDBY>
			<SQLVERSION>2030</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FCARAMELLA</ADDEDBY>
			<SQLVERSION>2029</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FCARAMELLA</ADDEDBY>
			<SQLVERSION>2028</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY></ADDEDBY>
			<SQLVERSION>2027</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fcaramella</ADDEDBY>
			<SQLVERSION>2026</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES>DATA_Ticket=TicketId
CNF_MatrixCell=MatrixCellId
CNF_Merchant=MerchantId
CNF_Projection=ProjectionId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Weight' AND
                Object_ID  = Object_ID(N'DATA_Ticket'))
BEGIN 
 Alter table DATA_Ticket
   add Weight integer null
END   </SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'ACReceiptTemplateId' AND
                Object_ID  = Object_ID(N'CNF_MatrixCell'))
BEGIN 
 Alter table CNF_MatrixCell
   add [ACReceiptTemplateId] integer null
END   </SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'MerchantType' AND
                Object_ID  = Object_ID(N'CNF_Merchant'))
BEGIN 
alter table CNF_Merchant
 add MerchantType Smallint NULL
END   </SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_Merchant
set  MerchantType = 1</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Merchant
 alter column MerchantType Smallint not NULL</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'TerminalId' AND
                Object_ID  = Object_ID(N'CNF_Merchant'))
BEGIN 
alter table CNF_Merchant
add TerminalId Integer NULL
END   </SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'ToDate' AND
                Object_ID  = Object_ID(N'CNF_Projection'))
BEGIN 
alter table CNF_Projection
  add ToDate DateTime null
END  </SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>marcocireni</ADDEDBY>
			<SQLVERSION>2025</SQLVERSION>
			<RMTRACKLINK>63227 </RMTRACKLINK>
			<REASON>To include 'Reprint' and 'Reissue' in Matrix cell
Alter Table  CNF_MatrixCellInfo</REASON>
			<TABLENAMES>CNF_MatrixCellInfo=MatrixCellInfoId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'DenyReprint' AND
                Object_ID  = Object_ID(N'CNF_MatrixCellInfo'))
BEGIN
  ALTER TABLE CNF_MatrixCellInfo ADD DenyReprint SmallInt  NOT NULL Default (0)
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'DenyReissue' AND
                Object_ID  = Object_ID(N'CNF_MatrixCellInfo'))
BEGIN
  ALTER TABLE CNF_MatrixCellInfo ADD DenyReissue SmallInt  NOT NULL Default (0)
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>2024</SQLVERSION>
			<RMTRACKLINK>61719</RMTRACKLINK>
			<REASON>SIAE - Table SIAE_TableReserved removed.</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'SIAE_TableReserved'))
BEGIN
drop table SIAE_TableReserved
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>JLaguardia</ADDEDBY>
			<SQLVERSION>2023</SQLVERSION>
			<RMTRACKLINK>56107</RMTRACKLINK>
			<REASON>+Added 2 new fields to CNF_System
  Hostname(Varchar100)
  DatabaseName(Varchar100)</REASON>
			<TABLENAMES>CNF_System=SystemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
               WHERE Name = 'ProdHostname' AND
               Object_ID  = Object_ID('CNF_System'))
BEGIN

alter table CNF_System
    add [ProdHostname] Nvarchar(100) NULL,
	[ProdDatabaseName] Nvarchar(100) NULL;

END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>pdalben</ADDEDBY>
			<SQLVERSION>2022</SQLVERSION>
			<RMTRACKLINK>64443</RMTRACKLINK>
			<REASON>Expanded field size
0 - DATA_PaymentCard.AcqRefData from 100 to 200</REASON>
			<TABLENAMES>DATA_PaymentCard=PaymentId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'AcqRefData' AND
                Object_ID  = Object_ID(N'DATA_PaymentCard'))
BEGIN
  ALTER TABLE DATA_PaymentCard 
    ALTER COLUMN [AcqRefData] [varchar](200) NULL;
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FrancoDamiani</ADDEDBY>
			<SQLVERSION>2021</SQLVERSION>
			<RMTRACKLINK>58166</RMTRACKLINK>
			<REASON>Alter DATA_Voucher Table
[0] Add column InUseWks
[1] Update InUseWks value for all previous records
[2] Add Default constraint to InUseWks column</REASON>
			<TABLENAMES>DATA_Voucher=VoucherId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'InUseWks' AND
                Object_ID  = Object_ID(N'DATA_Voucher'))
BEGIN
  ALTER TABLE DATA_Voucher ADD InUseWks smallint NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>UPDATE DATA_Voucher 
SET InUseWks = 0</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS ( select * from sys.objects WHERE type = 'D' and name = 'InUseWks_Default') 
BEGIN
  ALTER TABLE DATA_Voucher ADD CONSTRAINT InUseWks_Default DEFAULT 0 FOR InUseWks
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>marcoviscusi</ADDEDBY>
			<SQLVERSION>2020</SQLVERSION>
			<RMTRACKLINK>61356</RMTRACKLINK>
			<REASON>Alter Table DATA_TicketStatus</REASON>
			<TABLENAMES>DATA_TicketStatus=TicketStatusID</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Active' AND
                Object_ID  = Object_ID(N'DATA_TicketStatus'))
BEGIN
  ALTER TABLE DATA_TicketStatus ADD Active SmallInt  NOT NULL Default (0)
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>UPDATE DATA_TicketStatus SET Active = 1 where VoidType = 0</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>marcoviscusi</ADDEDBY>
			<SQLVERSION>2019</SQLVERSION>
			<RMTRACKLINK>61356</RMTRACKLINK>
			<REASON>Alter Table DATA_TicketStatus</REASON>
			<TABLENAMES>DATA_TicketStatus=TicketStatusID</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'DATA_TicketStatus'))

BEGIN
   ALTER TABLE DATA_TicketStatus NOCHECK CONSTRAINT ALL;
   ALTER TABLE DATA_TicketStatus ALTER COLUMN AccountID INTEGER NULL;
   ALTER TABLE DATA_TicketStatus ALTER COLUMN PerformanceID INTEGER NULL;
   ALTER TABLE DATA_TicketStatus ALTER COLUMN TransactionID INTEGER NULL;
   ALTER TABLE DATA_TicketStatus WITH CHECK CHECK CONSTRAINT ALL;
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>marcoviscusi</ADDEDBY>
			<SQLVERSION>2018</SQLVERSION>
			<RMTRACKLINK>61356</RMTRACKLINK>
			<REASON>Create Table DATA_TicketStatus</REASON>
			<TABLENAMES>DATA_TicketStatus=TicketStatusID</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'DATA_TicketStatus'))

BEGIN
Create table [DATA_TicketStatus]
(
	[TicketStatusID] Integer Identity(1,1) NOT NULL, 
	[TicketId] Integer NOT NULL,
	[AccountId] Integer NOT NULL,
	[PerformanceId] Integer NOT NULL,
	[TransactionId] Integer NOT NULL,
	[VoidType] Smallint Default 0 NOT NULL,
Primary Key ([TicketStatusID])
)  
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE [dbo].[DATA_TicketStatus]  WITH CHECK ADD FOREIGN KEY([TicketId])
REFERENCES [dbo].[DATA_Ticket] ([TicketId])</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE [dbo].[DATA_TicketStatus]  WITH CHECK ADD FOREIGN KEY([AccountId])
REFERENCES [dbo].[DATA_Account] ([AccountId])
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE [dbo].[DATA_TicketStatus]  WITH CHECK ADD FOREIGN KEY([PerformanceId])
REFERENCES [dbo].[CNF_Performance] ([PerformanceId])
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE [dbo].[DATA_TicketStatus]  WITH CHECK ADD FOREIGN KEY([TransactionId])
REFERENCES [dbo].[DATA_Transaction] ([TransactionId])
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>2017</SQLVERSION>
			<RMTRACKLINK>64185</RMTRACKLINK>
			<REASON>DATA_Ticket
[0] add field 

CNF_PromotionItemRule
[1]
[2]
			</REASON>
			<TABLENAMES>DATA_Ticket=TicketId
CNF_PromotionItemRule=PromotionItemRuleId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'MoneyCardAmount' AND
                Object_ID  = Object_ID(N'DATA_Ticket'))
BEGIN
  ALTER TABLE DATA_Ticket ADD MoneyCardAmount Float NULL  
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'CheckHistoricalFromDate' AND
                Object_ID  = Object_ID(N'CNF_PromotionItemRule'))
BEGIN
  ALTER TABLE CNF_PromotionItemRule 
    ADD CheckHistoricalFromDate Datetime NULL  
END

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'CheckHistoricalDateTo' AND
                Object_ID  = Object_ID(N'CNF_PromotionItemRule'))
BEGIN
  ALTER TABLE CNF_PromotionItemRule 
    ADD CheckHistoricalDateTo Datetime NULL  
END

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AndreaDavanzo</ADDEDBY>
			<SQLVERSION>2016</SQLVERSION>
			<RMTRACKLINK>62565</RMTRACKLINK>
			<REASON>Renaming columns
[0] Rename column from Gros to Gross</REASON>
			<TABLENAMES>DATA_SaleTax=SaleTaxId
DATA_TransactionTax=TransactionTaxId
DATA_SaleItemTax=SaleItemTaxId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
           WHERE Name = N'Gros' AND
           Object_ID  = Object_ID(N'DATA_SaleTax'))
BEGIN                                      
  EXEC sp_RENAME 'DATA_SaleTax.Gros' , 'Gross', 'COLUMN'
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
           WHERE Name = N'Gros' AND
           Object_ID  = Object_ID(N'DATA_TransactionTax'))
BEGIN                                      
  EXEC sp_RENAME 'DATA_TransactionTax.Gros' , 'Gross', 'COLUMN'
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
           WHERE Name = N'Gros' AND
           Object_ID  = Object_ID(N'DATA_SaleItemTax'))
BEGIN                          
  EXEC sp_RENAME 'DATA_SaleItemTax.Gros' , 'Gross', 'COLUMN'
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AndreaDavanzo</ADDEDBY>
			<SQLVERSION>2015</SQLVERSION>
			<RMTRACKLINK>61569</RMTRACKLINK>
			<REASON>CNF_SaleLimit
[0] Add column MaxAllowedPerTckOwner
[1] Add column MaxAllowedPerTckUser</REASON>
			<TABLENAMES>CNF_SaleLimit=SaleLimitId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'MaxAllowedPerTckOwner' AND
                Object_ID  = Object_ID(N'CNF_SaleLimit'))
BEGIN
  ALTER TABLE CNF_SaleLimit ADD MaxAllowedPerTckOwner Integer NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'MaxAllowedPerTckUser' AND
                Object_ID  = Object_ID(N'CNF_SaleLimit'))
BEGIN
  ALTER TABLE CNF_SaleLimit ADD MaxAllowedPerTckUser Integer NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>smcdonald</ADDEDBY>
			<SQLVERSION>2014</SQLVERSION>
			<RMTRACKLINK>63452</RMTRACKLINK>
			<REASON>Rename column on CNF_DocTemplate from Description to ReportDescription</REASON>
			<TABLENAMES>CNF_DocTemplate=DocTemplateId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
           WHERE Name = N'Description' AND
           Object_ID  = Object_ID(N'CNF_DocTemplate'))
BEGIN
  EXEC sp_rename 'CNF_DocTemplate.[Description]', 'ReportDescription', 'COLUMN';
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AndreaDavanzo</ADDEDBY>
			<SQLVERSION>2013</SQLVERSION>
			<RMTRACKLINK>61569</RMTRACKLINK>
			<REASON>CNF_SaleLimit
[0] Add column CountPerTckOwner 
[1] Add column CountPerTckUser
[2] Add column PerformanceId</REASON>
			<TABLENAMES>CNF_SaleLimit=SaleLimitId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
               WHERE Name = N'CountPerTckOwner' AND
               Object_ID  = Object_ID(N'CNF_SaleLimit'))
BEGIN
  ALTER TABLE CNF_SaleLimit ADD CountPerTckOwner integer NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
               WHERE Name = N'CountPerTckUser' AND
               Object_ID  = Object_ID(N'CNF_SaleLimit'))
BEGIN
  ALTER TABLE CNF_SaleLimit ADD CountPerTckUser integer NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
               WHERE Name = N'PerformanceId' AND
               Object_ID  = Object_ID(N'CNF_SaleLimit'))
BEGIN
  ALTER TABLE CNF_SaleLimit ADD PerformanceId integer NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	       WHERE TABLE_NAME = N'CNF_SaleLimit'
	       AND CONSTRAINT_NAME = N'fk_CNF_SaleLimit_CNF_Performance')          
BEGIN
  ALTER TABLE [CNF_SaleLimit] WITH CHECK 
  ADD  CONSTRAINT [fk_CNF_SaleLimit_CNF_Performance] FOREIGN KEY([PerformanceId])
  REFERENCES [CNF_Performance] ([PerformanceId])
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AndreaDavanzo</ADDEDBY>
			<SQLVERSION>2012</SQLVERSION>
			<RMTRACKLINK>61569</RMTRACKLINK>
			<REASON>CNF_Event
[0] Drop foreign key
[1] Drop SaleItemId column 
[2] Create new column SaleRestrictionId
[3] Create foreign key

CNF_SaleRestrictionValidity
[4] Drop all unused columns

CNF_SaleLimitRestriction 
[5] Drop all unused columns</REASON>
			<TABLENAMES>CNF_Event=EventId
CNF_SaleRestrictionValidity=SaleRestrictionValidityId
CNF_SaleLimitRestriction=SaleLimitRestrictionId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * 
           FROM sys.foreign_keys 
           WHERE object_id = OBJECT_ID(N'fk_CNF_Event_CNF_SaleLimit')
           AND parent_object_id = OBJECT_ID(N'CNF_Event'))
BEGIN
  ALTER TABLE CNF_Event DROP CONSTRAINT [fk_CNF_Event_CNF_SaleLimit]
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
           WHERE Name = N'SaleLimitId' AND
           Object_ID  = Object_ID(N'CNF_Event'))
BEGIN
  ALTER TABLE CNF_Event DROP COLUMN SaleLimitId
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
               WHERE Name = N'SaleRestrictionId' AND
               Object_ID  = Object_ID(N'CNF_Event'))
BEGIN
  ALTER TABLE CNF_Event ADD SaleRestrictionId integer NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	       WHERE TABLE_NAME = N'CNF_Event'
	       AND CONSTRAINT_NAME = N'fk_CNF_Event_CNF_SaleRestriction')          
BEGIN
  ALTER TABLE [CNF_Event] WITH CHECK 
  ADD  CONSTRAINT [fk_CNF_Event_CNF_SaleRestriction] FOREIGN KEY([SaleRestrictionId])
  REFERENCES [CNF_SaleRestriction] ([SaleRestrictionId])
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE CNF_SaleLimitRestriction DROP COLUMN Sunday
ALTER TABLE CNF_SaleLimitRestriction DROP COLUMN Monday
ALTER TABLE CNF_SaleLimitRestriction DROP COLUMN Tuesday
ALTER TABLE CNF_SaleLimitRestriction DROP COLUMN Wednesday
ALTER TABLE CNF_SaleLimitRestriction DROP COLUMN Thursday
ALTER TABLE CNF_SaleLimitRestriction DROP COLUMN Friday
ALTER TABLE CNF_SaleLimitRestriction DROP COLUMN Saturday
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE CNF_SaleRestrictionValidity DROP COLUMN Sunday
ALTER TABLE CNF_SaleRestrictionValidity DROP COLUMN Monday
ALTER TABLE CNF_SaleRestrictionValidity DROP COLUMN Tuesday
ALTER TABLE CNF_SaleRestrictionValidity DROP COLUMN Wednesday
ALTER TABLE CNF_SaleRestrictionValidity DROP COLUMN Thursday
ALTER TABLE CNF_SaleRestrictionValidity DROP COLUMN Friday
ALTER TABLE CNF_SaleRestrictionValidity DROP COLUMN Saturday</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AndreaDavanzo</ADDEDBY>
			<SQLVERSION>2011</SQLVERSION>
			<RMTRACKLINK>61569</RMTRACKLINK>
			<REASON>Alter CNF_Event table
[0] - Add column SaleLimitId
[1] - Create foreign key

Alter CNF_SaleRestriction table
[2] - Add column MaxTicketXOwnerXPerf 
[3] - Add column MaxTicketXTckAccountXPerf</REASON>
			<TABLENAMES>CNF_Event=EventId
CNF_SaleRestriction=SaleRestrictionId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'SaleLimitId' AND
                Object_ID  = Object_ID(N'CNF_Event'))
BEGIN
  ALTER TABLE CNF_Event ADD SaleLimitId integer NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_Event'
	          AND CONSTRAINT_NAME = N'fk_CNF_Event_CNF_SaleLimit')          
BEGIN
  ALTER TABLE [CNF_Event] WITH CHECK 
  ADD  CONSTRAINT [fk_CNF_Event_CNF_SaleLimit] FOREIGN KEY([SaleLimitId])
  REFERENCES [CNF_SaleLimit] ([SaleLimitId])
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'MaxTicketXOwnerXPerf' AND
                Object_ID  = Object_ID(N'CNF_SaleRestriction'))
BEGIN
  ALTER TABLE CNF_SaleRestriction ADD MaxTicketXOwnerXPerf integer NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'MaxTicketXTckAccountXPerf' AND
                Object_ID  = Object_ID(N'CNF_SaleRestriction'))
BEGIN
  ALTER TABLE CNF_SaleRestriction ADD MaxTicketXTckAccountXPerf integer NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>smcdonald</ADDEDBY>
			<SQLVERSION>2010</SQLVERSION>
			<RMTRACKLINK>63450</RMTRACKLINK>
			<REASON>Add description &amp; version to reports </REASON>
			<TABLENAMES>CNF_DocTemplate=DocTemplateId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Description' AND
                Object_ID  = Object_ID(N'CNF_DocTemplate'))
BEGIN
  ALTER TABLE CNF_DocTemplate ADD Description nvarchar(1000) NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Version' AND
                Object_ID  = Object_ID(N'CNF_DocTemplate'))
BEGIN
  ALTER TABLE CNF_DocTemplate ADD Version nvarchar(20) NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>2009</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>Update script only
[0] check if temporary table is there (security check)
[1] create temporary table
[2] update data
[3] drop temporary table</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>2008</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>CNF_MaskTableItem
[0] add FIeld Internal id 
[1] update value
[2] set Field as not null
[3] add index </REASON>
			<TABLENAMES>CNF_MaskTableItem=MaskTableItemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_MaskTableItem
  add InternalId Smallint NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_MaskTableItem 
  set InternalId = PriorityOrder</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_MaskTableItem
  alter column  InternalId Smallint not NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE NONCLUSTERED 
  INDEX [UQ_MaskTableItem_InternalId] ON [dbo].[CNF_MaskTableItem]
(
	[MaskTableId] ASC,
	[InternalId] ASC
)</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Esposito</ADDEDBY>
			<SQLVERSION>2007</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>Drop Table DATA_TicketPermission and its storeprocedure
Drop Foreign Key between DATA_Ticket2TicketPackage DATA_Ticket
Create table DATA_TicketPackage</REASON>
			<TABLENAMES>DATA_TicketPackage=TicketPackageId
CNF_TicketPackageGroup=TicketPackageGroupId
CNF_TicketPackageGroupPermission=TicketPackageGroupPermissionId
DATA_TicketPackage2Group=TicketPackage2GroupId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'DATA_TicketPermission'))
BEGIN
   DROP TABLE DATA_TicketPermission;

IF (EXISTS (SELECT * 
                  FROM SYS.PROCEDURES 
                  WHERE  NAME = 'sp_ui_DATA_TicketPermission_insert'))
begin                  
   DROP PROCEDURE sp_ui_DATA_TicketPermission_insert;
end

IF (EXISTS (SELECT * 
                  FROM SYS.PROCEDURES 
                  WHERE  NAME = 'sp_ui_DATA_TicketPermission_update'))
begin                  
   DROP PROCEDURE sp_ui_DATA_TicketPermission_update;
end

IF (EXISTS (SELECT * 
                  FROM SYS.PROCEDURES 
                  WHERE  NAME = 'sp_ui_DATA_TicketPermission_delete'))
begin                  
   DROP PROCEDURE sp_ui_DATA_TicketPermission_delete;
end





IF (EXISTS (SELECT * 
                  FROM SYS.PROCEDURES 
                  WHERE  NAME = 'otn_sp_ui_DATA_TicketPermission_insert'))
begin                  
   DROP PROCEDURE otn_sp_ui_DATA_TicketPermission_insert;
end


IF (EXISTS (SELECT * 
                  FROM SYS.PROCEDURES 
                  WHERE  NAME = 'otn_sp_ui_DATA_TicketPermission_update'))
begin                  
   DROP PROCEDURE otn_sp_ui_DATA_TicketPermission_update;
end

IF (EXISTS (SELECT * 
                  FROM SYS.PROCEDURES 
                  WHERE  NAME = 'otn_sp_ui_DATA_TicketPermission_delete'))
begin                  
   DROP PROCEDURE otn_sp_ui_DATA_TicketPermission_delete;
end


END


				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.foreign_keys
           WHERE Name = N'FK_DATA_Ticket2TicketPackage_TicketPackageId'
             AND parent_object_id = OBJECT_ID(N'DATA_Ticket2TicketPackage'))
BEGIN
  ALTER TABLE [DATA_Ticket2TicketPackage] DROP CONSTRAINT [FK_DATA_Ticket2TicketPackage_TicketPackageId]
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF (NOT EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'DATA_TicketPackage'))
BEGIN
Create table [DATA_TicketPackage]
(
	[TicketPackageId] Integer NOT NULL,
	[NumPackage] Numeric(20,0) NULL,
Primary Key ([TicketPackageId])
)

INSERT INTO DATA_TicketPackage (TicketPackageId, NumPackage)
SELECT TicketId
     , CASE WHEN ISNUMERIC(ExternalReferenceId) = 1 THEN CAST(ExternalReferenceId AS BIGINT) ELSE NULL END 
  FROM DATA_Ticket
 Where CreationType = 6 
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'DATA_TicketPackage'
	          AND CONSTRAINT_NAME = N'FK_DATA_TicketPackage_TicketPackageId'
)          
BEGIN
  ALTER TABLE [DATA_TicketPackage] WITH CHECK 
  ADD  CONSTRAINT [FK_DATA_TicketPackage_TicketPackageId] FOREIGN KEY([TicketPackageId])
  REFERENCES [DATA_Ticket] ([TicketId])    
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'DATA_Ticket2TicketPackage'
	          AND CONSTRAINT_NAME = N'FK_DATA_Ticket2TicketPackage_TicketPackageId'
)          
BEGIN
  ALTER TABLE [DATA_Ticket2TicketPackage] WITH CHECK 
  ADD  CONSTRAINT [FK_DATA_Ticket2TicketPackage_TicketPackageId] FOREIGN KEY([TicketPackageId])
  REFERENCES [DATA_TicketPackage] ([TicketPackageId])    
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF (NOT EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'CNF_TicketPackageGroup'))
BEGIN
Create table [CNF_TicketPackageGroup]
(
	[TicketPackageGroupId] Integer Identity(1,1) NOT NULL,
	[Code] Nvarchar(10) NOT NULL,
	[Name] Nvarchar(50) NULL,
	[Enabled] Smallint NOT NULL,
	[Note] Ntext NULL,
Primary Key ([TicketPackageGroupId])
)
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF (NOT EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'DATA_TicketPackage2Group'))
BEGIN
Create table [DATA_TicketPackage2Group]
(
	[TicketPackage2GroupId] Integer Identity(1,1) NOT NULL,
	[TicketPackageGroupId] Integer NOT NULL,
	[TicketPackageId] Integer NOT NULL,
Primary Key ([TicketPackage2GroupId])
)
END </SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'DATA_TicketPackage2Group'
	          AND CONSTRAINT_NAME = N'FK_DATA_TicketPackage2Group_TicketPackageGroupId'
)          
BEGIN
  ALTER TABLE [DATA_TicketPackage2Group] WITH CHECK 
  ADD  CONSTRAINT [FK_DATA_TicketPackage2Group_TicketGroupId] FOREIGN KEY([TicketPackageGroupId])
  REFERENCES [CNF_TicketPackageGroup] ([TicketPackageGroupId])    
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'DATA_TicketPackage2Group'
	          AND CONSTRAINT_NAME = N'FK_DATA_TicketPackage2Group_TicketPackageId'
)          
BEGIN
  ALTER TABLE [DATA_TicketPackage2Group] WITH CHECK 
  ADD  CONSTRAINT [FK_DATA_TicketPackage2Group_TicketPackageId] FOREIGN KEY([TicketPackageId])
  REFERENCES [DATA_TicketPackage] ([TicketPackageId])    
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF (NOT EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'CNF_TicketPackageGroupPermission'))
BEGIN
Create table [CNF_TicketPackageGroupPermission]
(
	[TicketPackageGroupPermissionId] Integer Identity(1,1) NOT NULL,
	[TicketPackageGroupId] Integer NOT NULL,
	[SiteId] Integer NULL,
	[WorkstationId] Integer NULL,
	[UserId] Integer NULL,
	[UserGroupId] Integer NULL,
	[AccountId] Integer NULL,
	[OperatingAreaId] Integer NULL,
	[Allow] Smallint NULL,
Primary Key ([TicketPackageGroupPermissionId])
)
END </SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_TicketPackageGroupPermission'
	          AND CONSTRAINT_NAME = N'FK_CNF_TicketPackageGroupPermission_TicketPackageGroupId'
)          
BEGIN
  ALTER TABLE [CNF_TicketPackageGroupPermission] WITH CHECK 
  ADD  CONSTRAINT [FK_CNF_TicketPackageGroupPermission_TicketPackageGroupId] FOREIGN KEY([TicketPackageGroupId])
  REFERENCES [CNF_TicketPackageGroup] ([TicketPackageGroupId])    
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_TicketPackageGroupPermission'
	          AND CONSTRAINT_NAME = N'FK_CNF_TicketPackageGroupPermission_SiteId'
)          
BEGIN
  ALTER TABLE [CNF_TicketPackageGroupPermission] WITH CHECK 
  ADD  CONSTRAINT [FK_CNF_TicketPackageGroupPermission_SiteId] FOREIGN KEY([SiteId])
  REFERENCES [CNF_Site] ([SiteId])    
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_TicketPackageGroupPermission'
	          AND CONSTRAINT_NAME = N'FK_CNF_TicketPackageGroupPermission_WorkstationId'
)          
BEGIN
  ALTER TABLE [CNF_TicketPackageGroupPermission] WITH CHECK 
  ADD  CONSTRAINT [FK_CNF_TicketPackageGroupPermission_WorkstationId] FOREIGN KEY([WorkstationId])
  REFERENCES [CNF_Workstation] ([WorkstationId])    
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_TicketPackageGroupPermission'
	          AND CONSTRAINT_NAME = N'FK_CNF_TicketPackageGroupPermission_UserId'
)          
BEGIN
  ALTER TABLE [CNF_TicketPackageGroupPermission] WITH CHECK 
  ADD  CONSTRAINT [FK_CNF_TicketPackageGroupPermission_UserId] FOREIGN KEY([UserId])
  REFERENCES [CNF_User] ([UserId])    
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_TicketPackageGroupPermission'
	          AND CONSTRAINT_NAME = N'FK_CNF_TicketPackageGroupPermission_UserGroupId'
)          
BEGIN
  ALTER TABLE [CNF_TicketPackageGroupPermission] WITH CHECK 
  ADD  CONSTRAINT [FK_CNF_TicketPackageGroupPermission_UserGroupId] FOREIGN KEY([UserGroupId])
  REFERENCES [CNF_UserGroup] ([UserGroupId])    
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_TicketPackageGroupPermission'
	          AND CONSTRAINT_NAME = N'FK_CNF_TicketPackageGroupPermission_AccountId'
)          
BEGIN
  ALTER TABLE [CNF_TicketPackageGroupPermission] WITH CHECK 
  ADD  CONSTRAINT [FK_CNF_TicketPackageGroupPermission_AccountId] FOREIGN KEY([AccountId])
  REFERENCES [DATA_Account] ([AccountId])    
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_TicketPackageGroupPermission'
	          AND CONSTRAINT_NAME = N'FK_CNF_TicketPackageGroupPermission_OperatingAreaId'
)          
BEGIN
  ALTER TABLE [CNF_TicketPackageGroupPermission] WITH CHECK 
  ADD  CONSTRAINT [FK_CNF_TicketPackageGroupPermission_OperatingAreaId] FOREIGN KEY([OperatingAreaId])
  REFERENCES [CNF_OperatingArea] ([OperatingAreaId])    
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>2006</SQLVERSION>
			<RMTRACKLINK>63368</RMTRACKLINK>
			<REASON>CNF_DataMask
[0] add column MasterObjectTypeCheckType</REASON>
			<TABLENAMES>CNF_DataMask=DataMaskId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_DataMask
  add MasterObjectTypeCheckType Smallint NULL</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>2005</SQLVERSION>
			<RMTRACKLINK>63367</RMTRACKLINK>
			<REASON>CNF_DataMask
[0] add column Min Choice Number</REASON>
			<TABLENAMES>CNF_DataMask=DataMaskId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_DataMask
  add MinChoiceNum Smallint NULL</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>2004</SQLVERSION>
			<RMTRACKLINK>63367</RMTRACKLINK>
			<REASON>CNF_DataMask
[0] add column Max Choice Number</REASON>
			<TABLENAMES>CNF_DataMask=DataMaskId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_DataMask
  add MaxChoiceNum Smallint NULL</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>pdalben</ADDEDBY>
			<SQLVERSION>2003</SQLVERSION>
			<RMTRACKLINK>63620</RMTRACKLINK>
			<REASON>Remved FK on field TickedId
[0] Drop FK TicketId
[1] Alter Column TicketId from NOT NULL To NULL
[2] Null the column TicketId
[3] Drop Index on TicketId</REASON>
			<TABLENAMES>DATA_Biometric=BiometricId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.foreign_keys 
  WHERE 
  Name = N'fkDATA_Biometric_DATA_Ticket' AND
  parent_object_id = OBJECT_ID(N'DATA_Biometric'))
BEGIN
  ALTER TABLE [DATA_Biometric] DROP CONSTRAINT [fkDATA_Biometric_DATA_Ticket]
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
  WHERE 
  Name = N'TicketId' AND
  object_id  = Object_ID(N'DATA_Biometric'))
BEGIN
  ALTER TABLE [DATA_Biometric] ALTER COLUMN [TicketId] [int] NULL
END   </SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
  WHERE 
  Name = N'TicketId' AND
  object_id  = Object_ID(N'DATA_Biometric'))
BEGIN
  UPDATE [DATA_Biometric] SET [TicketId] = NULL
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.indexes 
  WHERE 
  Name = N'IDX_BIOM_TICKETID' AND 
  object_id = OBJECT_ID(N'DATA_Biometric'))
BEGIN
  DROP INDEX [IDX_BIOM_TICKETID] ON [DATA_Biometric]
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>2002</SQLVERSION>
			<RMTRACKLINK>61574</RMTRACKLINK>
			<REASON>Table SIAE_TesseraTifosoRule recreated in order to some infos
[0] - Drop Table
[1] - Create Table
			</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT> 

IF (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'SIAE_TesseraTifosoRule'))
BEGIN
   DROP TABLE SIAE_TesseraTifosoRule;
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'SIAE_TesseraTifosoRule'))
BEGIN


Create table [SIAE_TesseraTifosoRule]
(
	[TdTRuleId] Integer Identity(1,1) NOT NULL,
	[TdTCardId] Integer NOT NULL,
	[TdTRuleCode] Nvarchar(10) NOT NULL,
	[TdTRuleName] Nvarchar(50) NOT NULL,
	[TdTRuleDesc] Nvarchar(100) NULL,
	[TicketAccountForTickets] Smallint NULL,
	[TicketAccountForSeasonPass] Smallint NULL,
	[ResAccountForTickets] Smallint NULL,
	[ResAccountForSeasonPass] Smallint NULL,
	[CustomRule] Ntext NULL,
Primary Key ([TdTRuleId])
) 
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>pdalben</ADDEDBY>
			<SQLVERSION>2001</SQLVERSION>
			<RMTRACKLINK>63620</RMTRACKLINK>
			<REASON>Regenerate storeprocedure for DATA_Biometric to update insert SP
[0] Migrate TicketId from DATA_Biometric to DATA_Biometric2Ticker</REASON>
			<TABLENAMES>DATA_Biometric=BiometricId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF (select COUNT(BiometricId) from DATA_Biometric where BiometricId not in (select BiometricId from DATA_Biometric2Ticket)) &lt;&gt;
   (select COUNT(BiometricId) from DATA_Biometric2Ticket where BiometricId not in (select BiometricId from DATA_Biometric))
BEGIN
  insert into DATA_Biometric2Ticket (BiometricId, TicketId)
  select B.BiometricId, B.TicketId 
  from DATA_Biometric AS B 
  where B.BiometricId not in (select BiometricId from DATA_Biometric2Ticket)
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>2000</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>CNF_UpSell
[0] add field enabled smaillint null
[1] add field UpsellAk nvarcharNull
[2] se Enabled = 1 to existing items
[3] set AK to existing values
[4] set enabled as not null
[5] set AK as not null
[6] Add AK to DATA_Counter</REASON>
			<TABLENAMES>CNF_UpSell=UpSellId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_UpSell
  add Enabled smallint null</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_UpSell
  add UpSellAK nvarchar(32) null</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_Upsell
  set Enabled = 1</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_UpSell set UpSellAK =(
select 
  (select top 1 SystemCode from Cnf_System) + '.UPS' + Cast(UPS.UpSellId as varchar)
from CNF_UpSell as UPS
WHERE CNF_UpSell.UpSellId=UPS.UpSellId
)</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_UpSell
  alter column Enabled smallint  not null</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_UpSell
  alter column UpSellAK nvarchar(32) not null</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>insert into DATA_Counter (CounterType, IdentifierAK, ReferenceTime, Counter) 
(
select 
  22,
  (select top 1 SystemCode from Cnf_System) + '.UPS',
  'NEVER',
  IsNull(MAX(CNF_UpSell.UpSellId), 0)

from 
  CNF_UpSell

)
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>pdalben</ADDEDBY>
			<SQLVERSION>1999</SQLVERSION>
			<RMTRACKLINK>63620</RMTRACKLINK>
			<REASON>DATA_Biometric2Ticket
[0] Create table
[1] Create index IdxDATA_Biometric2Ticket_TicketId
[2] Create index IdxDATA_Biometric2Ticket_BiometricId</REASON>
			<TABLENAMES>DATA_Biometric2Ticket=Biometric2TicketId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES 
  WHERE 
  TABLE_SCHEMA = 'dbo' AND  TABLE_NAME = 'DATA_Biometric2Ticket'))
BEGIN
Create table [DATA_Biometric2Ticket]
(
	[Biometric2TicketId] Integer Identity(1,1) NOT NULL,
	[TicketId] Integer NOT NULL,
	[BiometricId] Integer NOT NULL,
	[AccountId] Integer NULL,
Primary Key ([Biometric2TicketId])
) 
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.indexes 
  WHERE 
  Name = N'IdxDATA_Biometric2Ticket_TicketId' AND 
  object_id = OBJECT_ID(N'DATA_Biometric2Ticket'))
BEGIN
  Create Index [IdxDATA_Biometric2Ticket_TicketId] ON [DATA_Biometric2Ticket] ([TicketId]) 
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.indexes 
  WHERE 
  Name = N'IdxDATA_Biometric2Ticket_BiometricId' AND 
  object_id = OBJECT_ID(N'DATA_Biometric2Ticket'))
BEGIN
  Create Index [IdxDATA_Biometric2Ticket_BiometricId] ON [DATA_Biometric2Ticket] ([BiometricId]) 
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>marcoviscusi</ADDEDBY>
			<SQLVERSION>1998</SQLVERSION>
			<RMTRACKLINK>63322</RMTRACKLINK>
			<REASON>Alter view vwStock_Inventory</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER VIEW [dbo].[vwStock_Inventory]
AS
SELECT        SCP.MinStock, SCP.MatrixCellId, SCP.SKU AS Product, dbo.STOCK_CNF_Warehouse.WarehouseId, dbo.STOCK_CNF_Um.Description AS Um, 
                         dbo.STOCK_CNF_Warehouse.Description AS WareHouse, SUM(inventory.qtyleft) AS qtyleft, SUM(inventory.qtyout) AS qtyout, SUM(inventory.qtytomove) 
                         AS qtytomove, dbo.CNF_MatrixCell.Price, dbo.CNF_MatrixCell.Name
FROM            (SELECT        MatrixCellId, WarehouseId, SUM(QtyLeft) AS qtyleft, 0 AS qtyout, 0 AS qtytomove
                          FROM            dbo.STOCK_Movement WITH (nolock)
                          WHERE        (InOut = 1) AND (Completed = 1)
                          GROUP BY MatrixCellId, WarehouseId
                          UNION
                          SELECT        MatrixCellId, WarehouseId, 0 AS Expr1, SUM(Qty) AS qtyout, SUM(Qty - QtyMoved) AS qtytomove
                          FROM            dbo.STOCK_Movement AS STOCK_Movement_2 WITH (nolock)
                          WHERE        (InOut = - 1) AND (MovementDate = DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0))
                          GROUP BY MatrixCellId, WarehouseId
                          UNION
                          SELECT        MatrixCellId, WarehouseId, 0 AS Expr1, SUM(- Qty) AS qtyout, 0 AS qtytomove
                          FROM            dbo.STOCK_Movement AS STOCK_Movement_1 WITH (nolock)
                          WHERE        (InOut = 1) AND (MovementType IN (5, 6)) AND (MovementDate = DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0))
                          GROUP BY MatrixCellId, WarehouseId) AS inventory INNER JOIN
                         dbo.STOCK_CNF_Product AS SCP WITH (nolock) ON inventory.MatrixCellId = SCP.MatrixCellId INNER JOIN
                         dbo.STOCK_CNF_Warehouse WITH (nolock) ON inventory.WarehouseId = dbo.STOCK_CNF_Warehouse.WarehouseId INNER JOIN
                         dbo.STOCK_CNF_Um WITH (nolock) ON dbo.STOCK_CNF_Um.UmId = SCP.UmId INNER JOIN
                         dbo.CNF_MatrixCell ON SCP.MatrixCellId = dbo.CNF_MatrixCell.MatrixCellId
GROUP BY SCP.MinStock, SCP.MatrixCellId, SCP.SKU, dbo.STOCK_CNF_Warehouse.WarehouseId, dbo.STOCK_CNF_Um.Description, dbo.STOCK_CNF_Warehouse.Description, 
                         dbo.CNF_MatrixCell.Price, dbo.CNF_MatrixCell.Name</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AndreaDavanzo</ADDEDBY>
			<SQLVERSION>1997</SQLVERSION>
			<RMTRACKLINK>63701</RMTRACKLINK>
			<REASON>CNF_PswDictionary
[0] Create table
[1] Create index</REASON>
			<TABLENAMES>CNF_PswDictionary=DictionaryId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT (EXISTS (SELECT * 
                FROM INFORMATION_SCHEMA.TABLES 
                WHERE TABLE_SCHEMA = 'dbo' 
                AND  TABLE_NAME = 'CNF_PswDictionary'))
BEGIN

Create table [CNF_PswDictionary]
(
	[DictionaryId] Integer Identity(1,1) NOT NULL,
	[DictionaryText] Ntext NOT NULL,
Primary Key ([DictionaryId])
) 

END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT *  
               FROM sys.indexes  
               WHERE name='Idx_PwsDictionary' 
               AND object_id = OBJECT_ID('[dbo].[CNF_PswDictionary]'))
BEGIN
  Create UNIQUE Index [Idx_PwsDictionary] ON [CNF_PswDictionary] ([DictionaryId])
END  </SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1996</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>CNF_UpSell
[0] add column Weight

CNF_Upsell2MatrixCell
[1]  add column FromMatrixCellId
[2] add column ToMatrixCellId
[4] add FK ok ToMatrixCellId
[5] add FK ok FromMatrixCellId
[6] remove FK on Matrixcell Id</REASON>
			<TABLENAMES>CNF_UpSell=UpSellId
CNF_Upsell2MatrixCell=UpSell2MatrixCellId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_UpSell
  add Weight integer null</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Upsell2MatrixCell
  add FromMatrixCellId integer not null default 1</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> alter table CNF_Upsell2MatrixCell
  add ToMatrixCellId integer not null default 1</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Upsell2MatrixCell] 
add  foreign key([ToMatrixCellId]) references [CNF_MatrixCell] ([MatrixCellId]) </SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Upsell2MatrixCell] 
add  foreign key([FromMatrixCellId]) references [CNF_MatrixCell] ([MatrixCellId]) </SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>declare @foreign_key_name nvarchar(200)
declare  @dropstmt nvarchar(1000)
SELECT @foreign_key_name = f.name
  FROM sys.foreign_keys AS f
INNER JOIN sys.foreign_key_columns AS fc ON f.object_id = fc.constraint_object_id    
WHERE f.parent_object_id     = object_id(N'[dbo].[CNF_UpSell]')             -- TABELLA DA CUI SI VUOLE RIMUOVERE LA FK
  AND f.referenced_object_id = object_id(N'[dbo].[MatrixCellid]')              -- TABELLA DEL RIFERIMENTO DELLA FK 
  AND COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'MatrixCellId'; -- CAMPO FK DA RIMUOVERE

IF (LEN(@foreign_key_name) &gt; 0) 
begin
  SELECT @dropstmt = 'ALTER TABLE [dbo].[CNF_Upsell] DROP CONSTRAINT [' + @foreign_key_name + ']'; --  TABELLA DA CUI SI VUOLE RIMUOVERE LA FK
  EXECUTE sp_executesql @dropstmt
end;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Upsell2MatrixCell
  drop column MatrixCellId </SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>1995</SQLVERSION>
			<RMTRACKLINK>61574</RMTRACKLINK>
			<REASON>Replace Tables from  Memeship....  to SIAE_TesseraTifoso....


[0] - Drop Table DATA_MembershipCardRule2Entity
[1] - Drop Table CNF_MembershipCardRule
----------
[2] - Create Table [SIAE_TesseraTifosoRule]
[3] - Create Table [SIAE_TesseraTifosoRule2Entity]

			</REASON>
			<TABLENAMES>SIAE_TesseraTifosoRule=TdTRuleId
SIAE_TesseraTifosoRule2Entity=TdTRule2EntityId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>


IF (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'DATA_MembershipCardRule2Entity'))
BEGIN
   DROP TABLE DATA_MembershipCardRule2Entity;
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>        
IF (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'CNF_MembershipCardRule'))
BEGIN
   DROP TABLE CNF_MembershipCardRule;
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>
IF NOT (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'SIAE_TesseraTifosoRule'))
BEGIN

Create table [SIAE_TesseraTifosoRule]
(
	[TdTRuleId] Integer Identity(1,1) NOT NULL,
	[TdTCardId] Integer NOT NULL,
	[TicketAccountForTickets] Smallint NULL,
	[TicketAccountForSeasonPass] Smallint NULL,
	[ResAccountForTickets] Smallint NULL,
	[ResAccountForSeasonPass] Smallint NULL,
	[CustomRule] Ntext NULL,
Primary Key ([TdTRuleId])
) 

END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>  IF NOT (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'SIAE_TesseraTifosoRule2Entity'))
BEGIN

Create table [SIAE_TesseraTifosoRule2Entity]
(
	[TdTRule2EntityId] Integer Identity(1,1) NOT NULL,
	[OperatingAreaId] Integer NOT NULL,
	[TdTRuleId] Integer NOT NULL,
	[EntityTable] Smallint NOT NULL,
	[EntityId] Integer NOT NULL,
Primary Key ([TdTRule2EntityId])
) 

END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1994</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>--CNF_Upsell
[0] Create Table
[1] Add FK with DmgCategory
-- CNF_Upsell2MatrixCell
[2]Create Table
[3] Add FK on Cnf_Upsell
--CNF_UpSell_Validity
[4] create Table
[5] Add FK on Cnf_Upsell
--CNF_UpSell_Permission
[6] Create table
[7]   Add FK on Cnf_Upsell
[8]   Add FK on WorkstationId
[9]   Add FK on OperatingAreaId
[10] Add FK on SiteId
[11] Add FK on UserId
[12] Add FK on UserGroup</REASON>
			<TABLENAMES>CNF_UpSell=UpSellId
CNF_Upsell2MatrixCell=UpSell2MatrixCellId
CNF_UpSell_Validity=UpSellValidityId
CNF_UpSell_Permission=UpSellPermissionId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_UpSell]
(
	[UpSellId] Integer Identity(1,1) NOT NULL, UNIQUE ([UpSellId]),
	[DmgCategoryId] Integer NULL,
	[UpSellCode] Nvarchar(10) NOT NULL,
	[UpSellName] Nvarchar(50) NOT NULL,
	[UpSelldescription] Nvarchar(50) NOT NULL,
        [UpSellType] Smallint NOT NULL,
Primary Key ([UpSellId])
)</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> Alter table CNF_UpSell 
add  foreign key(DmgCategoryId) references CNF_DmgCategory (DmgCategoryId)



				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> Create table [CNF_Upsell2MatrixCell]
(
	[UpSell2MatrixCellId] Integer Identity(1,1) NOT NULL, UNIQUE ([UpSell2MatrixCellId]),
	[UpSellId] Integer NOT NULL,
	[MatrixCellId] Integer NOT NULL,
	[Link] Nvarchar(100) NULL,
Primary Key ([UpSell2MatrixCellId])
)</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Upsell2MatrixCell] 
  add  foreign key([UpSellId]) references [CNF_UpSell] ([UpSellId])  


				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table CNF_UpSell_Validity
(
	[UpSellValidityId] Integer Identity(1,1) NOT NULL, UNIQUE (UpSellValidityId),
	[UpSellId] Integer NOT NULL,
	[FromDate] Smalldatetime NULL,
	[ToDate] Smalldatetime NULL,
	[Sunday] Smallint NULL,
	[Monday] Smallint NULL,
	[Tuesday] Smallint NULL,
	[Wednesday] Smallint NULL,
	[Thursday] Smallint NULL,
	[Friday] Smallint NULL,
	[Saturday] Smallint NULL,
	[FromTime] Datetime NULL,
	[ToTime] Datetime NULL,
Primary Key (UpSellValidityId)
)</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_UpSell_Validity] 
  add  foreign key([UpSellId]) references [CNF_UpSell] ([UpSellId])  



				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_UpSell_Permission]
(
	[UpSellPermissionId] Integer Identity(1,1) NOT NULL, UNIQUE ([UpSellPermissionId]),
	[UpSellId] Integer NOT NULL,
	[UserGroupId] Integer NULL,
	[UserId] Integer NULL,
	[WorkstationId] Integer NULL,
	[SiteId] Integer NULL,
	[LocationId] Integer NULL,
	[OperatingAreaId] Integer NULL,
	[Allow] Smallint NOT NULL,
Primary Key ([UpSellPermissionId])
)</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_UpSell_Permission] 
  add  foreign key([UpSellId]) references [CNF_UpSell] ([UpSellId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_UpSell_Permission] 
  add  foreign key([WorkstationId]) references [CNF_Workstation] ([WorkstationId])  
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_UpSell_Permission] 
  add  foreign key([SiteId]) references [CNF_Site] ([SiteId])  </SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_UpSell_Permission] 
  add  foreign key([OperatingAreaId]) references [CNF_OperatingArea] ([OperatingAreaId])  </SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_UpSell_Permission] 
  add  foreign key([UserId]) references [CNF_User] ([UserId])  </SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_UpSell_Permission] 
  add  foreign key([UserGroupId]) references [CNF_UserGroup] ([UserGroupId])  </SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Esposito</ADDEDBY>
			<SQLVERSION>1993</SQLVERSION>
			<RMTRACKLINK>63364</RMTRACKLINK>
			<REASON>Alter table SYS_Lock increasing Holder coloumn capacity</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>DROP INDEX idxSysLockHolded ON SYS_Lock</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE SYS_Lock ALTER COLUMN Holder nchar(38) NOT NULL</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE NONCLUSTERED INDEX idxSysLockHolded ON SYS_Lock
(
	[Context] ASC,
	[Holder] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>1992</SQLVERSION>
			<RMTRACKLINK>61574</RMTRACKLINK>
			<REASON>Create Tables 
[0]- CNF_MembershipCard:
[1]- CNF_MembershipCardRule:
[2]- DATA_MembershipCardRule2Entity:

[3] - FK_CNF_MembershipCardRule_MSCardId
[4] - FK_DATA_MembershipCardRule2Entity_OperatingAreaId
[5] - FK_DATA_MembershipCardRule2Entity_MSCardRuleId

			</REASON>
			<TABLENAMES>CNF_MembershipCard=MSCardId
CNF_MembershipCardRule=MSCardRuleId
DATA_MembershipCardRule2Entity=MSCardRule2EntityId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>
IF NOT (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'CNF_MembershipCard'))
BEGIN

Create table [CNF_MembershipCard]
(
	[MSCardId] Integer Identity(1,1) NOT NULL,
	[Code] Nvarchar(10) NULL,
	[Name] Nvarchar(50) NULL,
	[Description] Nvarchar(100) NULL,
Primary Key ([MSCardId])
) 
END

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>
IF NOT (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'CNF_MembershipCardRule'))
BEGIN

Create table [CNF_MembershipCardRule]
(
	[MSCardRuleId] Integer Identity(1,1) NOT NULL,
	[MSCardId] Integer NOT NULL,
	[Rule1] Smallint NULL,
	[Rule2] Smallint NULL,
	[Rule3] Smallint NULL,
	[Rule4] Smallint NULL,
	[RuleCustom] Nvarchar(1000) NULL,
Primary Key ([MSCardRuleId])
) 

END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>
 IF NOT (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'DATA_MembershipCardRule2Entity'))
BEGIN

Create table [DATA_MembershipCardRule2Entity]
(
	[MSCardRule2EntityId] Integer Identity(1,1) NOT NULL,
	[OperatingAreaId] Integer NOT NULL,
	[MSCardRuleId] Integer NOT NULL,
	[EntityTable] Smallint NOT NULL,
	[EntityId] Integer NOT NULL,
Primary Key ([MSCardRule2EntityId])
) 

END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_MembershipCardRule'
	          AND CONSTRAINT_NAME = N'FK_CNF_MembershipCardRule_MSCardId'
)          
BEGIN
  ALTER TABLE [CNF_MembershipCardRule] WITH CHECK 
  ADD  CONSTRAINT [FK_CNF_MembershipCardRule_MSCardId] FOREIGN KEY([MSCardId])
  REFERENCES [CNF_MembershipCard] ([MSCardId])
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'DATA_MembershipCardRule2Entity'
	          AND CONSTRAINT_NAME = N'FK_DATA_MembershipCardRule2Entity_OperatingAreaId'
)          
BEGIN
  ALTER TABLE [DATA_MembershipCardRule2Entity] WITH CHECK 
  ADD  CONSTRAINT [FK_DATA_MembershipCardRule2Entity_OperatingAreaId] FOREIGN KEY([OperatingAreaId])
  REFERENCES [CNF_OperatingArea] ([OperatingAreaId])
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'DATA_MembershipCardRule2Entity'
	          AND CONSTRAINT_NAME = N'FK_DATA_MembershipCardRule2Entity_MSCardRuleId'
)          
BEGIN
  ALTER TABLE [DATA_MembershipCardRule2Entity] WITH CHECK 
  ADD  CONSTRAINT [FK_DATA_MembershipCardRule2Entity_MSCardRuleId] FOREIGN KEY([MSCardRuleId])
  REFERENCES [CNF_MembershipCardRule] ([MSCardRuleId])
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>smcdonald</ADDEDBY>
			<SQLVERSION>1991</SQLVERSION>
			<RMTRACKLINK>6330</RMTRACKLINK>
			<REASON>Add additional Column to CNF_PromotionProduct</REASON>
			<TABLENAMES>CNF_PromotionProduct=PromotionProductId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'CategoryExclude' AND
                Object_ID  = Object_ID(N'CNF_PromotionProduct'))
BEGIN
  ALTER TABLE CNF_PromotionProduct ADD CategoryExclude Int NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>smcdonald</ADDEDBY>
			<SQLVERSION>1990</SQLVERSION>
			<RMTRACKLINK>63401</RMTRACKLINK>
			<REASON>Add additional Column and Foreign Key constraint to CNF_PromotionProductCategory</REASON>
			<TABLENAMES>CNF_PromotionProductCategory=PromotionProductCategoryId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'PromotionItemRuleId' AND
                Object_ID  = Object_ID(N'CNF_PromotionProductCategory'))
BEGIN
  ALTER TABLE CNF_PromotionProductCategory ADD PromotionItemRuleId Int NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_PromotionProductCategory'
	          AND CONSTRAINT_NAME = N'FK_CNF_PromotionProductCategory_ItemRuleId'
)          
BEGIN
  ALTER TABLE [CNF_PromotionProductCategory] WITH CHECK 
  ADD  CONSTRAINT [FK_CNF_PromotionProductCategory_ItemRuleId] FOREIGN KEY([PromotionItemRuleId])
  REFERENCES [CNF_PromotionItemRule] ([PromotionItemRuleId])    
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>UPDATE PPC
  SET PPC.PromotionItemRuleId = 
    ( SELECT Max( PromotionItemRuleId ) From CNF_PromotionItemRule WHERE PromotionId = PPC.PromotionId 
    )
FROM CNF_PromotionProductCategory PPC
WHERE PPC.PromotionItemRuleId IS NULL</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'PromotionItemRuleId' AND
                Object_ID  = Object_ID(N'CNF_PromotionProductCategory'))
BEGIN
  ALTER TABLE CNF_PromotionProductCategory ALTER COLUMN PromotionItemRuleId int NOT NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FCARAMELLA</ADDEDBY>
			<SQLVERSION>1989</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>ADD GeneratedByTheSystem TO DATA_SaleITem

			</REASON>
			<TABLENAMES>DATA_SaleItem=SaleItemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'GeneratedByTheSystem' AND
                Object_ID  = Object_ID(N'DATA_SaleItem'))
BEGIN
  ALTER TABLE DATA_SaleItem ADD GeneratedByTheSystem Smallint NULL
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>1988</SQLVERSION>
			<RMTRACKLINK>61286</RMTRACKLINK>
			<REASON>CNF_Tax added new fields
0 - AppliedFrom
1 - AppliedTo</REASON>
			<TABLENAMES>CNF_Tax=TaxId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'AppliedFrom' AND
                Object_ID  = Object_ID(N'CNF_Tax'))
BEGIN
  ALTER TABLE CNF_Tax ADD AppliedFrom Float NULL
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'AppliedTo' AND
                Object_ID  = Object_ID(N'CNF_Tax'))
BEGIN
  ALTER TABLE CNF_Tax ADD AppliedTo Float NULL
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Esposito</ADDEDBY>
			<SQLVERSION>1987</SQLVERSION>
			<RMTRACKLINK>62970</RMTRACKLINK>
			<REASON>Create table Data_Ticket_History</REASON>
			<TABLENAMES>Data_TicketHistory=TicketHistoryId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'DATA_TicketHistory'))
BEGIN
Create table [DATA_TicketHistory]
(
	[TicketHistoryId] Integer Identity(1,1) NOT NULL,
	[TransactionId] Integer NOT NULL,
	[TicketId] Integer NOT NULL,
	[AccountId] Integer NULL,
	[VoidType] Smallint NULL,
	[InsDateTime] Datetime NOT NULL,
Primary Key ([TicketHistoryId])
) 
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'DATA_TicketHistory'
	          AND CONSTRAINT_NAME = N'FK_DATA_TicketHistory_AccountId'
)          
BEGIN
  ALTER TABLE [DATA_TicketHistory] WITH CHECK 
  ADD  CONSTRAINT [FK_DATA_TicketHistory_AccountId] FOREIGN KEY([AccountId])
  REFERENCES [DATA_Account] ([AccountId])    
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'DATA_TicketHistory'
	          AND CONSTRAINT_NAME = N'FK_DATA_TicketHistory_TicketId'
)          
BEGIN
  ALTER TABLE [DATA_TicketHistory] WITH CHECK 
  ADD  CONSTRAINT [FK_DATA_TicketHistory_TicketId] FOREIGN KEY([TicketId])
  REFERENCES [DATA_Ticket] ([TicketId])   
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Esposito</ADDEDBY>
			<SQLVERSION>1986</SQLVERSION>
			<RMTRACKLINK>62267</RMTRACKLINK>
			<REASON>New table DATA_TicketPermission</REASON>
			<TABLENAMES>DATA_TicketPermission=TicketPermissionId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'DATA_TicketPermission'))
BEGIN
Create table [DATA_TicketPermission]
(
	[TicketPermissionId] Integer Identity(1,1) NOT NULL,
	[TicketId] Integer NOT NULL,
	[SiteId] Integer NULL,
	[WorkstationId] Integer NULL,
	[UserId] Integer NULL,
	[UserGroupId] Integer NULL,
	[AccountId] Integer NULL,
	[OperatingAreaId] Integer NULL,
	[Allow] Smallint NULL,
Primary Key ([TicketPermissionId])
)
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'DATA_TicketPermission'
	          AND CONSTRAINT_NAME = N'FK_DATA_TicketPermission_TicketId'
)          
BEGIN
  ALTER TABLE [DATA_TicketPermission] WITH CHECK 
  ADD  CONSTRAINT [FK_DATA_TicketPermission_TicketId] FOREIGN KEY([TicketId])
  REFERENCES [DATA_Ticket] ([TicketId])    
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'DATA_TicketPermission'
	          AND CONSTRAINT_NAME = N'FK_DATA_TicketPermission_SiteId'
)          
BEGIN
  ALTER TABLE [DATA_TicketPermission] WITH CHECK 
  ADD  CONSTRAINT [FK_DATA_TicketPermission_SiteId] FOREIGN KEY([SiteId])
  REFERENCES [CNF_Site] ([SiteId])    
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'DATA_TicketPermission'
	          AND CONSTRAINT_NAME = N'FK_DATA_TicketPermission_WorkstationId'
)          
BEGIN
  ALTER TABLE [DATA_TicketPermission] WITH CHECK 
  ADD  CONSTRAINT [FK_DATA_TicketPermission_WorkstationId] FOREIGN KEY([WorkstationId])
  REFERENCES [CNF_Workstation] ([WorkstationId])    
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'DATA_TicketPermission'
	          AND CONSTRAINT_NAME = N'FK_DATA_TicketPermission_UserId'
)          
BEGIN
  ALTER TABLE [DATA_TicketPermission] WITH CHECK 
  ADD  CONSTRAINT [FK_DATA_TicketPermission_UserId] FOREIGN KEY([UserId])
  REFERENCES [CNF_User] ([UserId])    
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'DATA_TicketPermission'
	          AND CONSTRAINT_NAME = N'FK_DATA_TicketPermission_AccountId'
)          
BEGIN
  ALTER TABLE [DATA_TicketPermission] WITH CHECK 
  ADD  CONSTRAINT [FK_DATA_TicketPermission_AccountId] FOREIGN KEY([AccountId])
  REFERENCES [DATA_Account] ([AccountId])    
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'DATA_TicketPermission'
	          AND CONSTRAINT_NAME = N'FK_DATA_TicketPermission_OperatingAreaId'
)          
BEGIN
  ALTER TABLE [DATA_TicketPermission] WITH CHECK 
  ADD  CONSTRAINT [FK_DATA_TicketPermission_OperatingAreaId] FOREIGN KEY([OperatingAreaId])
  REFERENCES [CNF_OperatingArea] ([OperatingAreaId])    
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Esposito</ADDEDBY>
			<SQLVERSION>1985</SQLVERSION>
			<RMTRACKLINK>63247</RMTRACKLINK>
			<REASON>SaleItemId index on DATA_SaleItem2CostCenter</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT *  FROM sys.indexes  WHERE name='IX_DATA_SaleItem2CostCenter_SaleItemId' 
    AND object_id = OBJECT_ID('[dbo].[DATA_SaleItem2CostCenter]'))
BEGIN
  Create Index [IX_DATA_SaleItem2CostCenter_SaleItemId] ON [DATA_SaleItem2CostCenter] ([SaleItemId])  
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Esposito</ADDEDBY>
			<SQLVERSION>1984</SQLVERSION>
			<RMTRACKLINK>62266</RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES>DATA_Ticket2TicketPackage=Ticket2TicketPackageId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'DATA_Ticket2TicketPackage'))
BEGIN
Create table [DATA_Ticket2TicketPackage]
(
	[Ticket2TicketPackageId] Integer Identity(1,1) NOT NULL,
	[TicketPackageId] Integer NOT NULL,
	[TicketId] Integer NOT NULL,
Primary Key ([Ticket2TicketPackageId])
) 
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'DATA_Ticket2TicketPackage'
	          AND CONSTRAINT_NAME = N'FK_DATA_Ticket2TicketPackage_TicketId'
)          
BEGIN
  ALTER TABLE [DATA_Ticket2TicketPackage] WITH CHECK 
  ADD  CONSTRAINT [FK_DATA_Ticket2TicketPackage_TicketId] FOREIGN KEY([TicketId])
  REFERENCES [DATA_Ticket] ([TicketId])    
END</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'DATA_Ticket2TicketPackage'
	          AND CONSTRAINT_NAME = N'FK_DATA_Ticket2TicketPackage_TicketPackageId'
)          
BEGIN
  ALTER TABLE [DATA_Ticket2TicketPackage] WITH CHECK 
  ADD  CONSTRAINT [FK_DATA_Ticket2TicketPackage_TicketPackageId] FOREIGN KEY([TicketPackageId])
  REFERENCES [DATA_Ticket] ([TicketId])    
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>andreadavanzo</ADDEDBY>
			<SQLVERSION>1983</SQLVERSION>
			<RMTRACKLINK>62565</RMTRACKLINK>
			<REASON>Changed columns type from float to money
[0] DATA_SaleItemTax
[1] DATA_SaleTax
[2] DATA_TransactionTax</REASON>
			<TABLENAMES>DATA_SaleItemTax=SaleItemTaxId
DATA_SaleTax=SaleTaxId
DATA_TransactionTax=TransactionTaxId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
            WHERE Name = N'TaxValue' AND
            Object_ID  = Object_ID(N'DATA_SaleItemTax'))
BEGIN
  ALTER TABLE [DATA_SaleItemTax] ALTER COLUMN TaxValue Money NULL
END

IF EXISTS (SELECT * FROM sys.columns
            WHERE Name = N'TaxAmount' AND
            Object_ID  = Object_ID(N'DATA_SaleItemTax'))
BEGIN
  ALTER TABLE [DATA_SaleItemTax] ALTER COLUMN TaxAmount Money NULL
END

IF EXISTS (SELECT * FROM sys.columns
            WHERE Name = N'Net' AND
	    Object_ID  = Object_ID(N'DATA_SaleItemTax'))
BEGIN
  ALTER TABLE [DATA_SaleItemTax] ALTER COLUMN Net Money NULL
END

IF EXISTS (SELECT * FROM sys.columns
            WHERE Name = N'Gros' AND
            Object_ID  = Object_ID(N'DATA_SaleItemTax'))
BEGIN
  ALTER TABLE [DATA_SaleItemTax] ALTER COLUMN Gros Money NULL
END            </SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
            WHERE Name = N'TaxAmount' AND
            Object_ID  = Object_ID(N'DATA_SaleTax'))
BEGIN
  ALTER TABLE [DATA_SaleTax] ALTER COLUMN TaxAmount Money NULL
END

IF EXISTS (SELECT * FROM sys.columns
            WHERE Name = N'Net' AND
	    Object_ID  = Object_ID(N'DATA_SaleTax'))
BEGIN
  ALTER TABLE [DATA_SaleTax] ALTER COLUMN Net Money NULL
END

IF EXISTS (SELECT * FROM sys.columns
            WHERE Name = N'Gros' AND
            Object_ID  = Object_ID(N'DATA_SaleTax'))
BEGIN
  ALTER TABLE [DATA_SaleTax] ALTER COLUMN Gros Money NULL
END        </SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
            WHERE Name = N'TaxAmount' AND
            Object_ID  = Object_ID(N'DATA_TransactionTax'))
BEGIN
  ALTER TABLE [DATA_TransactionTax] ALTER COLUMN TaxAmount Money NULL
END

IF EXISTS (SELECT * FROM sys.columns
            WHERE Name = N'Gros' AND
            Object_ID  = Object_ID(N'DATA_TransactionTax'))
BEGIN
  ALTER TABLE [DATA_TransactionTax] ALTER COLUMN Gros Money NULL
END        </SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>andreadavanzo</ADDEDBY>
			<SQLVERSION>1982</SQLVERSION>
			<RMTRACKLINK>63080</RMTRACKLINK>
			<REASON>[0] Change the DiscountAmount column type into Money</REASON>
			<TABLENAMES>DATA_SaleItemRule=SaleItemRuleId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
            WHERE Name = N'DiscountAmount' AND
            Object_ID  = Object_ID(N'DATA_SaleItemRule'))
BEGIN
  ALTER TABLE [DATA_SaleItemRule] ALTER COLUMN DiscountAmount Money NULL
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Esposito</ADDEDBY>
			<SQLVERSION>1981</SQLVERSION>
			<RMTRACKLINK>62968</RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES>DATA_SaleItem=SaleItemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'BaseSaleId' AND
                Object_ID  = Object_ID(N'DATA_SaleItem'))
BEGIN
  ALTER TABLE DATA_SaleItem ADD BaseSaleId Int 
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'DATA_SaleItem'
	          AND CONSTRAINT_NAME = N'FK_DATA_SaleItem_BaseSaleId'
)          
BEGIN
  ALTER TABLE [DATA_SaleItem] WITH CHECK 
  ADD  CONSTRAINT [FK_DATA_SaleItem_BaseSaleId] FOREIGN KEY([BaseSaleId])
  REFERENCES [DATA_Sale] ([SaleId])    
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Esposito</ADDEDBY>
			<SQLVERSION>1980</SQLVERSION>
			<RMTRACKLINK>62650</RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES>DATA_SaleItem2CostCenter=SaleItem2CostCenterId
DATA_SaleItem=SaleItemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'TransactionId' AND
                Object_ID  = Object_ID(N'DATA_SaleItem2CostCenter'))
BEGIN
  ALTER TABLE DATA_SaleItem2CostCenter ADD TransactionId Int 
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'DATA_SaleItem2CostCenter'
	          AND CONSTRAINT_NAME = N'FK_DATA_SaleItem2CostCenter_TransactionId'
)          
BEGIN
  ALTER TABLE [DATA_SaleItem2CostCenter] WITH CHECK 
  ADD  CONSTRAINT [FK_DATA_SaleItem2CostCenter_TransactionId] FOREIGN KEY([TransactionId])
  REFERENCES [DATA_Transaction] ([TransactionId])    
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'OrigSaleItemId' AND
                Object_ID  = Object_ID(N'DATA_SaleItem'))
BEGIN
  ALTER TABLE DATA_SaleItem ADD OrigSaleItemId Int 
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'DATA_SaleItem'
	          AND CONSTRAINT_NAME = N'FK_DATA_SaleItem_OrigSaleItemId'
)          
BEGIN
  ALTER TABLE [DATA_SaleItem] WITH CHECK 
  ADD  CONSTRAINT [FK_DATA_SaleItem_OrigSaleItemId] FOREIGN KEY([OrigSaleItemId])
  REFERENCES [DATA_SaleItem] ([SaleItemId])    
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>1979</SQLVERSION>
			<RMTRACKLINK>62479</RMTRACKLINK>
			<REASON>Populate DATA_Right for each Site in order to set a default value for right  PaymentOpenCashDrawer</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>
select 1
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Esposito</ADDEDBY>
			<SQLVERSION>1978</SQLVERSION>
			<RMTRACKLINK>62266</RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES>CNF_ExternalTicketRange=ExternalTicketRangeId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'VarRangeLength' AND
                Object_ID  = Object_ID(N'CNF_ExternalTicketRange'))
BEGIN
  ALTER TABLE CNF_ExternalTicketRange ADD VarRangeLength Smallint 
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>kdixon</ADDEDBY>
			<SQLVERSION>1977</SQLVERSION>
			<RMTRACKLINK>61157</RMTRACKLINK>
			<REASON>Updated Data Dictionary Items</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>andreadavanzo</ADDEDBY>
			<SQLVERSION>1976</SQLVERSION>
			<RMTRACKLINK>62656</RMTRACKLINK>
			<REASON>Create table DATA_SaleItemTax
[0] Create Table
[1] Create Index</REASON>
			<TABLENAMES>DATA_SaleItemTax=SaleItemTaxId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'DATA_SaleItemTax'))
BEGIN
  Create table [DATA_SaleItemTax]
  (
  	[SaleItemTaxId] Integer Identity NOT NULL,
	[SaleItemId] Integer NOT NULL,
	[TaxId] Integer NOT NULL,
	[TaxCode] Nvarchar(10) NOT NULL,
	[TaxValue] Float NULL,
	[TaxAmount] Float NULL,
	[Net] Money NULL,
	[Gros] Float NULL,
	[TaxExempt] Smallint NOT NULL,
  Primary Key ([SaleItemTaxId])
  )  
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'DATA_SaleItemTax'
	          AND CONSTRAINT_NAME = N'FK_DATA_SaleItemTax_Tax'
)          
BEGIN
  ALTER TABLE [DATA_SaleItemTax] WITH CHECK 
  ADD  CONSTRAINT [FK_DATA_SaleItemTax_Tax] FOREIGN KEY([TaxId])
  REFERENCES [CNF_Tax] ([TaxId])    
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'DATA_SaleItemTax'
	          AND CONSTRAINT_NAME = N'FK_DATA_SaleItemTax_SaleItem'
)          
BEGIN
  ALTER TABLE [DATA_SaleItemTax]  WITH CHECK 
  ADD  CONSTRAINT [FK_DATA_SaleItemTax_SaleItem] FOREIGN KEY([SaleItemId])
  REFERENCES [DATA_SaleItem] ([SaleItemId])  
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT *  FROM sys.indexes  WHERE name='Idx_SaleItemTax' 
    AND object_id = OBJECT_ID('[dbo].[DATA_SaleItemTax]'))
BEGIN
  Create Index [Idx_SaleItemTax] ON [DATA_SaleItemTax] ([SaleItemId] ,[TaxId] )  
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>pdalben</ADDEDBY>
			<SQLVERSION>1975</SQLVERSION>
			<RMTRACKLINK>62153</RMTRACKLINK>
			<REASON>DATA_Payment added new fields
0 - ChangeAmount
1 - ChangeType</REASON>
			<TABLENAMES>DATA_Payment=PaymentId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'ChangeAmount' AND
                Object_ID  = Object_ID(N'DATA_Payment'))
BEGIN
  ALTER TABLE DATA_Payment ADD ChangeAmount Float Default 0 NOT NULL
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'ChangeType' AND
                Object_ID  = Object_ID(N'DATA_Payment'))
BEGIN
  ALTER TABLE DATA_Payment ADD ChangeType Smallint Default 0 NOT NULL
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>marcoviscusi</ADDEDBY>
			<SQLVERSION>1974</SQLVERSION>
			<RMTRACKLINK>61591</RMTRACKLINK>
			<REASON>CNF_Performance
[0] add field OnSaleType</REASON>
			<TABLENAMES>CNF_Performance=PerformanceId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'ONSALETYPE' AND
                Object_ID  = Object_ID(N'CNF_Performance'))
BEGIN
  ALTER TABLE CNF_Performance ADD OnSaleType Integer
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Programmatore</ADDEDBY>
			<SQLVERSION>1973</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.5.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Programmatore</ADDEDBY>
			<SQLVERSION>1972</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.5.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Programmatore</ADDEDBY>
			<SQLVERSION>1971</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.5.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Programmatore</ADDEDBY>
			<SQLVERSION>1970</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.5.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Programmatore</ADDEDBY>
			<SQLVERSION>1969</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.5.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Programmatore</ADDEDBY>
			<SQLVERSION>1968</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.5.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Programmatore</ADDEDBY>
			<SQLVERSION>1967</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.5.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Programmatore</ADDEDBY>
			<SQLVERSION>1966</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.5.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Programmatore</ADDEDBY>
			<SQLVERSION>1965</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.5.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Programmatore</ADDEDBY>
			<SQLVERSION>1964</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.5.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Programmatore</ADDEDBY>
			<SQLVERSION>1963</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.5.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Programmatore</ADDEDBY>
			<SQLVERSION>1962</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.5.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Programmatore</ADDEDBY>
			<SQLVERSION>1961</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.5.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Programmatore</ADDEDBY>
			<SQLVERSION>1960</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.5.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Programmatore</ADDEDBY>
			<SQLVERSION>1959</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.5.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Programmatore</ADDEDBY>
			<SQLVERSION>1958</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.5.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Programmatore</ADDEDBY>
			<SQLVERSION>1957</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.5.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Programmatore</ADDEDBY>
			<SQLVERSION>1956</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.5.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Programmatore</ADDEDBY>
			<SQLVERSION>1955</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.5.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Programmatore</ADDEDBY>
			<SQLVERSION>1954</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.5.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>pdalben</ADDEDBY>
			<SQLVERSION>1953</SQLVERSION>
			<RMTRACKLINK>60408</RMTRACKLINK>
			<REASON>Expanded field size
0 - DATA_Ticket.ExternalReferenceId from 250 to 400</REASON>
			<TABLENAMES>DATA_Ticket=TicketId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>-- Expand column DATA_Ticket.ExternalReferenceId from 250 to 400
IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'ExternalReferenceId' AND
                Object_ID  = Object_ID(N'DATA_Ticket'))
BEGIN
  ALTER TABLE DATA_Ticket 
    ALTER COLUMN [ExternalReferenceId] [varchar](400) NULL;
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>pdalben</ADDEDBY>
			<SQLVERSION>1952</SQLVERSION>
			<RMTRACKLINK>60408</RMTRACKLINK>
			<REASON>Expanded field size
0 - DATA_Right.StrValue from 80 to 200</REASON>
			<TABLENAMES>DATA_Right=DataRightId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>-- Expand column DATA_Right.StrVale from 80 to 200
IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'StrValue' AND
                Object_ID  = Object_ID(N'DATA_Right'))
BEGIN
  ALTER TABLE DATA_Right 
    ALTER COLUMN [StrValue] [varchar](200) NOT NULL;
END</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>pdalben</ADDEDBY>
			<SQLVERSION>1951</SQLVERSION>
			<RMTRACKLINK>60408</RMTRACKLINK>
			<REASON>Expanded field size
0 - DATA_MediaIdentifier.IdentifierCode from 100 to 400
1 - CNF_AlternativeCodes.Code from 32 to 36</REASON>
			<TABLENAMES>DATA_MediaIdentifier=MediaIdentifierId
CNF_AlternativeCodes=AlternativeCodesId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>-- Expand column IdentifierCode from 100 to 400

IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'IdentifierCode' AND
                Object_ID  = Object_ID(N'DATA_MediaIdentifier'))
BEGIN
  ALTER TABLE DATA_MediaIdentifier 
    ALTER COLUMN [IdentifierCode] [varchar](400) NOT NULL;
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>-- Expand column Code from 32 to 36

IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Code' AND
                Object_ID  = Object_ID(N'CNF_AlternativeCodes'))
BEGIN
  ALTER TABLE CNF_AlternativeCodes 
    ALTER COLUMN [Code] [varchar](36) NOT NULL;
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>kdixon</ADDEDBY>
			<SQLVERSION>1950</SQLVERSION>
			<RMTRACKLINK>62268</RMTRACKLINK>
			<REASON>Modify vwStatisticalGroup to no longer user * to get columns from the cnf_statisticalgroup.</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS(SELECT * FROM dbo.sysobjects WHERE ID = OBJECT_ID(N'[dbo].[vwStatisticalGroup]') AND OBJECTPROPERTY(id, N'IsView') = 1)
BEGIN
	DROP VIEW vwStatisticalGroup
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE view [dbo].[vwStatisticalGroup]
as
select
Main.StatisticalGroupId MainId,
cschild.StatisticalGroupId ChildId,
Main.StatisticalGroupDescription,
cschild.StatisticalGroupDescription Child,
Main.Level MainLevel,
cschild.Level ChildLevel,
cschild.Level-Main.Level RelLevel,
Main.Position MainPosition,
cschild.Position ChildPosition,
cschild.Position-Main.Position RelPosition

from
(
select
csg.Level,
csg.Position,
csg.StatisticalGroupId,
csg.Position StartPos,
csg.StatisticalGroupDescription,
Min(csgns.Position) EndPos
from
cnf_statisticalgroup csg left join
cnf_statisticalgroup csgns on csgns.Level &lt;= csg.Level and csgns.Position&gt;csg.Position
group by
csg.Level,
csg.Position,
csg.StatisticalGroupDescription,
csg.StatisticalGroupId,
csg.Position
union
select
0,
0,
null,
0,
'All',
null
) Main left join
( select StatisticalGroupId, StatisticalGroupCode, StatisticalGroupDescription, ParentId, Position, Level from cnf_statisticalgroup
 union
 select
  0,'','All',null,0,0) as cschild on cschild.Position &gt;= Main.StartPos and cschild.Position &lt;= IsNull(EndPos-1, cschild.Position)
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>marcoviscusi</ADDEDBY>
			<SQLVERSION>1949</SQLVERSION>
			<RMTRACKLINK>60086</RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>kdixon</ADDEDBY>
			<SQLVERSION>1948</SQLVERSION>
			<RMTRACKLINK>61775</RMTRACKLINK>
			<REASON>New global function to format currency for reports</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS(SELECT * FROM dbo.sysobjects WHERE ID = OBJECT_ID(N'[dbo].[F_FormatCurrency]') AND OBJECTPROPERTY(id, N'IsScalarFunction') = 1)
BEGIN
	DROP FUNCTION F_FormatCurrency
END

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE FUNCTION F_FormatCurrency(@Amount float)
RETURNS varchar(50)
AS 
BEGIN
    DECLARE @ret varchar(50),
	        @symbol varchar(10),
         	@Position varchar(1),
			@Format varchar(15);

	SELECT @symbol = Symbol, @Position = PosOndisplay, @Format = Format
	FROM CNF_Currency
	WHERE CurrencyType = 1

	if @Position = 1  --Position on Right
          set @ret = CONVERT(VARCHAR, CAST(@amount AS money), 1) + ' ' + @symbol
        else
          set @ret =  @symbol + ' ' + CONVERT(VARCHAR, CAST(@amount AS money), 1);

	RETURN @ret;
END;




				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>GRANT EXECUTE ON [dbo].[F_FormatCurrency] TO [public]
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>1947</SQLVERSION>
			<RMTRACKLINK>61811</RMTRACKLINK>
			<REASON>CNF_Location
[0] add  field InVenueLimitActive smallint
[1] update old records
[2] set as not null
[3] add  field InVenueLimit Integer

ADM_AccessConfiguration
[4] add  field InVenueLimitActive smallint
[5] update old records
[6] set as not null
[7] add  field InVenueLimit Integer


			</REASON>
			<TABLENAMES>CNF_Location=LocationId
ADM_AccessConfiguration=AccessConfigurationId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>
-- [0] add  field InVenueLimitActive smallint

IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'InVenueLimitActive' AND
                Object_ID  = Object_ID(N'CNF_Location'))
BEGIN
  ALTER TABLE CNF_Location ADD InVenueLimitActive smallint default 0
END

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>
--[1] update old records

  IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'InVenueLimitActive' AND
                Object_ID  = Object_ID(N'CNF_Location'))
BEGIN
  update CNF_Location       
  set InVenueLimitActive = 0
  where InVenueLimitActive is null                  
END

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>-- [2] set as not null

IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'InVenueLimitActive' AND
                Object_ID  = Object_ID(N'CNF_Location'))
BEGIN
  ALTER TABLE CNF_Location ALTER COLUMN InVenueLimitActive smallint not null
END


				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>
--[3] add  field InVenueLimit Integer

IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'InVenueLimit' AND
                Object_ID  = Object_ID(N'CNF_Location'))
BEGIN
  ALTER TABLE CNF_Location ADD InVenueLimit integer
END

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>--[4] add  field InVenueLimitActive smallint

IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'InVenueLimitActive' AND
                Object_ID  = Object_ID(N'ADM_AccessConfiguration'))
BEGIN
  ALTER TABLE ADM_AccessConfiguration ADD InVenueLimitActive smallint default 0
END

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> --[5] update old records 

   IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'InVenueLimitActive' AND
                Object_ID  = Object_ID(N'ADM_AccessConfiguration'))
BEGIN
  update ADM_AccessConfiguration       
  set InVenueLimitActive = 0
  where InVenueLimitActive is null                  
END

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> --[6] set as not null 

 IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'InVenueLimitActive' AND
                Object_ID  = Object_ID(N'ADM_AccessConfiguration'))
BEGIN
  ALTER TABLE ADM_AccessConfiguration ALTER COLUMN InVenueLimitActive smallint not null
END


				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>--[7] add  field InVenueLimit Integer


IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'InVenueLimit' AND
                Object_ID  = Object_ID(N'ADM_AccessConfiguration'))
BEGIN
  ALTER TABLE ADM_AccessConfiguration ADD InVenueLimit integer
END


				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>marcoviscusi</ADDEDBY>
			<SQLVERSION>1946</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>DATA_SaleItem
[0] add  field PriceType</REASON>
			<TABLENAMES>DATA_SaleItem=SaleItemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'PriceType' AND
                Object_ID  = Object_ID(N'DATA_SaleItem'))
BEGIN
  ALTER TABLE DATA_SaleItem ADD PriceType Integer default 0 
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Esposito</ADDEDBY>
			<SQLVERSION>1945</SQLVERSION>
			<RMTRACKLINK>61373</RMTRACKLINK>
			<REASON>DROP TABLE [DATA_SalePaymentFlexInfo]

CREATE OF [DATA_PaymentFlexInfo]</REASON>
			<TABLENAMES>DATA_PaymentFlexInfo=PaymentFlexInfoId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'DATA_SalePaymentFlexInfo'))
BEGIN
   DROP TABLE DATA_SalePaymentFlexInfo;
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'DATA_PaymentFlexInfo'))
BEGIN
Create table [DATA_PaymentFlexInfo]
(
	[PaymentFlexInfoId] Integer Identity(1,1) NOT NULL,
	[FlexContractId] Integer NOT NULL,
	[PayorAccountId] Integer NOT NULL,
	[WorkstationId] Integer NOT NULL,
	[UserId] Integer NOT NULL,
	[FinancedAmount] Float NULL,
	[DownpaymentAmount] Float NULL,
	[FeeAmount] Float NULL,
	[RefundableFeeAmount] Float NULL,
	[DownpaymentFeeAmount] Float NULL,
	[DownpaymentRefundableFeeAmount] Float NULL,
	[InstallmentAmount] Float NULL,
	[AnnualRate] Float NULL,
	[CreditCardRecap] Char(4) NULL,
	[CardTypeDesc] Varchar(20) NULL,
Primary Key ([PaymentFlexInfoId])
) 
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'DATA_PaymentFlexInfo'
	          AND CONSTRAINT_NAME = N'FK_DATA_PaymentFlexInfo_FlexContractId'
)          
BEGIN
   ALTER TABLE [DATA_PaymentFlexInfo]  
   WITH CHECK ADD CONSTRAINT [FK_DATA_PaymentFlexInfo_FlexContractId] FOREIGN KEY([FlexContractId])
   REFERENCES [CNF_FlexContract] ([FlexContractId])
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'DATA_PaymentFlexInfo'
	          AND CONSTRAINT_NAME = N'FK_DATA_PaymentFlexInfo_AccountId'
)          
BEGIN
   ALTER TABLE [DATA_PaymentFlexInfo]  
   WITH CHECK ADD CONSTRAINT [FK_DATA_PaymentFlexInfo_AccountId] FOREIGN KEY([PayorAccountId])
   REFERENCES [DATA_ACCOUNT] ([AccountId])
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'DATA_PaymentFlexInfo'
	          AND CONSTRAINT_NAME = N'FK_DATA_PaymentFlexInfo_WorkstationId'
)          
BEGIN
   ALTER TABLE [DATA_PaymentFlexInfo]  
   WITH CHECK ADD CONSTRAINT [FK_DATA_PaymentFlexInfo_WorkstationId] FOREIGN KEY([WorkstationId])
   REFERENCES [CNF_Workstation] ([WorkstationId])
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'DATA_PaymentFlexInfo'
	          AND CONSTRAINT_NAME = N'FK_DATA_PaymentFlexInfo_UserId'
)          
BEGIN
   ALTER TABLE [DATA_PaymentFlexInfo]  
   WITH CHECK ADD CONSTRAINT [FK_DATA_PaymentFlexInfo_UserId] FOREIGN KEY([UserId])
   REFERENCES [CNF_User] ([UserId])
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Esposito</ADDEDBY>
			<SQLVERSION>1944</SQLVERSION>
			<RMTRACKLINK>61373</RMTRACKLINK>
			<REASON>Create table [DATA_SalePaymentFlexInfo]
(
	[SalePaymentFlexInfoId] Integer Identity(1,1) NOT NULL,
	[SaleId] Integer NOT NULL,
	[FlexContractId] Integer NOT NULL,
	[PayorAccountId] Integer NOT NULL,
	[FinancedAmount] Float NULL,
	[DownpaymentAmount] Float NULL,
	[FeeAmount] Float NULL,
	[RefundableFeeAmount] Float NULL,
	[DownpaymentFeeAmount] Float NULL,
	[DownpaymentRefundableFeeAmount] Float NULL,
	[InstallmentAmount] Float NULL,
	[AnnualRate] Float NULL,
	[CreditCardRecap] Char(4) NULL,
	[CardTypeDesc] Varchar(20) NULL,
Primary Key ([SalePaymentFlexInfoId])
) </REASON>
			<TABLENAMES>DATA_SalePaymentFlexInfo=SalePaymentFlexInfoId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'DATA_SalePaymentFlexInfo'))
BEGIN
Create table [DATA_SalePaymentFlexInfo]
(
	[SalePaymentFlexInfoId] Integer Identity(1,1) NOT NULL,
	[SaleId] Integer NOT NULL,
	[FlexContractId] Integer NOT NULL,
	[PayorAccountId] Integer NOT NULL,
	[FinancedAmount] Float NULL,
	[DownpaymentAmount] Float NULL,
	[FeeAmount] Float NULL,
	[RefundableFeeAmount] Float NULL,
	[DownpaymentFeeAmount] Float NULL,
	[DownpaymentRefundableFeeAmount] Float NULL,
	[InstallmentAmount] Float NULL,
	[AnnualRate] Float NULL,
	[CreditCardRecap] Char(4) NULL,
	[CardTypeDesc] Varchar(20) NULL,
Primary Key ([SalePaymentFlexInfoId])
) 
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'DATA_SalePaymentFlexInfo'
	          AND CONSTRAINT_NAME = N'FK_DATA_SalePaymentFlexInfo_SaleId'
)          
BEGIN
   ALTER TABLE [DATA_SalePaymentFlexInfo]  
   WITH CHECK ADD CONSTRAINT [FK_DATA_SalePaymentFlexInfo_SaleId] FOREIGN KEY([SaleId])
   REFERENCES [DATA_SALE] ([SaleId])
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'DATA_SalePaymentFlexInfo'
	          AND CONSTRAINT_NAME = N'FK_DATA_SalePaymentFlexInfo_AccountId'
)          
BEGIN
   ALTER TABLE [DATA_SalePaymentFlexInfo]  
   WITH CHECK ADD CONSTRAINT [FK_DATA_SalePaymentFlexInfo_AccountId] FOREIGN KEY([PayorAccountId])
   REFERENCES [DATA_ACCOUNT] ([AccountId])
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'DATA_SalePaymentFlexInfo'
	          AND CONSTRAINT_NAME = N'FK_DATA_SalePaymentFlexInfo_FlexContractId'
)          
BEGIN
   ALTER TABLE [DATA_SalePaymentFlexInfo]  
   WITH CHECK ADD CONSTRAINT [FK_DATA_SalePaymentFlexInfo_FlexContractId] FOREIGN KEY([FlexContractId])
   REFERENCES [CNF_FlexContract] ([FlexContractId])
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>smcdonald</ADDEDBY>
			<SQLVERSION>1943</SQLVERSION>
			<RMTRACKLINK>60330</RMTRACKLINK>
			<REASON>Create table [CNF_PromotionProductCategory]</REASON>
			<TABLENAMES>CNF_PromotionProductCategory=PromotionProductCategoryId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'CNF_PromotionProductCategory'))
BEGIN
Create table [CNF_PromotionProductCategory]
(
  [PromotionProductCategoryId] Integer IDENTITY(1, 1) NOT NULL, UNIQUE ([PromotionProductCategoryId]),
  [PromotionId] Integer NOT NULL,
  [ProductCategoryId] Integer NOT NULL,

Primary Key ([PromotionProductCategoryId])
) 
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_PromotionProductCategory'
	          AND CONSTRAINT_NAME = N'FK_CNF_PromotionProductCategory_PromotionId'
)          
BEGIN
   ALTER TABLE [CNF_PromotionProductCategory]  
   WITH CHECK ADD CONSTRAINT [FK_CNF_PromotionProductCategory_PromotionId] FOREIGN KEY([PromotionId])
   REFERENCES [CNF_Promotion] ([PromotionId])
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'DATA_PaymentFlex2SaleItem'
	          AND CONSTRAINT_NAME = N'FK_CNF_PromotionProductCategory_CategoryId'
)          
BEGIN
   ALTER TABLE [CNF_PromotionProductCategory]  
   WITH CHECK ADD CONSTRAINT [FK_CNF_PromotionProductCategory_CategoryId] FOREIGN KEY([ProductCategoryId])
   REFERENCES [STOCK_CNF_ProductCategory] ([CategoryId])
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1942</SQLVERSION>
			<RMTRACKLINK>59068</RMTRACKLINK>
			<REASON>CNF_Subscription
[0] add field Weight as null
[1] update not null value
[2] set Weight as not null</REASON>
			<TABLENAMES>CNF_Subscription=SubscriptionId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>
IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Weight' AND
                Object_ID  = Object_ID(N'CNF_Subscription'))
BEGIN
  ALTER TABLE CNF_Subscription ADD Weight integer NULL
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_Subscription
set Weight =  Subscriptionid where Weight is null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
            WHERE Name = N'Weight' AND
            Object_ID  = Object_ID(N'CNF_Subscription'))
BEGIN
  ALTER TABLE CNF_Subscription ALTER COLUMN Weight integer not null
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>1941</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>DATA_DmgData
[0] Add index (DmgType , FKey, ObjType)</REASON>
			<TABLENAMES>DATA_DmgData=DmgDataId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>  IF not EXISTS (SELECT *  FROM sys.indexes  WHERE name='IDX_DmgTypeFKeyObjType' 
    AND object_id = OBJECT_ID('[dbo].[DATA_DmgData]'))
begin

CREATE NONCLUSTERED INDEX [IDX_DmgTypeFKeyObjType] ON [dbo].[DATA_DmgData] 
(
	[DmgType] ASC,
	[FKey] ASC,
	[ObjType] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]

end

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fesposito</ADDEDBY>
			<SQLVERSION>1940</SQLVERSION>
			<RMTRACKLINK>58204</RMTRACKLINK>
			<REASON>ADD Ovw6Mode TO DATA_PaymentFlex
UPDATE DATA_PaymentFlex for Integration</REASON>
			<TABLENAMES>DATA_PaymentFlex=PaymentId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Ovw6Mode' AND
                Object_ID  = Object_ID(N'DATA_PaymentFlex'))
BEGIN
  ALTER TABLE DATA_PaymentFlex ADD Ovw6Mode SMALLINT NOT NULL DEFAULT 0
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>UPDATE DATA_PaymentFlex SET Ovw6Mode = 1 
 WHERE NOT EXISTS (SELECT 1 FROM DATA_PaymentFlex2SaleItem
                    WHERE DATA_PaymentFlex2SaleItem.PaymentId = DATA_PaymentFlex.PaymentId)
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fesposito</ADDEDBY>
			<SQLVERSION>1939</SQLVERSION>
			<RMTRACKLINK>60973</RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (select 1 from ARC_Index  
                where ObjectType = 158
                  and DocumentType in (12, 13))                   
BEGIN

update ARC_Index 
   set ObjectType = 158
     , ObjectId = (select MIN(SystemId) from CNF_System where Enabled = 1)
 where ObjectType = 141 
   and DocumentType in (12, 13)

END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fesposito</ADDEDBY>
			<SQLVERSION>1938</SQLVERSION>
			<RMTRACKLINK>58204</RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES>CNF_PaymentMethod=PaymentMethodId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'FeeRefundType' AND
                Object_ID  = Object_ID(N'CNF_PaymentMethod'))
BEGIN
  ALTER TABLE CNF_PaymentMethod ADD FeeRefundType Smallint Default 0 NOT NULL;
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fesposito</ADDEDBY>
			<SQLVERSION>1937</SQLVERSION>
			<RMTRACKLINK>58204</RMTRACKLINK>
			<REASON>ALTER TABLE DATA_PaymentFlex ADD Amount Float Default 0 NOT NULL;
ALTER TABLE DATA_PaymentFlex ADD DownpaymentFeeAmount Float Default 0 NOT NULL;
ALTER TABLE DATA_PaymentFlex ADD DownpaymentRefundableFeeAmount Float Default 0 NOT NULL;
			</REASON>
			<TABLENAMES>DATA_PaymentFlex=PaymentId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Amount' AND
                Object_ID  = Object_ID(N'DATA_PaymentFlex'))
BEGIN
  ALTER TABLE DATA_PaymentFlex ADD Amount Float Default 0 NOT NULL;
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'DownpaymentFeeAmount' AND
                Object_ID  = Object_ID(N'DATA_PaymentFlex'))
BEGIN
  ALTER TABLE DATA_PaymentFlex ADD DownpaymentFeeAmount Float Default 0 NOT NULL;
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'DownpaymentRefundableFeeAmount' AND
                Object_ID  = Object_ID(N'DATA_PaymentFlex'))
BEGIN
  ALTER TABLE DATA_PaymentFlex ADD DownpaymentRefundableFeeAmount Float Default 0 NOT NULL;
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fesposito</ADDEDBY>
			<SQLVERSION>1936</SQLVERSION>
			<RMTRACKLINK>58204</RMTRACKLINK>
			<REASON>Create table [DATA_SaleItem2FlexPayment]</REASON>
			<TABLENAMES>DATA_PaymentFlex2SaleItem=PaymentFlex2SaleItemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'DATA_PaymentFlex2SaleItem'))
BEGIN
Create table [DATA_PaymentFlex2SaleItem]
(
	[PaymentFlex2SaleItemId] Integer Identity(1,1) NOT NULL, UNIQUE ([PaymentFlex2SaleItemId]),
	[PaymentId] Integer NOT NULL,
	[SaleItemId] Integer NOT NULL,
Primary Key ([PaymentFlex2SaleItemId])
) 
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'DATA_PaymentFlex2SaleItem'
	          AND CONSTRAINT_NAME = N'FK_DATA_SaleItem_SaleItemId'
)          
BEGIN
   ALTER TABLE [DATA_PaymentFlex2SaleItem]  
   WITH CHECK ADD  CONSTRAINT [FK_DATA_SaleItem_SaleItemId] FOREIGN KEY([SaleItemId])
   REFERENCES [DATA_SaleItem] ([SaleItemId])
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'DATA_PaymentFlex2SaleItem'
	          AND CONSTRAINT_NAME = N'FK_DATA_PaymentFlex_PaymentId'
)          
BEGIN
   ALTER TABLE [DATA_PaymentFlex2SaleItem]  
   WITH CHECK ADD  CONSTRAINT [FK_DATA_PaymentFlex_PaymentId] FOREIGN KEY([PaymentId])
   REFERENCES [DATA_PaymentFlex] ([PaymentId])
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>kdixon</ADDEDBY>
			<SQLVERSION>1935</SQLVERSION>
			<RMTRACKLINK>61160</RMTRACKLINK>
			<REASON>Create View for Sales Reports</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS(SELECT * FROM dbo.sysobjects WHERE ID = OBJECT_ID(N'[dbo].[VW_Sales]') AND OBJECTPROPERTY(id, N'IsView') = 1)
BEGIN
	DROP VIEW VW_Sales
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE VIEW VW_Sales
AS

select CNF_Site.SiteId,
       CNF_Site.SiteCode,
       CNF_Site.SiteName,
       CNF_User.UserId,
       CNF_User.UserCode, 
       CNF_User.UserName, 
       CNF_Event.EventId,
       CNF_Event.EventCode,
       CNF_Event.EventName, 
       CNF_PriceTable.PriceTableId,
       CNF_PriceTable.Description,
       CNF_PriceList.PriceListId,
       CNF_PriceList.PriceListCode, 
       CNF_PriceList.PriceListName, 
       DATA_SaleItem.ProductType, 
       CNF_MatrixSheet.MatrixSheetId, 
       CNF_MatrixSheet.MatrixSheetName, 
       CNF_MatrixCell.MatrixCellId, 
       CNF_AttributeSet.AttributeCodes,
       DATA_Transaction.TransactionType,
       DATA_SaleItem.Quantity,
       DATA_SaleItem.TotalAmount,
       DATA_SaleItem.PeopleCount,
       TransactionId,
       FTransactionDate,
       DATA_Transaction.Paid,
       DATA_Transaction.Revenue,
       DATA_Transaction.TaxRevenue,
       CNF_OperatingArea.OperatingAreaId,	     
       CNF_OperatingArea.AreaCode, 
       CNF_OperatingArea.OpAreaName,
       CNF_Workstation.WorkstationDescription,
       CNF_Workstation.WorkstationAK,
       CNF_Workstation.WorkstationId,
       AttributeNames,
       UnitPrice,
       DATA_Transaction.TransactionDate,
       DATA_Transaction.Completed,
       DATA_Transaction.Encoded,
       DATA_Transaction.Validated,
       DATA_Transaction.Approved,
       DATA_Transaction.TransactionStatus,
       DATA_Transaction.Tip,
       DATA_Transaction.Change,
       DATA_Transaction.Serial,       
       DATA_Sale.Paid AS DSPaid
FROM DATA_Transaction DATA_Transaction
     INNER JOIN DATA_Sale DATA_Sale WITH(NOLOCK)  ON (DATA_Sale.SaleId = DATA_Transaction.SaleId) 
     INNER JOIN DATA_SaleItem DATA_SaleItem WITH(NOLOCK)  ON (DATA_SaleItem.SaleId = DATA_Sale.SaleId)
     INNER JOIN CNF_MatrixCell CNF_MatrixCell WITH(NOLOCK)  ON (CNF_MatrixCell.MatrixCellId = DATA_SaleItem.MatrixCellId)
     INNER JOIN CNF_MatrixSheet CNF_MatrixSheet WITH(NOLOCK)  ON (CNF_MatrixSheet.MatrixSheetId = CNF_MatrixCell.MatrixSheetId)
     INNER JOIN CNF_PriceTable CNF_PriceTable WITH(NOLOCK) ON (CNF_MatrixCell.PriceTableId = CNF_PriceTable.PriceTableId)
     INNER JOIN CNF_Site CNF_Site WITH(NOLOCK)  ON (CNF_Site.SiteId = DATA_Transaction.SiteId)
     INNER JOIN CNF_AttributeSet CNF_AttributeSet WITH(NOLOCK)  ON (CNF_AttributeSet.AttributeSetId = CNF_MatrixCell.AttributeSetId)
     INNER JOIN CNF_Event CNF_Event WITH(NOLOCK)  ON (CNF_Event.EventId = CNF_MatrixSheet.EventId)
     INNER JOIN CNF_PriceList CNF_PriceList WITH(NOLOCK)  ON (CNF_PriceList.PriceListId = CNF_MatrixCell.PriceListId)
     INNER JOIN CNF_User CNF_User WITH(NOLOCK) ON (CNF_User.UserId = DATA_Transaction.UserId)
     INNER JOIN CNF_OperatingArea CNF_OperatingArea WITH(NOLOCK) ON (CNF_OperatingArea.OperatingAreaId = DATA_Transaction.OperatingAreaId)
     INNER JOIN CNF_Workstation CNF_Workstation WITH(NOLOCK) ON (CNF_Workstation.WorkstationId = DATA_Transaction.WorkstationId)
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>marcoviscusi</ADDEDBY>
			<SQLVERSION>1934</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>[DATA_ACCOUNT]
[0] Update field ExpirationDate</REASON>
			<TABLENAMES>DATA_Account=AccountId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_ACCOUNT set ExpirationDate = (
select max(ActiveTo) from DATA_Ticket
where DATA_Ticket.AccountId=DATA_Account.AccountId and not DATA_Ticket.AccountId is null) ;
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>kdixon</ADDEDBY>
			<SQLVERSION>1933</SQLVERSION>
			<RMTRACKLINK>61160</RMTRACKLINK>
			<REASON>Create View for Sales Reports</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS(SELECT * FROM dbo.sysobjects WHERE ID = OBJECT_ID(N'[dbo].[VW_Sales]') AND OBJECTPROPERTY(id, N'IsView') = 1)
BEGIN
	DROP VIEW VW_Sales
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE VIEW VW_Sales
AS

select CNF_Site.SiteId,
       CNF_Site.SiteCode,
       CNF_Site.SiteName,
       CNF_User.UserId,
       CNF_User.UserCode, 
       CNF_User.UserName, 
       CNF_Event.EventId,
       CNF_Event.EventCode,
       CNF_Event.EventName, 
       CNF_PriceTable.PriceTableId,
       CNF_PriceTable.Description,
       CNF_PriceList.PriceListId,
       CNF_PriceList.PriceListCode, 
       CNF_PriceList.PriceListName, 
       DATA_SaleItem.ProductType, 
       CNF_MatrixSheet.MatrixSheetId, 
       CNF_MatrixSheet.MatrixSheetName, 
       CNF_MatrixCell.MatrixCellId, 
       CNF_AttributeSet.AttributeCodes,
       DATA_Transaction.TransactionType,
       DATA_SaleItem.Quantity,
       DATA_SaleItem.TotalAmount,
       DATA_SaleItem.PeopleCount,
       TransactionId,
       FTransactionDate,
       DATA_Transaction.Paid,
       DATA_Transaction.Revenue,
       DATA_Transaction.TaxRevenue,
       CNF_OperatingArea.OperatingAreaId,	     
       CNF_OperatingArea.AreaCode, 
       CNF_OperatingArea.OpAreaName,
       CNF_Workstation.WorkstationDescription,
       CNF_Workstation.WorkstationAK,
       CNF_Workstation.WorkstationId,
       AttributeNames,
       UnitPrice,
       DATA_Transaction.TransactionDate,
       DATA_Transaction.Completed,
       DATA_Transaction.Encoded,
       DATA_Transaction.Validated,
       DATA_Transaction.Approved,
       DATA_Transaction.TransactionStatus,
       DATA_Transaction.Tip,
       DATA_Transaction.Change,
       DATA_Transaction.Serial
FROM DATA_Transaction DATA_Transaction
     INNER JOIN DATA_Sale DATA_Sale WITH(NOLOCK)  ON (DATA_Sale.SaleId = DATA_Transaction.SaleId) 
     INNER JOIN DATA_SaleItem DATA_SaleItem WITH(NOLOCK)  ON (DATA_SaleItem.SaleId = DATA_Sale.SaleId)
     INNER JOIN CNF_MatrixCell CNF_MatrixCell WITH(NOLOCK)  ON (CNF_MatrixCell.MatrixCellId = DATA_SaleItem.MatrixCellId)
     INNER JOIN CNF_MatrixSheet CNF_MatrixSheet WITH(NOLOCK)  ON (CNF_MatrixSheet.MatrixSheetId = CNF_MatrixCell.MatrixSheetId)
     INNER JOIN CNF_PriceTable CNF_PriceTable WITH(NOLOCK) ON (CNF_MatrixCell.PriceTableId = CNF_PriceTable.PriceTableId)
     INNER JOIN CNF_Site CNF_Site WITH(NOLOCK)  ON (CNF_Site.SiteId = DATA_Transaction.SiteId)
     INNER JOIN CNF_AttributeSet CNF_AttributeSet WITH(NOLOCK)  ON (CNF_AttributeSet.AttributeSetId = CNF_MatrixCell.AttributeSetId)
     INNER JOIN CNF_Event CNF_Event WITH(NOLOCK)  ON (CNF_Event.EventId = CNF_MatrixSheet.EventId)
     INNER JOIN CNF_PriceList CNF_PriceList WITH(NOLOCK)  ON (CNF_PriceList.PriceListId = CNF_MatrixCell.PriceListId)
     INNER JOIN CNF_User CNF_User WITH(NOLOCK) ON (CNF_User.UserId = DATA_Transaction.UserId)
     INNER JOIN CNF_OperatingArea CNF_OperatingArea WITH(NOLOCK) ON (CNF_OperatingArea.OperatingAreaId = DATA_Transaction.OperatingAreaId)
     INNER JOIN CNF_Workstation CNF_Workstation WITH(NOLOCK) ON (CNF_Workstation.WorkstationId = DATA_Transaction.WorkstationId)
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>kdixon</ADDEDBY>
			<SQLVERSION>1932</SQLVERSION>
			<RMTRACKLINK>61160</RMTRACKLINK>
			<REASON>Create View for Sales Reports</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS(SELECT * FROM dbo.sysobjects WHERE ID = OBJECT_ID(N'[dbo].[VW_Sales]') AND OBJECTPROPERTY(id, N'IsView') = 1)
BEGIN
	DROP VIEW VW_Sales
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE VIEW VW_Sales
AS

select CNF_Site.SiteId,
       CNF_Site.SiteCode,
       CNF_Site.SiteName,
       CNF_User.UserId,
       CNF_User.UserCode, 
       CNF_User.UserName, 
       CNF_Event.EventId,
       CNF_Event.EventCode,
       CNF_Event.EventName, 
       CNF_PriceTable.PriceTableId,
       CNF_PriceTable.Description,
       CNF_PriceList.PriceListId,
       CNF_PriceList.PriceListCode, 
       CNF_PriceList.PriceListName, 
       DATA_SaleItem.ProductType, 
       CNF_MatrixSheet.MatrixSheetId, 
       CNF_MatrixSheet.MatrixSheetName, 
       CNF_MatrixCell.MatrixCellId, 
       CNF_AttributeSet.AttributeCodes,
       DATA_Transaction.TransactionType,
       DATA_SaleItem.Quantity,
       DATA_SaleItem.TotalAmount,
       DATA_SaleItem.PeopleCount,
       TransactionId,
       FTransactionDate,
       DATA_Transaction.Paid,
       DATA_Transaction.Revenue,
       DATA_Transaction.TaxRevenue,
       CNF_OperatingArea.OperatingAreaId,	     
       CNF_OperatingArea.AreaCode, 
       CNF_OperatingArea.OpAreaName,
       CNF_Workstation.WorkstationDescription,
       CNF_Workstation.WorkstationAK,
       CNF_Workstation.WorkstationId,
       AttributeNames,
       UnitPrice,
       DATA_Transaction.TransactionDate,
       DATA_Transaction.Completed,
       DATA_Transaction.Encoded,
       DATA_Transaction.Validated,
       DATA_Transaction.Approved,
       DATA_Transaction.TransactionStatus,
       DATA_Transaction.Tip,
       DATA_Transaction.Change,
       DATA_Transaction.Serial
FROM DATA_Transaction DATA_Transaction
     INNER JOIN DATA_Sale DATA_Sale  ON (DATA_Sale.SaleId = DATA_Transaction.SaleId) 
     INNER JOIN DATA_SaleItem DATA_SaleItem  ON (DATA_SaleItem.SaleId = DATA_Sale.SaleId)
     INNER JOIN CNF_MatrixCell CNF_MatrixCell  ON (CNF_MatrixCell.MatrixCellId = DATA_SaleItem.MatrixCellId)
     INNER JOIN CNF_MatrixSheet CNF_MatrixSheet  ON (CNF_MatrixSheet.MatrixSheetId = CNF_MatrixCell.MatrixSheetId)
     INNER JOIN CNF_PriceTable CNF_PriceTable ON (CNF_MatrixCell.PriceTableId = CNF_PriceTable.PriceTableId)
     INNER JOIN CNF_Site CNF_Site  ON (CNF_Site.SiteId = DATA_Transaction.SiteId)
     INNER JOIN CNF_AttributeSet CNF_AttributeSet  ON (CNF_AttributeSet.AttributeSetId = CNF_MatrixCell.AttributeSetId)
     INNER JOIN CNF_Event CNF_Event  ON (CNF_Event.EventId = CNF_MatrixSheet.EventId)
     INNER JOIN CNF_PriceList CNF_PriceList  ON (CNF_PriceList.PriceListId = CNF_MatrixCell.PriceListId)
     INNER JOIN CNF_User CNF_User ON (CNF_User.UserId = DATA_Transaction.UserId)
     INNER JOIN CNF_OperatingArea CNF_OperatingArea ON (CNF_OperatingArea.OperatingAreaId = DATA_Transaction.OperatingAreaId)
     INNER JOIN CNF_Workstation CNF_Workstation ON (CNF_Workstation.WorkstationId = DATA_Transaction.WorkstationId)
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>kdixon</ADDEDBY>
			<SQLVERSION>1931</SQLVERSION>
			<RMTRACKLINK>61158</RMTRACKLINK>
			<REASON>Drop VW_Admissions  &amp; Add View</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS(SELECT * FROM dbo.sysobjects WHERE ID = OBJECT_ID(N'[dbo].[VW_Admissions]') AND OBJECTPROPERTY(id, N'IsView') = 1)
BEGIN
	DROP VIEW VW_Admissions
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE VIEW VW_Admissions
AS   
SELECT  CNF_Site.SiteId, 
        CNF_Site.SiteName, 
        CNF_Location.LocationId,
        CNF_Location.LocationCode, 
	CNF_Location.Name CNF_Name,
	CNF_MatrixSheet.MatrixSheetId ,
	CNF_Event.EventId,
	CNF_Event.EventCode, 
	CNF_Event.EventName, 
	CNF_MatrixCell.MatrixCellId,
        ADM_Gate.GateId ADM_GateId,        
	ADM_Gate.Name Gate_Name,
	ADM_Gate.Description,
        DATA_TicketUsage.FUsageDate,
        DATA_TicketUsage.Gateid,  
	DATA_TicketUsage.UsageDate,         
        DATEPART(HOUR, DATA_TicketUsage.UsageDate) RotHour,
	DATA_TicketUsage.UsageType,
	DATA_TicketUsage.ValidateResult,
	DATA_Ticket.PeopleCount,
	DATA_Ticket.VoidType,
	DATA_Ticket.Price,
	DATA_Ticket.PrintedPrice
FROM  DATA_TicketUsage WITH(NOLOCK) 
      LEFT JOIN  DATA_Ticket WITH(NOLOCK) ON (DATA_Ticket.TicketId = DATA_TicketUsage.TicketId)
      LEFT JOIN  ADM_Gate WITH(NOLOCK) ON (ADM_Gate.GateId = DATA_TicketUsage.GateId)
	  LEFT JOIN  CNF_Location WITH(NOLOCK) ON  (CNF_Location.LocationId = ADM_Gate.LocationId)
	  INNER JOIN CNF_Site WITH(NOLOCK) ON (CNF_Site.SiteId = CNF_Location.SiteId)
	  LEFT JOIN  CNF_MatrixCell CNF_MatrixCell WITH(NOLOCK) ON (CNF_MatrixCell.MatrixCellId = DATA_Ticket.MatrixCellId)
	  INNER JOIN CNF_MatrixSheet CNF_MatrixSheet WITH(NOLOCK) ON (CNF_MatrixSheet.MatrixSheetId = CNF_MatrixCell.MatrixSheetId)
	  INNER JOIN CNF_Event CNF_Event WITH(NOLOCK) ON (CNF_Event.EventId = CNF_MatrixSheet.EventId)
	  INNER JOIN CNF_AttributeSet CNF_AttributeSet WITH(NOLOCK) ON (CNF_AttributeSet.AttributeSetId = CNF_MatrixCell.AttributeSetId)
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fesposito</ADDEDBY>
			<SQLVERSION>1930</SQLVERSION>
			<RMTRACKLINK>58204</RMTRACKLINK>
			<REASON>Added 2 new columns in CNF_FlexContract for menagement of Printing Document Template</REASON>
			<TABLENAMES>CNF_FlexContract=FlexContractId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'PreviewDocTemplateId' AND
                Object_ID  = Object_ID(N'CNF_FlexContract'))                
BEGIN
   ALTER TABLE CNF_FlexContract ADD PreviewDocTemplateId Integer NULL;
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'FinalDocTemplateId' AND
                Object_ID  = Object_ID(N'CNF_FlexContract'))                
BEGIN
   ALTER TABLE CNF_FlexContract ADD FinalDocTemplateId Integer NULL;
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_FlexContract'
	          AND CONSTRAINT_NAME = N'FK_CNF_DocTemplate_PreviewDocTemplateId'
)          
BEGIN
   ALTER TABLE [CNF_FlexContract]  
   WITH CHECK ADD  CONSTRAINT [FK_CNF_DocTemplate_PreviewDocTemplateId] FOREIGN KEY([PreviewDocTemplateId])
   REFERENCES [CNF_DocTemplate] ([DocTemplateId])
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_FlexContract'
	          AND CONSTRAINT_NAME = N'FK_CNF_DocTemplate_FinalDocTemplateId'
)          
BEGIN
   ALTER TABLE [CNF_FlexContract]  
   WITH CHECK ADD  CONSTRAINT [FK_CNF_DocTemplate_FinalDocTemplateId] FOREIGN KEY([FinalDocTemplateId])
   REFERENCES [CNF_DocTemplate] ([DocTemplateId])
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>marcoviscusi</ADDEDBY>
			<SQLVERSION>1929</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>[DATA_ACCOUNT]
[0] Added field ExpirationDate
[1] Update field ExpirationDate
[DATA_TICKET]
[2] Added filed Memebership</REASON>
			<TABLENAMES>DATA_Account=AccountId
DATA_Ticket=TicketId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'ExpirationDate' AND
                Object_ID  = Object_ID(N'DATA_ACCOUNT'))                
BEGIN
ALTER TABLE DATA_ACCOUNT ADD ExpirationDate datetime default('01/01/1900');
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_ACCOUNT set ExpirationDate = isnull((
select max(ActiveTo) from DATA_Ticket
where not (ActiveTo is null) and DATA_Ticket.AccountId=DATA_Account.AccountId), '01/01/1900');

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Membership' AND
                Object_ID  = Object_ID(N'DATA_Ticket'))
BEGIN
  ALTER TABLE DATA_Ticket ADD Membership smallint default (0);
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1928</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>[CNF_Promotion]
[0] add field CalculatedActiveFrom
[1] add field CalculatedActiveto
[2] update CalculatedActiveFrom with old value
[3] update CalculatedActiveto with old value</REASON>
			<TABLENAMES>CNF_Promotion=PromotionId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Promotion
  add CalculatedActiveFrom dateTime Null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Promotion
  add CalculatedActiveTo dateTime Null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_promotion
  set CalculatedActiveFrom =  
  (select 
  min(PV.FromDate) as FromDate
from 
  CNF_PromotionValidity as PV    
where
   PV.PromotionId = CNF_promotion.PromotionId
group by
  PV.PromotionId    
  )
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> update CNF_promotion
  set CalculatedActiveTo =  
  (select 
  min(PV.ToDate) as FromDate
from 
  CNF_PromotionValidity as PV    
where
   PV.PromotionId = CNF_promotion.PromotionId
group by
  PV.PromotionId    
  )
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Damiani Franco</ADDEDBY>
			<SQLVERSION>1927</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>Revision of previous patch 1924 

CNF_DocTemplate
[0] add sen dcalendar flag </REASON>
			<TABLENAMES>CNF_DocTemplate=DocTemplateId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'SendCalendar' AND
                Object_ID  = Object_ID(N'CNF_DocTemplate'))                
BEGIN
  alter table CNF_DocTemplate
    add SendCalendar Smallint NULL  
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fesposito</ADDEDBY>
			<SQLVERSION>1926</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>Adding a new table CNF_MatrixCell2FlexContract</REASON>
			<TABLENAMES>CNF_MatrixCell2FlexContract=MatrixCell2FlexContractId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'CNF_MatrixCell2FlexContract'))

BEGIN
Create table [CNF_MatrixCell2FlexContract]
(
	[MatrixCell2FlexContractId] Integer Identity(1,1) NOT NULL,
	[MatrixCellId] Integer NOT NULL,
	[FlexContractId] Integer NOT NULL,
Primary Key ([MatrixCell2FlexContractId])
) 
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.indexes 
               WHERE name = N'Idx_MatrixCellFlexContract' 
	       AND object_id = OBJECT_ID(N'CNF_MatrixCell2FlexContract')
	      )
BEGIN    
   Create UNIQUE Index [Idx_MatrixCellFlexContract] ON [CNF_MatrixCell2FlexContract] ([MatrixCellId] ,[FlexContractId] )
END 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_MatrixCell2FlexContract'
	          AND CONSTRAINT_NAME = N'FK_CNF_MatrixCell_MatrixCellId'
)          
BEGIN
   ALTER TABLE [CNF_MatrixCell2FlexContract]  
   WITH CHECK ADD  CONSTRAINT [FK_CNF_MatrixCell_MatrixCellId] FOREIGN KEY([MatrixCellId])
   REFERENCES [CNF_MatrixCell] ([MatrixCellId])
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
	        WHERE TABLE_NAME = N'CNF_MatrixCell2FlexContract'
	          AND CONSTRAINT_NAME = N'FK_CNF_MatrixCell_FlexContractId'
)          
BEGIN
   ALTER TABLE [CNF_MatrixCell2FlexContract]  
   WITH CHECK ADD  CONSTRAINT [FK_CNF_MatrixCell_FlexContractId] FOREIGN KEY([FlexContractId])
   REFERENCES [CNF_FlexContract] ([FlexContractId])
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>adavanzo</ADDEDBY>
			<SQLVERSION>1925</SQLVERSION>
			<RMTRACKLINK>60058</RMTRACKLINK>
			<REASON>0) Added a new column BoxType on DATA_BOX
1) Added a new index on BoxId
2) Added a new index on WorkstationId-UserId</REASON>
			<TABLENAMES>DATA_Box=BoxId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'BoxType' AND
                Object_ID  = Object_ID(N'DATA_Box'))
BEGIN
alter table DATA_Box
  add BoxType Smallint Default 0 NOT NULL
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.indexes 
               WHERE name = N'IDX_DataBox_BoxId' 
	       AND object_id = OBJECT_ID(N'DATA_BOX')
	       AND is_unique = 1)
BEGIN                             
  Create UNIQUE Index [IDX_DataBox_BoxId] ON [DATA_Box] ([BoxId] )  
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.indexes 
               WHERE name = N'IDX_DataBox_UserWks' 
	       AND object_id = OBJECT_ID(N'DATA_BOX')
	       AND is_unique = 0)
BEGIN 
  Create Index [IDX_DataBox_UserWks] ON [DATA_Box] ([WorkstationId] ,[UserId] )
END 
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1924</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>CNF_DocTemplate
[0] add sen dcalendar flag </REASON>
			<TABLENAMES>CNF_DocTemplate=DocTemplateId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_DocTemplate
 add SendCalendar Smallint NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FCARAMELLA</ADDEDBY>
			<SQLVERSION>1923</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES>CNF_MatrixCell=MatrixCellId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'PdfTemplateId' AND
                Object_ID  = Object_ID(N'CNF_MatrixCell'))
BEGIN
alter table CNF_MatrixCell
  add PdfTemplateId integer null
END

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'PdfTemplateId' AND
                Object_ID  = Object_ID(N'CNF_MatrixCell'))
BEGIN
  ALTER TABLE CNF_MatrixCell
  WITH CHECK ADD  CONSTRAINT [FK_CNF_CNF_MatrixCell_PdfTemplateId] FOREIGN KEY([PdfTemplateId])
  REFERENCES [CNF_MatrixCell] ([DocTemplateId])  
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FedericoCaramella</ADDEDBY>
			<SQLVERSION>1922</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.3.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************
			</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FedericoCaramella</ADDEDBY>
			<SQLVERSION>1921</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.3.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************
			</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FedericoCaramella</ADDEDBY>
			<SQLVERSION>1920</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.3.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************
			</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FedericoCaramella</ADDEDBY>
			<SQLVERSION>1919</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.3.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************
			</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FedericoCaramella</ADDEDBY>
			<SQLVERSION>1918</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.3.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************
			</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FedericoCaramella</ADDEDBY>
			<SQLVERSION>1917</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.3.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************
			</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FedericoCaramella</ADDEDBY>
			<SQLVERSION>1916</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.3.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************
			</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FedericoCaramella</ADDEDBY>
			<SQLVERSION>1915</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.3.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************
			</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FedericoCaramella</ADDEDBY>
			<SQLVERSION>1914</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.3.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************
			</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FedericoCaramella</ADDEDBY>
			<SQLVERSION>1913</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.3.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************
			</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FedericoCaramella</ADDEDBY>
			<SQLVERSION>1912</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.3.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************
			</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FedericoCaramella</ADDEDBY>
			<SQLVERSION>1911</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.3.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************
			</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FedericoCaramella</ADDEDBY>
			<SQLVERSION>1910</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.3.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************
			</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FedericoCaramella</ADDEDBY>
			<SQLVERSION>1909</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.3.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************
			</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FedericoCaramella</ADDEDBY>
			<SQLVERSION>1908</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.3.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************
			</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FedericoCaramella</ADDEDBY>
			<SQLVERSION>1907</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.3.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************
			</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FedericoCaramella</ADDEDBY>
			<SQLVERSION>1906</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.3.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************
			</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FedericoCaramella</ADDEDBY>
			<SQLVERSION>1905</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.3.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************
			</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FedericoCaramella</ADDEDBY>
			<SQLVERSION>1904</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.4.3.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************
			</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FedericoCaramella</ADDEDBY>
			<SQLVERSION>1903</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>0 - CNF_PaymentMethod add SurveyId column
1 - Add FK</REASON>
			<TABLENAMES>CNF_PaymentMethod=PaymentMethodId
CNF_Subscription=SubscriptionId
CNF_Subscription2Performance=Subscription2PerformanceId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'SurveyId' AND
                Object_ID  = Object_ID(N'CNF_PaymentMethod'))
BEGIN
alter table CNF_PaymentMethod
  add SurveyId integer null
END

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'SurveyId' AND
                Object_ID  = Object_ID(N'CNF_PaymentMethod'))
BEGIN
  ALTER TABLE CNF_PaymentMethod
  WITH CHECK ADD  CONSTRAINT [FK_CNF_PaymentMethod_SurveyId] FOREIGN KEY([SurveyId])
  REFERENCES [CNF_Survey] ([SurveyId])  
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1902</SQLVERSION>
			<RMTRACKLINK>59127</RMTRACKLINK>
			<REASON>CNF_ExternalMediaType
[0] add field AllowOnTicketOnly smallint null
[1] update existng value
[2] set AllowOnTicketOnly as  not null</REASON>
			<TABLENAMES>CNF_ExternalMediaType=ExternalMediaTypeId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_ExternalMediaType
  add AllowOnTicketOnly smallint null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> update CNF_ExternalMediaType 
 set AllowOnTicketOnly = 0
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_ExternalMediaType
  alter column AllowOnTicketOnly smallint not null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>pdalben</ADDEDBY>
			<SQLVERSION>1901</SQLVERSION>
			<RMTRACKLINK>60075</RMTRACKLINK>
			<REASON>Recreated index IDX_BIOM_TICKETID without unique property
0 - drop index
1- create index</REASON>
			<TABLENAMES>DATA_Biometric=BiometricId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.indexes 
           WHERE name = N'IDX_BIOM_TICKETID' 
	   AND object_id = OBJECT_ID(N'DATA_BIOMETRIC')
	   AND is_unique = 1)
BEGIN
  DROP INDEX DATA_BIOMETRIC.IDX_BIOM_TICKETID
END

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.indexes 
               WHERE name = N'IDX_BIOM_TICKETID' 
	       AND object_id = OBJECT_ID(N'DATA_BIOMETRIC'))
BEGIN
  CREATE INDEX IDX_BIOM_TICKETID ON DATA_Biometric (TicketId) 
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>marcoviscusi</ADDEDBY>
			<SQLVERSION>1900</SQLVERSION>
			<RMTRACKLINK>60305</RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES>DATA_SaleItem2CostCenter=SaleItem2CostCenterId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'CostCenterAK' AND
                Object_ID  = Object_ID(N'DATA_SaleItem2CostCenter'))
BEGIN
  ALTER TABLE DATA_SaleItem2CostCenter ADD CostCenterAK varchar(32) NOT NULL DEFAULT ''
END

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'CostCenterCode' AND
                Object_ID  = Object_ID(N'DATA_SaleItem2CostCenter'))
BEGIN
  ALTER TABLE DATA_SaleItem2CostCenter ADD CostCenterCode varchar(10) NOT NULL DEFAULT ''
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'CostCenterDescription' AND
                Object_ID  = Object_ID(N'DATA_SaleItem2CostCenter'))
BEGIN
  ALTER TABLE DATA_SaleItem2CostCenter ADD CostCenterDescription nvarchar(100) NULL DEFAULT ''
END

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Quantity' AND
                Object_ID  = Object_ID(N'DATA_SaleItem2CostCenter'))
BEGIN
  ALTER TABLE DATA_SaleItem2CostCenter ADD Quantity Integer default 0
END

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'UnitAmount' AND
                Object_ID  = Object_ID(N'DATA_SaleItem2CostCenter'))
BEGIN
  ALTER TABLE DATA_SaleItem2CostCenter ADD UnitAmount float NOT NULL default 0
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>1899</SQLVERSION>
			<RMTRACKLINK>60320</RMTRACKLINK>
			<REASON>New tables for Statistics:

[0] - STAT_PRODUCT:
[1] - STAT_COSTCENTER:
[2] - STAT_STATISTICALGROUP:
[3] - STAT_CREDITCARD:
[4] - STAT_PAYMENT:
[5] - STAT_ADMISSION:
--------------------
[6] - Foreign keys

			</REASON>
			<TABLENAMES>STAT_Product=StatProductId
STAT_CostCenter=StatCostCenterId
STAT_StatisticalGroup=StatStatisticalGroupId
STAT_CreditCard=StatCreditCardId
STAT_Payment=StatPaymentId
STAT_Admission=StatAdmissionId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'STAT_Product'))

BEGIN
Create table [STAT_Product]
(
	[StatProductId] Integer Identity(1,1) NOT NULL,
	[SystemId] Integer NULL,
	[SiteId] Integer NULL,
	[OperatingAreaId] Integer NULL,
	[WorkstationId] Integer NULL,
	[UserId] Integer NULL,
	[MatrixCellId] Integer NOT NULL,
	[FDate] Datetime NOT NULL,
	[Period] Smallint NOT NULL,
	[EncodedQty] Integer NULL,
	[EncodedAmount] Money NULL,
	[VoidedQty] Integer NULL,
	[VoidedAmount] Money NULL,
	[UpgradedFromQty] Integer NULL,
	[UpgradedFromAmount] Money NULL,
	[UpgradedToQty] Integer NULL,
	[UpgradedToAmount] Money NULL,
	[TotalRefundedQty] Integer NULL,
	[TotalRefundedAmount] Money NULL,
	[ReissuedQty] Integer NULL,
	[ReissuedAmount] Money NULL,
	[ReprintedQty] Integer NULL,
	[ReprintedAmount] Money NULL,
	[ExternalQty] Integer NULL,
	[ExternalAmount] Money NULL,
	[TaxAmount] Money NULL,
Primary Key ([StatProductId])
) 
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>
IF NOT (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'STAT_CostCenter'))

BEGIN

Create table [STAT_CostCenter]
(
	[StatCostCenterId] Integer Identity(1,1) NOT NULL,
	[SystemId] Integer NULL,
	[SiteId] Integer NULL,
	[OperatingAreaId] Integer NULL,
	[WorkstationId] Integer NULL,
	[UserId] Integer NULL,
	[CostCenterId] Integer NOT NULL,
	[FDate] Datetime NOT NULL,
	[Period] Smallint NOT NULL,
	[Quantity] Integer NULL,
	[Amount] Money NULL,
Primary Key ([StatCostCenterId])
) 
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'STAT_StatisticalGroup'))

BEGIN

Create table [STAT_StatisticalGroup]
(
	[StatStatisticalGroupId] Integer Identity(1,1) NOT NULL,
	[SystemId] Integer NULL,
	[SiteId] Integer NULL,
	[OperatingAreaId] Integer NULL,
	[WorkstationId] Integer NULL,
	[UserId] Integer NULL,
	[StatisticalGroupId] Integer NOT NULL,
	[FDate] Datetime NOT NULL,
	[Period] Smallint NOT NULL,
	[Quantity] Integer NULL,
	[Amount] Money NULL,
Primary Key ([StatStatisticalGroupId])
) 
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>      IF NOT (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'STAT_CreditCard'))

BEGIN


Create table [STAT_CreditCard]
(
	[StatCreditCardId] Integer Identity(1,1) NOT NULL,
	[SystemId] Integer NOT NULL,
	[SiteId] Integer NULL,
	[OperatingAreaId] Integer NULL,
	[WorkstationId] Integer NULL,
	[UserId] Integer NULL,
	[CurrencyId] Integer NOT NULL,
	[PaymentCardId] Integer NOT NULL,
	[FDate] Datetime NOT NULL,
	[Period] Smallint NOT NULL,
	[Amount] Money NULL,
Primary Key ([StatCreditCardId])
) 
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>       IF NOT (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'STAT_Payment'))

BEGIN

Create table [STAT_Payment]
(
	[StatPaymentId] Integer Identity(1,1) NOT NULL,
	[SystemId] Integer NULL,
	[SiteId] Integer NULL,
	[OperatingAreaId] Integer NULL,
	[WorkstationId] Integer NULL,
	[UserId] Integer NULL,
	[CurrencyId] Integer NOT NULL,
	[PaymentMethodId] Integer NOT NULL,
	[FDate] Datetime NOT NULL,
	[Period] Smallint NOT NULL,
	[Amount] Money NULL,
Primary Key ([StatPaymentId])
) 
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>       IF NOT (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'STAT_Admission'))

BEGIN

Create table [STAT_Admission]
(
	[StatAdmissionId] Integer Identity(1,1) NOT NULL,
	[SystemId] Integer NULL,
	[SiteId] Integer NULL,
	[OperatingAreaId] Integer NULL,
	[GateId] Integer NULL,
	[WorkstationId] Integer NULL,
	[MatrixCellId] Integer NOT NULL,
	[FDate] Datetime NOT NULL,
	[Period] Smallint NOT NULL,
	[Entry] Integer NULL,
	[Reentry] Integer NULL,
	[ExitNumber] Integer NULL,
	[Transit] Integer NULL,
Primary Key ([StatAdmissionId])
) 
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>

ALTER TABLE [STAT_Product]  
WITH CHECK ADD  CONSTRAINT [FK_STAT_Product_SystemId] FOREIGN KEY([SystemId])
REFERENCES [CNF_System] ([SystemId]);

ALTER TABLE [STAT_Product]  
WITH CHECK ADD  CONSTRAINT [FK_STAT_Product_SiteId] FOREIGN KEY([SiteId])
REFERENCES [CNF_Site] ([SiteId]);

ALTER TABLE [STAT_Product]  
WITH CHECK ADD  CONSTRAINT [FK_STAT_Product_OperatingAreaId] FOREIGN KEY([OperatingAreaId])
REFERENCES [CNF_OperatingArea] ([OperatingAreaId]);

ALTER TABLE [STAT_Product]  
WITH CHECK ADD  CONSTRAINT [FK_STAT_Product_WorkstationId] FOREIGN KEY([WorkstationId])
REFERENCES [CNF_Workstation] ([WorkstationId]);

ALTER TABLE [STAT_Product]  
WITH CHECK ADD  CONSTRAINT [FK_STAT_Product_UserId] FOREIGN KEY([UserId])
REFERENCES [CNF_User] ([UserId]);

ALTER TABLE [STAT_Product]  
WITH CHECK ADD  CONSTRAINT [FK_STAT_Product_MatrixCellId] FOREIGN KEY([MatrixCellId])
REFERENCES [CNF_MatrixCell] ([MatrixCellId]);





ALTER TABLE [STAT_CostCenter]            
WITH CHECK ADD  CONSTRAINT [FK_STAT_CostCenter_SystemId] FOREIGN KEY([SystemId])
REFERENCES [CNF_System] ([SystemId]);

ALTER TABLE [STAT_CostCenter]  
WITH CHECK ADD  CONSTRAINT [FK_STAT_CostCenter_SiteId] FOREIGN KEY([SiteId])
REFERENCES [CNF_Site] ([SiteId]);

ALTER TABLE [STAT_CostCenter]  
WITH CHECK ADD  CONSTRAINT [FK_STAT_CostCenter_OperatingAreaId] FOREIGN KEY([OperatingAreaId])
REFERENCES [CNF_OperatingArea] ([OperatingAreaId]);

ALTER TABLE [STAT_CostCenter]  
WITH CHECK ADD  CONSTRAINT [FK_STAT_CostCenter_WorkstationId] FOREIGN KEY([WorkstationId])
REFERENCES [CNF_Workstation] ([WorkstationId]);

ALTER TABLE [STAT_CostCenter]  
WITH CHECK ADD  CONSTRAINT [FK_STAT_CostCenter_UserId] FOREIGN KEY([UserId])
REFERENCES [CNF_User] ([UserId]);

ALTER TABLE [STAT_CostCenter]  
WITH CHECK ADD  CONSTRAINT [FK_STAT_CostCenter_CostCenterId] FOREIGN KEY([CostCenterId])
REFERENCES [CNF_CostCenter] ([CostCenterId]);



ALTER TABLE [STAT_StatisticalGroup]            
WITH CHECK ADD  CONSTRAINT [FK_STAT_StatisticalGroup_SystemId] FOREIGN KEY([SystemId])
REFERENCES [CNF_System] ([SystemId]);

ALTER TABLE [STAT_StatisticalGroup]  
WITH CHECK ADD  CONSTRAINT [FK_STAT_StatisticalGroup_SiteId] FOREIGN KEY([SiteId])
REFERENCES [CNF_Site] ([SiteId]);

ALTER TABLE [STAT_StatisticalGroup]  
WITH CHECK ADD  CONSTRAINT [FK_STAT_StatisticalGroup_OperatingAreaId] FOREIGN KEY([OperatingAreaId])
REFERENCES [CNF_OperatingArea] ([OperatingAreaId]);

ALTER TABLE [STAT_StatisticalGroup]  
WITH CHECK ADD  CONSTRAINT [FK_STAT_StatisticalGroup_WorkstationId] FOREIGN KEY([WorkstationId])
REFERENCES [CNF_Workstation] ([WorkstationId]);

ALTER TABLE [STAT_StatisticalGroup]  
WITH CHECK ADD  CONSTRAINT [FK_STAT_StatisticalGroup_UserId] FOREIGN KEY([UserId])
REFERENCES [CNF_User] ([UserId]);

ALTER TABLE [STAT_StatisticalGroup]  
WITH CHECK ADD  CONSTRAINT [FK_STAT_StatisticalGroup_StatisticalGroupId] FOREIGN KEY([StatisticalGroupId])
REFERENCES [CNF_StatisticalGroup] ([StatisticalGroupId]);



ALTER TABLE [STAT_CreditCard]            
WITH CHECK ADD  CONSTRAINT [FK_STAT_CreditCard_SystemId] FOREIGN KEY([SystemId])
REFERENCES [CNF_System] ([SystemId]);

ALTER TABLE [STAT_CreditCard]  
WITH CHECK ADD  CONSTRAINT [FK_STAT_CreditCard_SiteId] FOREIGN KEY([SiteId])
REFERENCES [CNF_Site] ([SiteId]);

ALTER TABLE [STAT_CreditCard]  
WITH CHECK ADD  CONSTRAINT [FK_STAT_CreditCard_OperatingAreaId] FOREIGN KEY([OperatingAreaId])
REFERENCES [CNF_OperatingArea] ([OperatingAreaId]);

ALTER TABLE [STAT_CreditCard]  
WITH CHECK ADD  CONSTRAINT [FK_STAT_CreditCard_WorkstationId] FOREIGN KEY([WorkstationId])
REFERENCES [CNF_Workstation] ([WorkstationId]);

ALTER TABLE [STAT_CreditCard]  
WITH CHECK ADD  CONSTRAINT [FK_STAT_CreditCard_UserId] FOREIGN KEY([UserId])
REFERENCES [CNF_User] ([UserId]);

ALTER TABLE [STAT_CreditCard]  
WITH CHECK ADD  CONSTRAINT [FK_STAT_CreditCard_CurrencyId] FOREIGN KEY([CurrencyId])
REFERENCES [CNF_Currency] ([CurrencyId]);

ALTER TABLE [STAT_CreditCard]  
WITH CHECK ADD  CONSTRAINT [FK_STAT_CreditCard_PaymentCardId] FOREIGN KEY([PaymentCardId])
REFERENCES [CNF_PaymentCard] ([PaymentCardId])




ALTER TABLE [STAT_Payment]            
WITH CHECK ADD  CONSTRAINT [FK_STAT_Payment_SystemId] FOREIGN KEY([SystemId])
REFERENCES [CNF_System] ([SystemId]);

ALTER TABLE [STAT_Payment]  
WITH CHECK ADD  CONSTRAINT [FK_STAT_Payment_SiteId] FOREIGN KEY([SiteId])
REFERENCES [CNF_Site] ([SiteId]);

ALTER TABLE [STAT_Payment]  
WITH CHECK ADD  CONSTRAINT [FK_STAT_Payment_OperatingAreaId] FOREIGN KEY([OperatingAreaId])
REFERENCES [CNF_OperatingArea] ([OperatingAreaId]);

ALTER TABLE [STAT_Payment]  
WITH CHECK ADD  CONSTRAINT [FK_STAT_Payment_WorkstationId] FOREIGN KEY([WorkstationId])
REFERENCES [CNF_Workstation] ([WorkstationId]);

ALTER TABLE [STAT_Payment]  
WITH CHECK ADD  CONSTRAINT [FK_STAT_Payment_UserId] FOREIGN KEY([UserId])
REFERENCES [CNF_User] ([UserId]);

ALTER TABLE [STAT_Payment]  
WITH CHECK ADD  CONSTRAINT [FK_STAT_Payment_CurrencyId] FOREIGN KEY([CurrencyId])
REFERENCES [CNF_Currency] ([CurrencyId]);

ALTER TABLE [STAT_Payment]  
WITH CHECK ADD  CONSTRAINT [FK_STAT_Payment_PaymentMethodId] FOREIGN KEY([PaymentMethodId])
REFERENCES [CNF_PaymentMethod] ([PaymentMethodId]);




ALTER TABLE [STAT_Admission]            
WITH CHECK ADD  CONSTRAINT [FK_STAT_Admission_SystemId] FOREIGN KEY([SystemId])
REFERENCES [CNF_System] ([SystemId]);

ALTER TABLE [STAT_Admission]  
WITH CHECK ADD  CONSTRAINT [FK_STAT_Admission_SiteId] FOREIGN KEY([SiteId])
REFERENCES [CNF_Site] ([SiteId]);

ALTER TABLE [STAT_Admission]  
WITH CHECK ADD  CONSTRAINT [FK_STAT_Admission_OperatingAreaId] FOREIGN KEY([OperatingAreaId])
REFERENCES [CNF_OperatingArea] ([OperatingAreaId]);

ALTER TABLE [STAT_Admission]  
WITH CHECK ADD  CONSTRAINT [FK_STAT_Admission_GateId] FOREIGN KEY([GateId])
REFERENCES [ADM_Gate] ([GateId]);

ALTER TABLE [STAT_Admission]  
WITH CHECK ADD  CONSTRAINT [FK_STAT_Admission_WorkstationId] FOREIGN KEY([WorkstationId])
REFERENCES [CNF_Workstation] ([WorkstationId]);

ALTER TABLE [STAT_Admission]  
WITH CHECK ADD  CONSTRAINT [FK_STAT_Admission_MatrixCellId] FOREIGN KEY([MatrixCellId])
REFERENCES [CNF_MatrixCell] ([MatrixCellId]);










				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>pdalben</ADDEDBY>
			<SQLVERSION>1898</SQLVERSION>
			<RMTRACKLINK>60075</RMTRACKLINK>
			<REASON>Added field VoidType to DATA_Biometric</REASON>
			<TABLENAMES>DATA_Biometric=BiometricId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'VoidType' AND
                Object_ID  = Object_ID(N'DATA_Biometric'))
BEGIN
  ALTER TABLE DATA_Biometric ADD VoidType smallint DEFAULT 0 NOT NULL
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>pdalben</ADDEDBY>
			<SQLVERSION>1897</SQLVERSION>
			<RMTRACKLINK>60076</RMTRACKLINK>
			<REASON>Added field BiometricLevel to ADM_AccessPoint
[0] add field as null
[1] set old value
[2] set filed as not null</REASON>
			<TABLENAMES>ADM_AccessPoint=WorkstationId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'BiometricLevel' AND
                Object_ID  = Object_ID(N'ADM_AccessPoint'))
BEGIN
  ALTER TABLE ADM_AccessPoint ADD BiometricLevel smallint NULL DEFAULT 0
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>
  UPDATE ADM_AccessPoint SET BiometricLevel = 0
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>
  ALTER TABLE ADM_AccessPoint ALTER COLUMN BiometricLevel smallint NOT NULL


				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>pdalben</ADDEDBY>
			<SQLVERSION>1896</SQLVERSION>
			<RMTRACKLINK>58172</RMTRACKLINK>
			<REASON>Added field PermanentOverride to DATA_Biometric</REASON>
			<TABLENAMES>DATA_Biometric=BiometricId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'PermanentOverride' AND
                Object_ID  = Object_ID(N'DATA_Biometric'))
BEGIN
  ALTER TABLE DATA_Biometric ADD PermanentOverride smallint DEFAULT 0 NOT NULL
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fesposito</ADDEDBY>
			<SQLVERSION>1895</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>Adding columns to DATA_PaymentFlex:
- DownpaymentAmount Float Default 0 NOT NULL
- FeeAmount Float Default 0 NOT NULL
- RefundableFeeAmount Float Default 0 NOT NULL
New model of CNF_FlexContractFee
Adding columns to DATA_PaymentPlan:
- FeeAmount Float NULL
- RefundableFeeAmount Float NULL 

**This patch contains also updates for patch 1893 </REASON>
			<TABLENAMES>CNF_FlexContractFee=FlexContractFeeId
DATA_PaymentFlex=PaymentId
DATA_PaymentPlan=PaymentPlanId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'FeeAmount' AND
                Object_ID  = Object_ID(N'DATA_PaymentFlex'))
BEGIN
  ALTER TABLE DATA_PaymentFlex 
    ADD DownpaymentAmount Float Default 0 NOT NULL,
	FeeAmount Float Default 0 NOT NULL,
	RefundableFeeAmount Float Default 0 NOT NULL
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF OBJECT_ID(N'CNF_FlexContractFee', 'U') IS NOT NULL
BEGIN
  DROP TABLE CNF_FlexContractFee;
END 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'CNF_FlexContractFee'))

BEGIN

Create table [CNF_FlexContractFee]
(
	[FlexContractFeeId] Integer Identity(1,1) NOT NULL,
	[FlexContractId] Integer NOT NULL,
	[PromotionId] Integer NOT NULL,
	[IncludedInDp] Smallint NOT NULL,
	[Refundable] Smallint Default 0 NOT NULL,
Primary Key ([FlexContractFeeId])
)

END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'FeeAmount' AND
                Object_ID  = Object_ID(N'DATA_PaymentPlan'))
BEGIN
  ALTER TABLE DATA_PaymentPlan 
    ADD FeeAmount Float NULL    
      , RefundableFeeAmount Float NULL 
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>pdalben</ADDEDBY>
			<SQLVERSION>1894</SQLVERSION>
			<RMTRACKLINK>60072</RMTRACKLINK>
			<REASON>Added field LastCompareDate in DATA_Biometric</REASON>
			<TABLENAMES>DATA_Biometric=BiometricId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'LastCompareDate' AND
                Object_ID  = Object_ID(N'DATA_Biometric'))
BEGIN
  ALTER TABLE DATA_Biometric ADD LastCompareDate datetime NULL
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fesposito</ADDEDBY>
			<SQLVERSION>1893</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>db model updated but the patch is missing, added in 1895</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fesposito</ADDEDBY>
			<SQLVERSION>1892</SQLVERSION>
			<RMTRACKLINK>59928</RMTRACKLINK>
			<REASON>Fixing script for installment before 7.4.1.13</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_PaymentPlan set AppliedAmount = 0
 where PaymentActivityType = 1
   and FlexPaymentStatus = 4
   and AppliedAmount = Amount
   and not exists (select * from DATA_PaymentPlan2Transaction PP2T 
                    where PP2T.PaymentPlanId = DATA_PaymentPlan.PaymentPlanId 
                      and PP2T.FlexPaymentStatus is not null)
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Damiani Franco</ADDEDBY>
			<SQLVERSION>1891</SQLVERSION>
			<RMTRACKLINK>56580</RMTRACKLINK>
			<REASON>Add  column Enablee to CNF_StatisticalGroup
[0] - Add Column
[1] - update previous recs
[2] - Set column to NOT NULL
[3] - Set column default to 1</REASON>
			<TABLENAMES>CNF_StatisticalGroup=StatisticalGroupId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Enabled' AND
                Object_ID  = Object_ID(N'CNF_StatisticalGroup'))
BEGIN
  ALTER TABLE CNF_StatisticalGroup ADD Enabled smallint NULL
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>UPDATE CNF_StatisticalGroup 
SET ENABLED = 1
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE CNF_StatisticalGroup
   ALTER COLUMN Enabled smallint NOT NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS ( select * from sys.objects WHERE type = 'D' and name = 'CNF_STAT_GROUP_ENABLED_DEF_VALUE') 
BEGIN
  ALTER TABLE CNF_StatisticalGroup ADD CONSTRAINT CNF_STAT_GROUP_ENABLED_DEF_VALUE DEFAULT 1 FOR Enabled
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Damiani Franco</ADDEDBY>
			<SQLVERSION>1890</SQLVERSION>
			<RMTRACKLINK>56580</RMTRACKLINK>
			<REASON>Add  column Enablee to CNF_PerformanceCategory
[0] - Add Column
[1] - update previous recs
[2] - Set column to NOT NULL
[3] - Set column default to 1</REASON>
			<TABLENAMES>CNF_PerformanceCategory=PerformanceCategoryId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Enabled' AND
                Object_ID  = Object_ID(N'CNF_PerformanceCategory'))
BEGIN
  ALTER TABLE CNF_PerformanceCategory ADD Enabled smallint NULL
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>UPDATE CNF_PerformanceCategory 
SET ENABLED = 1
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE CNF_PerformanceCategory
   ALTER COLUMN Enabled smallint NOT NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS ( select * from sys.objects WHERE type = 'D' and name = 'CNF_PERF_CAT_ENABLED_DEF_VALUE') 
BEGIN
  ALTER TABLE CNF_PerformanceCategory ADD CONSTRAINT CNF_PERF_CAT_ENABLED_DEF_VALUE DEFAULT 1 FOR Enabled
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>dpiazzolla</ADDEDBY>
			<SQLVERSION>1889</SQLVERSION>
			<RMTRACKLINK>59730 </RMTRACKLINK>
			<REASON>Delete all translations where CNF_MultiLanguage.FormName = 'fResource'   and ComponentName = 'tgbResource'</REASON>
			<TABLENAMES>CNF_MultiLanguage=MultiLanguageId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>  delete FROM CNF_MultiLanguage
  where 
  FormName = 'fResource'     
  and ComponentName = 'tgbResource'
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1888</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>CNF_DataMask
[0] change len from 40 to 250 for RuleId</REASON>
			<TABLENAMES>CNF_DataMask=DataMaskId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_DataMask
  alter column RuleId Varchar(250) NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>dpiazzolla</ADDEDBY>
			<SQLVERSION>1887</SQLVERSION>
			<RMTRACKLINK>59264</RMTRACKLINK>
			<REASON>[1]
renamed  
NF_AttributeTemplate.SortOrder in CNF_AttributeTemplate.Weight

[2]
renamed  and set not null 
NF_Attribute.SortOrder in CNF_Attribute.Weigh</REASON>
			<TABLENAMES>CNF_AttributeTemplate=AttributeTemplateId
CNF_Attribute=AttributeId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>  EXEC sp_rename 'CNF_Attribute.SortOrder', 'Weight', 'column';
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>  EXEC sp_rename 'CNF_AttributeTemplate.SortOrder', 'Weight', 'column';
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>dpiazzolla</ADDEDBY>
			<SQLVERSION>1886</SQLVERSION>
			<RMTRACKLINK>59264</RMTRACKLINK>
			<REASON>[1]
renamed  and set not null 
CNF_AttributeTemplate.Weight in NF_AttributeTemplate.SortOrder 

[2]
renamed  and set not null 
CNF_Attribute.Weight in NF_Attribute.SortOrder
			</REASON>
			<TABLENAMES>CNF_AttributeTemplate=AttributeTemplateId
CNF_Attribute=AttributeId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>With Attr As
(
SELECT Code,Weight,AttributeId,
ROW_NUMBER() OVER (ORDER BY Code ASC) AS RowNumber
FROM CNF_Attribute
where Weight is null
)
UPDATE Attr SET Weight=RowNumber;

ALTER TABLE CNF_Attribute
  ALTER COLUMN Weight int NOT NULL;

EXEC sp_rename 'CNF_Attribute.Weight', 'SortOrder', 'column';
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>With AttrTempl As
(
SELECT AttributeTemplateCode,Weight,AttributeTemplateId,
ROW_NUMBER() OVER (ORDER BY AttributeTemplateCode ASC) AS RowNumber
FROM CNF_AttributeTemplate
where Weight is null
)
UPDATE AttrTempl SET Weight=RowNumber;

ALTER TABLE CNF_AttributeTemplate
  ALTER COLUMN Weight int NOT NULL;

EXEC sp_rename 'CNF_AttributeTemplate.Weight', 'SortOrder', 'column';
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Esposito</ADDEDBY>
			<SQLVERSION>1885</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>New table FlexContractFee</REASON>
			<TABLENAMES>CNF_FlexContractFee=FlexContractFeeId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'CNF_FlexContractFee'))

BEGIN

Create table [CNF_FlexContractFee]
(
	[FlexContractFeeId] Integer Identity(1,1) NOT NULL,
	[FlexContractId] Integer NOT NULL,
	[ContractFeeType] Smallint NOT NULL,
	[ContractFeeValue] Float NOT NULL,
	[IncludedInDp] Smallint NOT NULL,
Primary Key ([FlexContractFeeId])
) 

END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Esposito</ADDEDBY>
			<SQLVERSION>1884</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>[1] -- ADD TempUnblock, TempUnblockPeriodType, TempUnblockPeriod TO CNF_FlexContract

[2] -- ADD SchedDate TO DATA_TriggerItem</REASON>
			<TABLENAMES>CNF_FlexContract=FlexContractId
DATA_TriggerItem=TriggerItemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'TempUnblock' AND
                Object_ID  = Object_ID(N'CNF_FlexContract'))
BEGIN
  ALTER TABLE CNF_FlexContract ADD TempUnblock smallint NULL, 
                                   TempUnblockPeriodType smallint NULL,
                                   TempUnblockPeriod smallint NULL
END

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'SchedDate' AND
                Object_ID  = Object_ID(N'DATA_TriggerItem'))
BEGIN
  ALTER TABLE DATA_TriggerItem ADD SchedDate DateTime NULL
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FedericoCaramella</ADDEDBY>
			<SQLVERSION>1883</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'AllDayPerformance' AND
                Object_ID  = Object_ID(N'CNF_Performance'))
BEGIN
  ALTER TABLE CNF_Performance ADD AllDayPerformance smallint DEFAULT 0 NOT NULL 
END
			</REASON>
			<TABLENAMES>CNF_Subscription=SubscriptionId
CNF_Subscription2Performance=Subscription2PerformanceId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Package' AND
                Object_ID  = Object_ID(N'CNF_Subscription'))
BEGIN
  ALTER TABLE CNF_Subscription ADD Package smallint NULL 
END

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Fixed' AND
                Object_ID  = Object_ID(N'CNF_Subscription2Performance'))
BEGIN
  ALTER TABLE CNF_Subscription2Performance ADD Fixed smallint NULL 
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>pierangelodalben</ADDEDBY>
			<SQLVERSION>1882</SQLVERSION>
			<RMTRACKLINK>59240</RMTRACKLINK>
			<REASON>Added column AllDayPerformance to CNF_Performance</REASON>
			<TABLENAMES>CNF_Performance=PerformanceId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'AllDayPerformance' AND
                Object_ID  = Object_ID(N'CNF_Performance'))
BEGIN
  ALTER TABLE CNF_Performance ADD AllDayPerformance smallint DEFAULT 0 NOT NULL 
END

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Esposito</ADDEDBY>
			<SQLVERSION>1881</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>[1] -- ADD PaymentAccountRecap TO DATA_PaymentPlan2Transaction</REASON>
			<TABLENAMES>DATA_PaymentPlan2Transaction=PaymentPlan2TransactionId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns WHERE Name = N'PaymentAccountRecap' AND Object_ID  = Object_ID(N'DATA_PaymentPlan2Transaction'))
BEGIN 
  ALTER TABLE DATA_PaymentPlan2Transaction ADD PaymentAccountRecap NVarchar(30) NULL; 
END; 
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Esposito</ADDEDBY>
			<SQLVERSION>1880</SQLVERSION>
			<RMTRACKLINK>59460</RMTRACKLINK>
			<REASON>[1] -- ADD VariableAmountPayment TO CNF_FlexContract</REASON>
			<TABLENAMES>CNF_FlexContract=FlexContractId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns WHERE Name = N'VariableAmountPayment' AND Object_ID  = Object_ID(N'CNF_FlexContract'))
BEGIN 
  ALTER TABLE CNF_FlexContract ADD VariableAmountPayment Smallint NOT NULL DEFAULT 0; 
END; 
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>marcoviscusi</ADDEDBY>
			<SQLVERSION>1879</SQLVERSION>
			<RMTRACKLINK>59336</RMTRACKLINK>
			<REASON>[0]  --CREATE NEW TABLE  DATA_SaleItem2CostCenter
[1] --FOREIGN KEY SaleItemId
[2] --FOREIGN KEY CostCenterId
[3] -- ADD CostCenterType TO CNF_CostCenter_Validity</REASON>
			<TABLENAMES>DATA_SaleItem2CostCenter=SaleItem2CostCenterId
CNF_CostCenter_Validity=CostCenterValidityId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'DATA_SaleItem2CostCenter'))

BEGIN

Create table [DATA_SaleItem2CostCenter]
(
	[SaleItem2CostCenterId] Integer Identity(1,1) NOT NULL,
	[CostCenterId] Integer NOT NULL,
	[SaleItemId] Integer NOT NULL,
	[Amount] Float NOT NULL,
	[CalcType] Smallint NOT NULL,
	[CalcValue] Float NOT NULL,
	[CostCenterType] Smallint NOT NULL,
Primary Key ([SaleItem2CostCenterId])
) 

END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE [DATA_SaleItem2CostCenter]  
WITH CHECK ADD  CONSTRAINT [FK_DATA_SaleItem2CostCenter_SaleItemId] FOREIGN KEY([SaleItemId])
REFERENCES [DATA_SaleItem] ([SaleItemId])
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE [DATA_SaleItem2CostCenter]  
WITH CHECK ADD  CONSTRAINT [FK_DATA_SaleItem2CostCenter_CostCenterId] FOREIGN KEY([CostCenterId])
REFERENCES [CNF_CostCenter] ([CostCenterId])
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns WHERE Name = N'CostCenterType' AND Object_ID  = Object_ID(N'CNF_CostCenter_Validity'))
BEGIN 
  ALTER TABLE CNF_CostCenter_Validity ADD CostCenterType Smallint NULL; 
END; 
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>dpiazzolla</ADDEDBY>
			<SQLVERSION>1878</SQLVERSION>
			<RMTRACKLINK>59321</RMTRACKLINK>
			<REASON>delete an unused rigth</REASON>
			<TABLENAMES>CNF_Right=RightId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>  delete from
  DATA_Right
  where RightId = (
  select RightId FROM CNF_Right
  where RightAK = 'LedgerAccountsEdit');

  delete FROM CNF_Right
  where RightAK = 'LedgerAccountsEdit';
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Damiani Franco</ADDEDBY>
			<SQLVERSION>1877</SQLVERSION>
			<RMTRACKLINK>56582</RMTRACKLINK>
			<REASON>Add  column Enable to CNF_AttributeTemplate
[0] - Add Column
[1] - update previous recs
[2] - Set column to NOT NULL
[3] - Set column default to 1</REASON>
			<TABLENAMES>CNF_AttributeTemplate=AttributeTemplateId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Enabled' AND
                Object_ID  = Object_ID(N'CNF_AttributeTemplate'))
BEGIN
  ALTER TABLE CNF_AttributeTemplate ADD Enabled smallint NULL
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>UPDATE CNF_AttributeTemplate 
SET ENABLED = 1;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE dbo.CNF_AttributeTemplate
   ALTER COLUMN Enabled smallint NOT NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS ( select * from sys.objects 
                WHERE type = 'D' 
                  and name = ( SELECT
                                default_constraints.name
                               FROM sys.all_columns
                               INNER JOIN
                                   sys.tables 
                                        ON all_columns.object_id = tables.object_id
                                INNER JOIN sys.schemas
                                        ON tables.schema_id = schemas.schema_id
                                INNER JOIN sys.default_constraints
                                        ON all_columns.default_object_id = default_constraints.object_id
                                WHERE tables.name = 'CNF_AttributeTemplate'
                                    AND all_columns.name = 'Enabled')
                                ) 
BEGIN
  ALTER TABLE CNF_AttributeTemplate ADD CONSTRAINT CNF_AttrTempl_DEF_VALUE DEFAULT 1 FOR Enabled
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>dpiazzolla</ADDEDBY>
			<SQLVERSION>1876</SQLVERSION>
			<RMTRACKLINK>Issue #58532</RMTRACKLINK>
			<REASON>Delete from CNF_Attribute_SaleValidity where Allow = 1</REASON>
			<TABLENAMES>CNF_Attribute_SaleValidity=AttributeSaleValidityId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>  delete
  FROM CNF_Attribute_SaleValidity
  where Allow = 1
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Damiani Franco</ADDEDBY>
			<SQLVERSION>1875</SQLVERSION>
			<RMTRACKLINK>58981 </RMTRACKLINK>
			<REASON>[0] - drop DATA_SaleItem Quickupgrade reference column
[1] - drop DATA_SaleiItem fk to QuickUpgrade
			</REASON>
			<TABLENAMES>DATA_SaleItem=SaleItemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.objects
                WHERE Name = N'FK_DATA_SaleItem_QuickUpgrade' )
BEGIN
  ALTER TABLE DATA_saleItem 
  DROP CONSTRAINT FK_DATA_SaleItem_QuickUpgrade
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'QuickUpgradeId' AND
                Object_ID  = Object_ID(N'DATA_saleItem'))
BEGIN
  ALTER TABLE DATA_saleItem DROP COLUMN QuickUpgradeId
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1874</SQLVERSION>
			<RMTRACKLINK>58871</RMTRACKLINK>
			<REASON>CNF_MatrixCell
[0] add field DmgCategoryId
[1]Add FK on DmgCategoryId

RES_CNF_RequirementTemplate
[2] Add field RequirementAK null
[3] set values 
[4] switch to not null
[5] insert counter</REASON>
			<TABLENAMES>CNF_MatrixCell=MatrixCellid
RES_CNF_RequirementTemplate=RequirementTemplateId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>  IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'DmgCategoryId' AND
                Object_ID  = Object_ID(N'CNF_MatrixCell'))
BEGIN
 alter table CNF_matrixCell 
   add DmgCategoryId integer null
END


				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_MatrixCell add 
  foreign key(DmgCategoryId) references CNF_DmgCategory (DmgCategoryId)


				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>  IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'RequirementAK' AND
                Object_ID  = Object_ID(N'RES_CNF_RequirementTemplate'))
BEGIN
alter table RES_CNF_RequirementTemplate    
  add RequirementAK Nvarchar(32) NULL
END


				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update RES_CNF_RequirementTemplate set RequirementAK =(
select 
  (select top 1 SystemCode from Cnf_System) + '.REQ' + Cast(REQ.RequirementTemplateId as varchar)
from RES_CNF_RequirementTemplate as REQ
WHERE RES_CNF_RequirementTemplate.RequirementTemplateId=REQ.RequirementTemplateId
)

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table RES_CNF_RequirementTemplate    
  alter column RequirementAK Nvarchar(32) not NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>insert into DATA_Counter (CounterType, IdentifierAK, ReferenceTime, Counter) 
(
select 
  21,
  (select top 1 SystemCode from Cnf_System) + '.REQ',
  'NEVER',
  IsNull(MAX(RES_CNF_RequirementTemplate.RequirementTemplateId), 0)

from 
  RES_CNF_RequirementTemplate

)
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Esposito</ADDEDBY>
			<SQLVERSION>1873</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>Adding new fields for ovw6 down payment \ manual payment</REASON>
			<TABLENAMES>DATA_PaymentPlan2Transaction=PaymentPlan2TransactionId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'FlexPaymentStatus' AND
                Object_ID  = Object_ID(N'DATA_PaymentPlan2Transaction'))
BEGIN
  ALTER TABLE DATA_PaymentPlan2Transaction  
    ADD FlexPaymentStatus SmallInt NULL,     
        AppliedAmount Float NULL;
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1872</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>CNF_MatrixCell
[0] add field MatrixCellAK
[1] update values
[2] set field MatrixCellAK as not null
[3] update data Counter</REASON>
			<TABLENAMES>CNF_MatrixCell=MatrixCellId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT> IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'MatrixCellAk' AND
                Object_ID  = Object_ID(N'CNF_MatrixCell'))
BEGIN
 alter table CNF_MatrixCell
 add MatrixCellAk nvarchar(32) null
END


				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_MatrixCell set MatrixCellAK =(
select 
  EV.EventAK + '.MCC' + Cast (MC.MatrixCellId as varchar)

from CNF_MatrixCell as MC
inner join CNF_MatrixSheet as MS on (MC.MatrixSheetId=MS.MatrixSheetId)
inner join CNF_Event as EV on(EV.Eventid=MS.EventId) 
inner join CNF_System as SY on (EV.SystemId = SY.SystemId)

WHERE CNF_MatrixCell.MatrixCellId=MC.MatrixCellId
)

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> alter table CNF_MatrixCell
 alter column MatrixCellAk nvarchar(32) not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>insert into DATA_Counter (CounterType, IdentifierAK, ReferenceTime, Counter) 
(
select 
  20,
  EV.EventAK,
  'NEVER',
  IsNull(MAX(MC.MatrixCellid), 0)

from CNF_MatrixCell as MC
inner join CNF_MatrixSheet as MS on (MC.MatrixSheetId=MS.MatrixSheetId)
inner join CNF_Event as EV on (MS.EventId=EV.EventId)
group By 
   EV.EventAK
)
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Esposito</ADDEDBY>
			<SQLVERSION>1871</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>Adding new fields for ovw6 down payment \ manual payment</REASON>
			<TABLENAMES>DATA_PaymentPlan2Transaction=PaymentPlan2TransactionId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Ovw6Site' AND
                Object_ID  = Object_ID(N'DATA_PaymentPlan2Transaction'))
BEGIN
  ALTER TABLE DATA_PaymentPlan2Transaction  
    ADD Ovw6Site Int NULL,     
        Ovw6Station Int NULL,     
        Ovw6Transaction Int NULL,     
        Ovw6User Int NULL,     
        Ovw6TransDate Int NULL;
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1870</SQLVERSION>
			<RMTRACKLINK>58420</RMTRACKLINK>
			<REASON>RES_CNF_RequirementTemplate
[0] add field dmgCategoryId
[1] add FK</REASON>
			<TABLENAMES>RES_CNF_RequirementTemplate=RequirementTemplateId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table RES_CNF_RequirementTemplate
  add DmgCategoryId Integer NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table RES_CNF_RequirementTemplate 
 add  foreign key(DmgCategoryId) references CNF_DmgCategory (DmgCategoryId)  


				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>1869</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>empty patch for 7.4.1 release</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>1868</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>empty patch for 7.4.1 release</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>1867</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>empty patch for 7.4.1 release</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>1866</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>empty patch for 7.4.1 release</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>1865</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>empty patch for 7.4.1 release</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>1864</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>empty patch for 7.4.1 release</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>1863</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>empty patch for 7.4.1 release</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>1862</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>empty patch for 7.4.1 release</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>1861</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>empty patch for 7.4.1 release</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>1860</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>empty patch for 7.4.1 release</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>dapicella</ADDEDBY>
			<SQLVERSION>1859</SQLVERSION>
			<RMTRACKLINK>58533</RMTRACKLINK>
			<REASON>Tax exemptable during the Sale process
[0] add column TaxExempt to DATA_Sale
[1] add column TaxExempt to DATA_SaleTax 
[2] add column TaxExempt to DATA_TransactionTax</REASON>
			<TABLENAMES>DATA_Sale=SaleId
DATA_SaleTax=SaleTaxId
DATA_TransactionTax=TransactionTaxId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'TaxExempt' AND
                Object_ID  = Object_ID(N'DATA_Sale'))
BEGIN
  ALTER TABLE DATA_Sale ADD TaxExempt SmallInt NOT NULL DEFAULT(0)
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'TaxExempt' AND
                Object_ID  = Object_ID(N'DATA_SaleTax'))
BEGIN
  ALTER TABLE DATA_SaleTax ADD TaxExempt SmallInt NOT NULL DEFAULT(0)
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'TaxExempt' AND
                Object_ID  = Object_ID(N'DATA_TransactionTax'))
BEGIN
  ALTER TABLE DATA_TransactionTax ADD TaxExempt SmallInt NOT NULL DEFAULT(0)
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1858</SQLVERSION>
			<RMTRACKLINK>57118</RMTRACKLINK>
			<REASON>CNF_DataMaskTranslation
[0] modify field len to 200
[1] modify field len to 200
[2] modify field len to 200</REASON>
			<TABLENAMES>CNF_DataMaskTranslation=DataMaskTranslationId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_DataMaskTranslation
alter column FieldName Nvarchar(200) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> alter table CNF_DataMaskTranslation
alter column RequiredError Nvarchar(200) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> alter table CNF_DataMaskTranslation
alter column FieldHint Nvarchar(200) 
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FedericoCaramella</ADDEDBY>
			<SQLVERSION>1857</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>0 - Insert No Charge Upgrade Discount Promotion</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF not EXISTS (SELECT * FROM CNF_Promotion
                WHERE PromotionType = 101)
BEGIN
INSERT INTO CNF_Promotion
           (Description
           ,Active
           ,Code
           ,PromotionType
           ,CreatableOnPos
           ,SupervisorOverride)
     VALUES
           ('NO CHARGE UPGRADE',
		     1,
			 'NOCHARGE',
			 101,
			 0,
			 0 )

INSERT INTO CNF_PromotionItem
           (PromotionId
           ,Description
           ,RuleType)
     VALUES
           ((SELECT Promotionid from CNF_Promotion where PromotionType = 101),
            'NO CHARGE UPGRADE',
            'Advanced')

INSERT INTO CNF_PromotionItemRule
           (PromotionItemId
           ,AnyProduct
           ,ApplyDiscountToAllItem)
     VALUES
           (( SELECT top 1 PromotionItemId from CNF_PromotionItem order by PromotionItemId desc )
		   ,0
		   ,0)

END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FedericoCaramella</ADDEDBY>
			<SQLVERSION>1856</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>0 - Drop ApplyToSingleItem
1 - Insert Manual Discount Promotion
			</REASON>
			<TABLENAMES>CNF_PromotionItemRule=PromotionItemRuleId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'ApplyToSingleItem' AND
                Object_ID  = Object_ID(N'CNF_PromotionItemRule'))
BEGIN
alter table CNF_PromotionItemRule
  drop column ApplyToSingleItem     
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF not EXISTS (SELECT * FROM CNF_Promotion
                WHERE PromotionType = 100)
BEGIN
INSERT INTO CNF_Promotion
           (Description
           ,Active
           ,Code
           ,PromotionType
           ,CreatableOnPos
           ,SupervisorOverride)
     VALUES
           ('MANUAL DISCOUNT',
		     1,
			 'MANUAL',
			 100,
			 0,
			 0 )

INSERT INTO CNF_PromotionItem
           (PromotionId
           ,Description
           ,RuleType)
     VALUES
           ((SELECT Promotionid from CNF_Promotion where PromotionType = 100),
            'Manual Discount',
            'Advanced')

INSERT INTO CNF_PromotionItemRule
           (PromotionItemId
           ,AnyProduct
           ,ApplyDiscountToAllItem)
     VALUES
           (( SELECT top 1 PromotionItemId from CNF_PromotionItem order by PromotionItemId desc )
		   ,0
		   ,0)

END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>dpiazzolla</ADDEDBY>
			<SQLVERSION>1855</SQLVERSION>
			<RMTRACKLINK>47716</RMTRACKLINK>
			<REASON>Add FK CNF_UserGroup.SystemId</REASON>
			<TABLENAMES>CNF_UserGroup=UserGroupId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'SystemId' AND
                Object_ID  = Object_ID(N'CNF_UserGroup'))
BEGIN
  ALTER TABLE CNF_UserGroup ADD SystemId int NULL
END


				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>UPDATE CNF_UserGroup SET SystemId = (SELECT min(SystemId) FROM CNF_System)
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE CNF_UserGroup
ALTER COLUMN SystemId INT NOT NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE [CNF_UserGroup]  WITH CHECK 
ADD  CONSTRAINT [FK_CNF_UserGroup_SystemId] 
FOREIGN KEY([SystemId])
REFERENCES [CNF_System] ([SystemId])  
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>1854</SQLVERSION>
			<RMTRACKLINK>58207</RMTRACKLINK>
			<REASON>Add new table CNF_SaleRestrictionValidity
Add new table CNF_SaleLimitRestriction</REASON>
			<TABLENAMES>CNF_SaleRestrictionValidity=SaleRestrictionValidityId
CNF_SaleLimitRestriction=SaleLimitRestrictionId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>  -- Script 0
IF NOT (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'CNF_SaleRestrictionValidity'))

BEGIN


 CREATE TABLE CNF_SaleRestrictionValidity
(
	[SaleRestrictionValidityId] integer IDENTITY(1,1) NOT NULL,
	[SaleRestrictionId] integer NOT NULL,
        MaxAllowed Integer NOT NULL,
        Enabled smallint NULL,
        Updated Integer NOT NULL,
	[StartDateTime] datetime NULL,
	[EndDateTime] datetime NULL,
	[Period] smallint NULL,  
	[Sunday] smallint NULL,
	[Monday] smallint NULL,
	[Tuesday] smallint NULL,
	[Wednesday] smallint NULL,
	[Thursday] smallint NULL,
	[Friday] smallint NULL,
	[Saturday] smallint NULL,



PRIMARY KEY ([SaleRestrictionValidityId]),

  CONSTRAINT [fk_CNF_SaleRestrictionValidity_SaleRestrictionId] FOREIGN KEY ([SaleRestrictionId]) 
  REFERENCES [dbo].[CNF_SaleRestriction] ([SaleRestrictionId]) 
  ON UPDATE NO ACTION
  ON DELETE NO ACTION


)

END 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>   -- Script 1
IF NOT (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'CNF_SaleLimitRestriction'))

BEGIN

CREATE TABLE CNF_SaleLimitRestriction
(
	[SaleLimitRestrictionId] integer IDENTITY(1,1) NOT NULL,
	[SaleLimitId] integer NOT NULL,
	[SaleRestrictionId] integer NOT NULL,
	[SaleRestrictionValidityId] integer NOT NULL,
	[StartDateTime] datetime NULL,
	[EndDateTime] datetime NULL,
	[Period] smallint NULL, 
	[Sunday] smallint NULL,
	[Monday] smallint NULL,
	[Tuesday] smallint NULL,
	[Wednesday] smallint NULL,
	[Thursday] smallint NULL,
	[Friday] smallint NULL,
	[Saturday] smallint NULL,
	[Enabled] smallint NULL,
	[MaxAllowed] integer NULL,
	[Used] integer NULL,
	[FirstUsedDatetime] datetime NULL,
	[LastUsedDatetime] datetime NULL,

PRIMARY KEY ([SaleLimitRestrictionId]),

  CONSTRAINT [fk_CNF_SaleLimitRestriction_SaleLimitId] FOREIGN KEY ([SaleLimitId]) 
  REFERENCES [dbo].[CNF_SaleLimit] ([SaleLimitId]) 
  ON UPDATE NO ACTION
  ON DELETE NO ACTION,


  CONSTRAINT [fk_CNF_SaleLimitRestriction_SaleRestrictionId] FOREIGN KEY ([SaleRestrictionId]) 
  REFERENCES [dbo].[CNF_SaleRestriction] ([SaleRestrictionId]) 
  ON UPDATE NO ACTION
  ON DELETE NO ACTION,

  CONSTRAINT [fk_CNF_SaleLimitRestriction_SaleRestrictionValidityId] FOREIGN KEY ([SaleRestrictionValidityId]) 
  REFERENCES [dbo].[CNF_SaleRestrictionValidity] ([SaleRestrictionValidityId]) 
  ON UPDATE NO ACTION
  ON DELETE NO ACTION,


)

END

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Damiani Franco</ADDEDBY>
			<SQLVERSION>1853</SQLVERSION>
			<RMTRACKLINK>52481</RMTRACKLINK>
			<REASON>DATA_SaleItem 
[0] Add Field QuickUpgradeId
[1] Add Foreign key  FK_SaleItem_Quickupgrade</REASON>
			<TABLENAMES>DATA_SaleItem=SaleItemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'QuickUpgradeId' AND
                Object_ID  = Object_ID(N'DATA_SaleItem'))
BEGIN
  ALTER TABLE DATA_SaleItem ADD QuickUpgradeId INT NULL
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if NOT exists (select 1 
                  from sys.objects 
                  where object_id = OBJECT_ID(N'[FK_DATA_SaleItem_QuickUpgrade]') 
                        AND parent_object_id = OBJECT_ID('CNF_MatrixCell_QuickUpgrade'))
BEGIN
  ALTER TABLE [DATA_SaleItem]  WITH CHECK 
       ADD  CONSTRAINT [FK_DATA_SaleItem_QuickUpgrade] 
            FOREIGN KEY([QuickUpgradeId])
            REFERENCES [CNF_MatrixCell_QuickUpgrade] ([QuickUpgradeId])    
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1852</SQLVERSION>
			<RMTRACKLINK>58392</RMTRACKLINK>
			<REASON>CNF_DataMask
[0] add field MasterObjectType 
[1] add field MasterObjectTypeValue</REASON>
			<TABLENAMES>CNF_DataMask=DataMaskId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT> alter table CNF_DataMask
  add MasterObjectType Integer NULL 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> alter table CNF_DataMask
  add MasterObjectTypeValue Nvarchar(30)
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_DataMask set 
 MasterObjectType =  cast( FieldRulesXML as XML).value('(/ROOT/FIELDRULELIST/FIELDRULE/MASTERFIELDENABLE/MASTEROBJECTTYPE)[1]', 'int'),
 MasterObjectTypeValue =cast( FieldRulesXML as XML).value('(/ROOT/FIELDRULELIST/FIELDRULE/MASTERFIELDENABLE/MASTERVALUE)[1]', 'nvarchar(30)')
where
 FieldRulesXML is not null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1851</SQLVERSION>
			<RMTRACKLINK>57611</RMTRACKLINK>
			<REASON>DATA_SecurityChangeLog</REASON>
			<TABLENAMES>DATA_SecurityChangeLog=SecurityChangeLogId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>  Create table [DATA_SecurityChangeLog]
(
	[SecurityChangeLogId] Integer Identity(1,1) NOT NULL,
	[WorkstationId] Integer NOT NULL,
	[UserId] Integer NOT NULL,
	[EventType] Smallint NOT NULL,
	[ChangeResult] Smallint NOT NULL,
	[TimeStamp] Datetime NOT NULL,
	[IPAddress] Nvarchar(20) NOT NULL,
	[LogMessage] Nvarchar(400) NOT NULL,
Primary Key ([SecurityChangeLogId])
) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_SecurityChangeLog] 
add  foreign key([UserId]) references [CNF_User] ([UserId]) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_SecurityChangeLog] 
add  foreign key([WorkstationId]) references [CNF_Workstation] ([WorkstationId])  


				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1850</SQLVERSION>
			<RMTRACKLINK>57611</RMTRACKLINK>
			<REASON>[0] add field  PADSSMode
[1] update old data
[2] Alter PADSSMode as not Null
[3] add field SecurityAdmin
[4] update old data
[5] alter SecurityAdmin as not Null</REASON>
			<TABLENAMES>CNF_User=userID
CNF_System=SystemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns WHERE Name = N'PADSSMode' AND Object_ID  = Object_ID(N'CNF_System'))
BEGIN 
  ALTER TABLE CNF_System ADD PADSSMode Smallint NULL; 
END; 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns WHERE Name = N'PADSSMode' AND Object_ID  = Object_ID(N'CNF_System'))
BEGIN
  UPDATE CNF_System SET PADSSMode = 0 WHERE PADSSMode IS NULL;   
END; 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT IS_NULLABLE FROM sys.columns WHERE Name = N'PADSSMode' AND Object_ID  = Object_ID(N'CNF_System'))
BEGIN
  ALTER TABLE CNF_System ALTER COLUMN PADSSMode Smallint NOT NULL; 
END; 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns WHERE Name = N'SecurityAdmin' AND Object_ID  = Object_ID(N'CNF_User'))
BEGIN 
  ALTER TABLE CNF_User ADD SecurityAdmin Smallint null;  
END;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns WHERE Name = N'SecurityAdmin' AND Object_ID  = Object_ID(N'CNF_User'))
BEGIN 
  UPDATE CNF_User SET SecurityAdmin = 0 WHERE SecurityAdmin IS NULL;
END;

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT IS_NULLABLE FROM sys.columns WHERE Name = N'SecurityAdmin' AND Object_ID  = Object_ID(N'CNF_User'))
BEGIN 
  ALTER TABLE CNF_User ALTER COLUMN SecurityAdmin Smallint NOT NULL;  
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FedericoCaramella</ADDEDBY>
			<SQLVERSION>1849</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>[0]  --CREATE NEW TABLE CNF_ExchangeRate
[1] --FOREIGN KEY FromCurrencyId
[2] --FOREIGN KEY ToCurrencyId
[3] --FOREIGN KEY RoundingRuleId</REASON>
			<TABLENAMES>CNF_ExchangeRate=ExchangeRateId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'CNF_ExchangeRate'))

BEGIN

Create table [CNF_ExchangeRate]
(
	[ExchangeRateId] Integer Identity(1,1) NOT NULL,
	[FromCurrencyId] Integer NOT NULL,
	[ToCurrencyId] Integer NOT NULL,
	[ExchangeRate] Float NOT NULL,
	[RoundDecimals] Smallint NULL,
	[RoundingRuleId] Integer NULL,
Primary Key ([ExchangeRateId])
) 

END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE [CNF_ExchangeRate]  
WITH CHECK ADD  CONSTRAINT [FK_CNF_ExchangeRate_FromCurrencyId] FOREIGN KEY([FromCurrencyId])
REFERENCES [CNF_Currency] ([CurrencyId])
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE [CNF_ExchangeRate]  
WITH CHECK ADD  CONSTRAINT [FK_CNF_ExchangeRate_ToCurrencyId] FOREIGN KEY([ToCurrencyId])
REFERENCES [CNF_Currency] ([CurrencyId])
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE [CNF_ExchangeRate]  
WITH CHECK ADD  CONSTRAINT [FK_CNF_ExchangeRate_RoundingRuleId] FOREIGN KEY([RoundingRuleId])
REFERENCES [CNF_RoundingRule] ([RoundingRuleId])
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Damiani Franco</ADDEDBY>
			<SQLVERSION>1848</SQLVERSION>
			<RMTRACKLINK>52481 </RMTRACKLINK>
			<REASON>[0]  --CREATE NEW TABLE CNF_MatrixCell_QuickUpgrade
[1] --FOREIGN KEY MatrixCellId 
[2] --FOREIGN KEY QuickUpgradeMatrixCellId
[3] --CREATE INDEX IDX_CNF_MatrixCell_QuickUpgrade_MatrixCellId
[4] --CREATE INDEX IDX_CNF_MatrixCell_QuickUpgrade_QuickUpgradeMatrixCellId
[5] -- RECREATE Function [dbo].[Split]
[6] --MOVE DATA TO NEW TABLE</REASON>
			<TABLENAMES>CNF_MatrixCell_QuickUpgrade=QuickUpgradeId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'CNF_MatrixCell_QuickUpgrade'))

BEGIN
	CREATE TABLE CNF_MatrixCell_QuickUpgrade (
		QuickUpgradeId int IDENTITY(1, 1) NOT NULL,
		MatrixCellId int NOT NULL,
		QuickUpgradeMatrixCellId int NOT NULL,
		NoChargeUpgrade smallint Default 0 NOT NULL,
		PRIMARY KEY CLUSTERED 
			(
				[QuickUpgradeId] ASC
			)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
		) ON [PRIMARY]
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE [CNF_MatrixCell_QuickUpgrade]  WITH CHECK ADD  CONSTRAINT [FK_CNF_MatrixCell_QuickUpgrade_MatrixCellId] FOREIGN KEY([MatrixCellId])
REFERENCES [CNF_MatrixCell] ([MatrixCellId])
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE [CNF_MatrixCell_QuickUpgrade]  WITH CHECK ADD  CONSTRAINT [FK_CNF_MatrixCell_QuickUpgrade_QuickUpgradeMatrixCellId] FOREIGN KEY([QuickUpgradeMatrixCellId])
REFERENCES [CNF_MatrixCell] ([MatrixCellId])
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * 
	FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS 
        WHERE CONSTRAINT_NAME ='IDX_CNF_MatrixCell_QuickUpgrade_MatrixCellId'
		and TABLE_NAME = 'CNF_MatrixCell_QuickUpgrade')
BEGIN
	CREATE NONCLUSTERED INDEX [IDX_CNF_MatrixCell_QuickUpgrade_MatrixCellId] ON [dbo].[CNF_MatrixCell_QuickUpgrade]
	(
		MatrixCellId 
	) ON [PRIMARY]

END

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * 
				FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS 
				WHERE CONSTRAINT_NAME ='IDX_CNF_MatrixCell_QuickUpgrade_QuickUpgradeMatrixCellId'
				and TABLE_NAME = 'CNF_MatrixCell_QuickUpgradeMatrixCellId')
BEGIN
	CREATE NONCLUSTERED INDEX [IDX_CNF_MatrixCell_QuickUpgrade_QuickUpgradeMatrixCellId] ON [dbo].[CNF_MatrixCell_QuickUpgrade]
	(
		QuickUpgradeMatrixCellId 
	) ON [PRIMARY]

END

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * 
            FROM INFORMATION_SCHEMA.ROUTINES
            WHERE ROUTINE_SCHEMA = 'dbo' 
            AND  ROUTINE_NAME = 'Split')

BEGIN
	DROP FUNCTION [dbo].[Split]
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE FUNCTION [dbo].[Split]
(   
 @String varchar(max)
,@Delimiter char
)
RETURNS @Results table
(
 Ordinal int
,value varchar(max)
)
as
begin

    set @String = isnull(@String,'')
    set @Delimiter = isnull(@Delimiter,',') -- default ','

    declare
     @TempString varchar(max) = @String
    ,@Ordinal int = 0
    ,@CharIndex int = 0

    set @CharIndex = charindex(@Delimiter, @TempString)
    while @CharIndex != 0 begin     
        set @Ordinal += 1       
        insert @Results values
        (
         @Ordinal
        ,substring(@TempString, 0, @CharIndex)
        )       
        set @TempString = substring(@TempString, @CharIndex + 1, len(@TempString) - @CharIndex)     
        set @CharIndex = charindex(@Delimiter, @TempString)
    end

    if @TempString != '' begin
        set @Ordinal += 1 
        insert @Results values
        (
         @Ordinal
        ,@TempString
        )
    end

    return
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>          SELECT 
	MatrixCellId, 
	QuickUpgradeIds
INTO #work_to_do
FROM 
	CNF_MatrixCellInfo 
WHERE 
	(QuickUpgradeIds is not null) and (RTRIM(LTRIM(QuickUpgradeIds)) &lt;&gt; '')

DECLARE ToWork CURSOR FOR SELECT MatrixCellId, QuickUpgradeIds FROM #work_to_do

DECLARE @MatrixCellId int
DECLARE @QuickUpgradeIds Nvarchar(1000)
DECLARE @Ordinal int
DECLARE @value varchar(max)

OPEN ToWork 
FETCH NEXT FROM ToWork INTO @MatrixCellId, @QuickUpgradeIds

WHILE @@FETCH_STATUS &lt;&gt; -1 
BEGIN
	DECLARE ToMove CURSOR FOR SELECT * FROM dbo.split(@QuickUpgradeIds, ',')
	OPEN ToMove 
	FETCH NEXT FROM ToMove INTO @Ordinal, @value

	WHILE @@FETCH_STATUS &lt;&gt; -1 
	BEGIN
		INSERT INTO CNF_MatrixCell_QuickUpgrade 
		(MatrixCellId, QuickUpgradeMatrixCellId, NoChargeUpgrade)
		VALUES
		(@MatrixCellId, CONVERT(int, (RTRIM(LTRIM(@value)))), 0) --TO CHECK

		FETCH NEXT FROM ToMove INTO @Ordinal, @value
	END

	CLOSE ToMove;
	DEALLOCATE ToMove;

	UPDATE CNF_MatrixCellInfo SET QuickUpgradeIds = Null WHERE MatrixCellId = @MatrixCellId
	FETCH NEXT FROM ToWork INTO @MatrixCellId, @QuickUpgradeIds 
END

CLOSE ToWork
DEALLOCATE ToWork

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Esposito</ADDEDBY>
			<SQLVERSION>1847</SQLVERSION>
			<RMTRACKLINK>55664</RMTRACKLINK>
			<REASON>Remapping cdburner driver from drvsiae.dll to drvcdburner.dll</REASON>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT> UPDATE 
   CNF_Driver 
 SET 
   DllName = 'DrvCDBurner.dll'    
 WHERE DriverType = 1 and FamilyType = 154
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>smcdonald</ADDEDBY>
			<SQLVERSION>1846</SQLVERSION>
			<RMTRACKLINK>55790</RMTRACKLINK>
			<REASON>Add new fields for Rapid Connect to DATA_PaymentCard</REASON>
			<TABLENAMES>DATA_PaymentCard=PaymentID</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'SystemTraceAuditNumber' AND
                Object_ID  = Object_ID(N'DATA_PaymentCard'))
BEGIN
ALTER TABLE [dbo].[DATA_PaymentCard]
ADD [SystemTraceAuditNumber] int NULL,
	[TransactionDateTime] Datetime NULL,
	[TransactionDateTimeGMT] Datetime NULL,
	[ResponseCode] Varchar(10) NULL,
	[AVSResultCode] Varchar(2) NULL,
	[CCVResultCode] Varchar(10) NULL,
	[ReferenceNumber] Varchar(30) NULL,
	[OrderNumber] Varchar(20) NULL,
	[POSEntryMode] Varchar(6) NULL,
	[AuthorizingNetworkID] Varchar(6) NULL,
	[VISAACI] Varchar(2) NULL,
	[VISAMSDI] Varchar(30) NULL,
	[VISACardLevelResult] Varchar(4) NULL,
	[VISATransID] Varchar(30) NULL,
	[MCBankNet] Varchar(30) NULL,
	[MCACI] Varchar(2) NULL,
	[MCMSDI] Varchar(30) NULL,
	[MCCCVErrorCode] Varchar(1) NULL,
	[MCPOSEntryModeChg] Varchar(1) NULL,
	[DSDiscProcCode] Varchar(12) NULL,
	[DSDiscPOSEntry] Varchar(8) NULL,
	[DSDiscRespCode] Varchar(4) NULL,
	[DSDiscPOSData] Varchar(30) NULL,
	[DSDiscTransQualifier] Varchar(4) NULL,
	[DSDiscNRID] Varchar(20) NULL,
	[AMEXPOSData] Varchar(24) NULL,
	[AMEXTranID] Varchar(30) NULL,
	[AMEXGdSoldCd] Varchar(10) NULL;
 END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1845</SQLVERSION>
			<RMTRACKLINK>57458</RMTRACKLINK>
			<REASON>CNF_System
[0] add field [WebEnabled] Smallint NULL
[1] set new filed as 0</REASON>
			<TABLENAMES>CNF_System=SystemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT> alter table CNF_System 
   add WebEnabled Smallint NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> update CNF_System set WebEnabled = 0
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fesposito</ADDEDBY>
			<SQLVERSION>1844</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Added new column CheckOverpayment</REASON>
			<TABLENAMES>CNF_PaymentMethod=PaymentMethodId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'CheckOverpayment' AND
                Object_ID  = Object_ID(N'CNF_PaymentMethod'))
BEGIN
alter table CNF_PaymentMethod
  add CheckOverpayment smallint null    
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>dapicella</ADDEDBY>
			<SQLVERSION>1843</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>empty patch for 7.3.3 release</REASON>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>dapicella</ADDEDBY>
			<SQLVERSION>1842</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>empty patch for 7.3.3 release</REASON>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>dapicella</ADDEDBY>
			<SQLVERSION>1841</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>empty patch for 7.3.3 release</REASON>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>dapicella</ADDEDBY>
			<SQLVERSION>1840</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>empty patch for 7.3.3 release</REASON>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>dapicella</ADDEDBY>
			<SQLVERSION>1839</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>empty patch for 7.3.3 release</REASON>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>dapicella</ADDEDBY>
			<SQLVERSION>1838</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>empty patch for 7.3.3 release</REASON>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>dapicella</ADDEDBY>
			<SQLVERSION>1837</SQLVERSION>
			<RMTRACKLINK/>
			<REASON/>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>dapicella</ADDEDBY>
			<SQLVERSION>1836</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>empty patch for 7.3.3 release</REASON>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>dapicella</ADDEDBY>
			<SQLVERSION>1835</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>empty patch for 7.3.3 release</REASON>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>dapicella</ADDEDBY>
			<SQLVERSION>1834</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>empty patch for 7.3.3 release</REASON>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>francescosalvi</ADDEDBY>
			<SQLVERSION>1833</SQLVERSION>
			<RMTRACKLINK>56429</RMTRACKLINK>
			<REASON>Dropped view vwStock_Inventory and recreated with one more join and field</REASON>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT *
           FROM INFORMATION_SCHEMA.VIEWS
           WHERE table_name = 'vwStock_Inventory'
             and table_schema = 'dbo')
	DROP VIEW [dbo].[vwStock_Inventory]
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE VIEW [dbo].[vwStock_Inventory]
AS
SELECT        SCP.MinStock, SCP.MatrixCellId, SCP.SKU AS Product, dbo.STOCK_CNF_Warehouse.WarehouseId, dbo.STOCK_CNF_Um.Description AS Um, 
                         dbo.STOCK_CNF_Warehouse.Description AS WareHouse, SUM(inventory.qtyleft) AS qtyleft, SUM(inventory.qtyout) AS qtyout, SUM(inventory.qtytomove) 
                         AS qtytomove, dbo.CNF_MatrixCell.Price, dbo.CNF_MatrixCell.Name
FROM            (SELECT        MatrixCellId, WarehouseId, SUM(QtyLeft) AS qtyleft, 0 AS qtyout, 0 AS qtytomove
                          FROM            dbo.STOCK_Movement WITH (nolock)
                          WHERE        (InOut = 1)
                          GROUP BY MatrixCellId, WarehouseId
                          UNION
                          SELECT        MatrixCellId, WarehouseId, 0 AS Expr1, SUM(Qty) AS qtyout, SUM(Qty - QtyMoved) AS qtytomove
                          FROM            dbo.STOCK_Movement AS STOCK_Movement_2 WITH (nolock)
                          WHERE        (InOut = - 1) AND (MovementDate = DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0))
                          GROUP BY MatrixCellId, WarehouseId
                          UNION
                          SELECT        MatrixCellId, WarehouseId, 0 AS Expr1, SUM(- Qty) AS qtyout, 0 AS qtytomove
                          FROM            dbo.STOCK_Movement AS STOCK_Movement_1 WITH (nolock)
                          WHERE        (InOut = 1) AND (MovementType IN (5, 6)) AND (MovementDate = DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0))
                          GROUP BY MatrixCellId, WarehouseId) AS inventory INNER JOIN
                         dbo.STOCK_CNF_Product AS SCP WITH (nolock) ON inventory.MatrixCellId = SCP.MatrixCellId INNER JOIN
                         dbo.STOCK_CNF_Warehouse WITH (nolock) ON inventory.WarehouseId = dbo.STOCK_CNF_Warehouse.WarehouseId INNER JOIN
                         dbo.STOCK_CNF_Um WITH (nolock) ON dbo.STOCK_CNF_Um.UmId = SCP.UmId INNER JOIN
                         dbo.CNF_MatrixCell ON SCP.MatrixCellId = dbo.CNF_MatrixCell.MatrixCellId
GROUP BY SCP.MinStock, SCP.MatrixCellId, SCP.SKU, dbo.STOCK_CNF_Warehouse.WarehouseId, dbo.STOCK_CNF_Um.Description, dbo.STOCK_CNF_Warehouse.Description, 
                         dbo.CNF_MatrixCell.Price, dbo.CNF_MatrixCell.Name
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>francescosalvi</ADDEDBY>
			<SQLVERSION>1832</SQLVERSION>
			<RMTRACKLINK>56429</RMTRACKLINK>
			<REASON>Dropped view vwStock_Inventory and recreated with one more join and field</REASON>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT *
           FROM INFORMATION_SCHEMA.VIEWS
           WHERE table_name = 'vwStock_Inventory'
             and table_schema = 'dbo')
	DROP VIEW [dbo].[vwStock_Inventory]
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE VIEW [dbo].[vwStock_Inventory]
AS
SELECT        SCP.MinStock, SCP.MatrixCellId, SCP.SKU AS Product, dbo.STOCK_CNF_Warehouse.WarehouseId, dbo.STOCK_CNF_Um.Description AS Um, 
                         dbo.STOCK_CNF_Warehouse.Description AS WareHouse, SUM(inventory.qtyleft) AS qtyleft, SUM(inventory.qtyout) AS qtyout, SUM(inventory.qtytomove) 
                         AS qtytomove, dbo.CNF_MatrixCell.Price
FROM            (SELECT        MatrixCellId, WarehouseId, SUM(QtyLeft) AS qtyleft, 0 AS qtyout, 0 AS qtytomove
                          FROM            dbo.STOCK_Movement WITH (nolock)
                          WHERE        (InOut = 1)
                          GROUP BY MatrixCellId, WarehouseId
                          UNION
                          SELECT        MatrixCellId, WarehouseId, 0 AS Expr1, SUM(Qty) AS qtyout, SUM(Qty - QtyMoved) AS qtytomove
                          FROM            dbo.STOCK_Movement AS STOCK_Movement_2 WITH (nolock)
                          WHERE        (InOut = - 1) AND (MovementDate = DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0))
                          GROUP BY MatrixCellId, WarehouseId
                          UNION
                          SELECT        MatrixCellId, WarehouseId, 0 AS Expr1, SUM(- Qty) AS qtyout, 0 AS qtytomove
                          FROM            dbo.STOCK_Movement AS STOCK_Movement_1 WITH (nolock)
                          WHERE        (InOut = 1) AND (MovementType IN (5, 6)) AND (MovementDate = DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0))
                          GROUP BY MatrixCellId, WarehouseId) AS inventory INNER JOIN
                         dbo.STOCK_CNF_Product AS SCP WITH (nolock) ON inventory.MatrixCellId = SCP.MatrixCellId INNER JOIN
                         dbo.STOCK_CNF_Warehouse WITH (nolock) ON inventory.WarehouseId = dbo.STOCK_CNF_Warehouse.WarehouseId INNER JOIN
                         dbo.STOCK_CNF_Um WITH (nolock) ON dbo.STOCK_CNF_Um.UmId = SCP.UmId INNER JOIN
                         dbo.CNF_MatrixCell ON SCP.MatrixCellId = dbo.CNF_MatrixCell.MatrixCellId
GROUP BY SCP.MinStock, SCP.MatrixCellId, SCP.SKU, dbo.STOCK_CNF_Warehouse.WarehouseId, dbo.STOCK_CNF_Um.Description, dbo.STOCK_CNF_Warehouse.Description, 
                         dbo.CNF_MatrixCell.Price
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fcaramella</ADDEDBY>
			<SQLVERSION>1831</SQLVERSION>
			<RMTRACKLINK>57459</RMTRACKLINK>
			<REASON>Added new column ApplyToSingleItem</REASON>
			<TABLENAMES>CNF_PromotionItemRule=PromotionItemRuleId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'ApplyToSingleItem' AND
                Object_ID  = Object_ID(N'CNF_PromotionItemRule'))
BEGIN
alter table CNF_PromotionItemRule
  add ApplyToSingleItem smallint null    
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AndreaDavanzo</ADDEDBY>
			<SQLVERSION>1830</SQLVERSION>
			<RMTRACKLINK>57118</RMTRACKLINK>
			<REASON>0 CREATE TABLE CNF_MaskTableItem_Translation
1 add foreign key with CNF_Language
2 add foreign key with CNF_MaskTableItem
3 add index on CNF_MaskTableItem_Translation</REASON>
			<TABLENAMES>CNF_MaskTableItem_Translation=MaskTableTranslationId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'CNF_MaskTableItem_Translation'))
BEGIN
  Create table [CNF_MaskTableItem_Translation]
  (
	[MaskTableTranslationId] Integer Identity(1,1) NOT NULL,
	[MaskTableItemId] Integer NOT NULL,
	[LanguageId] Integer NOT NULL,
	[Translation] Nvarchar(100) NULL,
  PRIMARY KEY CLUSTERED 
  (
	[MaskTableTranslationId] ASC
  )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
  ) ON [PRIMARY]
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE [CNF_MaskTableItem_Translation]  WITH CHECK ADD  CONSTRAINT [fk_MaskTableTrans_LangId] FOREIGN KEY([LanguageId])
REFERENCES [CNF_Language] ([LanguageId])
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE [CNF_MaskTableItem_Translation]  WITH CHECK ADD  CONSTRAINT [fk_MaskTableTrans_MaskId] FOREIGN KEY([MaskTableItemId])
REFERENCES [CNF_MaskTableItem] ([MaskTableItemId])
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * 
  FROM sys.indexes 
  WHERE name='Idx_MaskTable_Translate')
BEGIN
  Create UNIQUE Index [Idx_MaskTable_Translate] ON [CNF_MaskTableItem_Translation] ([MaskTableItemId] ,[LanguageId] )
END 
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AndreaDavanzo</ADDEDBY>
			<SQLVERSION>1829</SQLVERSION>
			<RMTRACKLINK>57118</RMTRACKLINK>
			<REASON>Added new column RequiredError</REASON>
			<TABLENAMES>CNF_DataMaskTranslation=DataMaskTranslationId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'RequiredError' AND
                Object_ID  = Object_ID(N'CNF_DataMaskTranslation'))
BEGIN
  ALTER TABLE CNF_DataMaskTranslation ADD RequiredError Nvarchar(40) NULL  
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1828</SQLVERSION>
			<RMTRACKLINK>55564 </RMTRACKLINK>
			<REASON>//CNF_PromotionItemRule
[0] add Check Historical Products</REASON>
			<TABLENAMES>CNF_PromotionItemRule=PromotionItemRuleId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_PromotionItemRule
  add CheckHistorical smallint null

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>1827</SQLVERSION>
			<RMTRACKLINK>57099</RMTRACKLINK>
			<REASON>Add new field in DATA_Ticket and DATA_Media in order to trace last voiid type

[0] Add new field LastVoidType in DATA_Ticket
[1] Add new field LastVoidType in DATA_Media
			</REASON>
			<TABLENAMES>DATA_Ticket=TicketId
DATA_Media=MediaId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'LastVoidType' AND
                Object_ID  = Object_ID(N'DATA_Ticket'))
BEGIN
  ALTER TABLE DATA_Ticket ADD LastVoidType smallint NULL
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'LastVoidType' AND
                Object_ID  = Object_ID(N'DATA_Media'))
BEGIN
  ALTER TABLE DATA_Media ADD LastVoidType smallint NULL
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Damiani Franco</ADDEDBY>
			<SQLVERSION>1826</SQLVERSION>
			<RMTRACKLINK>54033</RMTRACKLINK>
			<REASON>Added new field in CNF_Promotions indicate that a coupon cannot be combined with others

[0] Add new field NotCombinable
[1] Update all records in CNF_Promotions
[2] Alter Field NotCombinable to NOT NULL Default 0</REASON>
			<TABLENAMES>CNF_Promotion=PromotionId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>     
IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'NotCombinable' AND
                Object_ID  = Object_ID(N'CNF_Promotion'))
BEGIN
  ALTER TABLE CNF_Promotion ADD NotCombinable smallint NULL
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> UPDATE 
   CNF_Promotion 
 SET 
   NotCombinable = 0    
 WHERE NotCombinable IS NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS ( SELECT * FROM sys.columns
		WHERE Name = N'NotCombinable' AND Object_ID  = Object_ID(N'CNF_Promotion')) 
BEGIN 
  ALTER TABLE CNF_Promotion ADD CONSTRAINT NotComb_Def DEFAULT (0) FOR NotCombinable
END;

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>dpiazzolla</ADDEDBY>
			<SQLVERSION>1825</SQLVERSION>
			<RMTRACKLINK>56996</RMTRACKLINK>
			<REASON>Table RES_CNF_RequirementTemplate
  Added Field SetUpPerformanceName (U_Type)</REASON>
			<TABLENAMES>RES_CNF_RequirementTemplate=RequirementTemplateId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'SetUpPerformanceName' AND
                Object_ID  = Object_ID(N'RES_CNF_RequirementTemplate'))
BEGIN
  ALTER TABLE RES_CNF_RequirementTemplate ADD SetUpPerformanceName smallint DEFAULT 0 NOT NULL
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AndreaDavanzo</ADDEDBY>
			<SQLVERSION>1824</SQLVERSION>
			<RMTRACKLINK>57118</RMTRACKLINK>
			<REASON>Creation of the new table for the translation of the labels and hint for the DataMask
[0] Create table
[1] Create index
[2], [3] Create foreign keys</REASON>
			<TABLENAMES>CNF_DataMaskTranslation=DataMaskTranslationId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT (EXISTS (SELECT * 
                  FROM INFORMATION_SCHEMA.TABLES 
                  WHERE TABLE_SCHEMA = 'dbo' 
                    AND  TABLE_NAME = 'CNF_DataMaskTranslation'))

BEGIN
  Create table [CNF_DataMaskTranslation]
  (
	[DataMaskTranslationId] Integer Identity(1,1) NOT NULL,
	[LanguageId] Integer NOT NULL,
	[DataMaskId] Integer NOT NULL,
	[FieldName] Nvarchar(40) NULL,
	[FieldHint] Nvarchar(40) NULL,
  Primary Key ([DataMaskTranslationId])
  ) 
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * 
  FROM sys.indexes 
  WHERE name='Idx_DataMask_Translation')
BEGIN
  Create UNIQUE Index [Idx_DataMask_Translation] ON [CNF_DataMaskTranslation] ([LanguageId] ,[DataMaskId] )  
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE [dbo].[CNF_DataMaskTranslation]  WITH CHECK ADD CONSTRAINT [fk_DataMaskTrans_LangId] FOREIGN KEY([LanguageId])
REFERENCES [dbo].[CNF_Language] ([LanguageId])  

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE [dbo].[CNF_DataMaskTranslation]  WITH CHECK ADD CONSTRAINT [fk_DataMaskTrans_MaskId] FOREIGN KEY([DataMaskId])
REFERENCES [dbo].[CNF_DataMask] ([DataMaskId])

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>dapicella</ADDEDBY>
			<SQLVERSION>1823</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>[0] Update Permission for CNF_Doctemplate
[1] delete old rights</REASON>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>INSERT INTO CNF_DocTemplate_Permission
           (DocTemplateId
           ,UserId
           ,UserGroupId
           ,Allow)

SELECT distinct
  DR.SourceId as DocTemplateId,
  US.UserId, 
  ROl.UserGroupId,
  DR.StrValue
from CNF_Right as CR
  inner join DATA_Right as DR  on (CR.RightId=DR.RightId)
  inner join CNF_DocTemplate as Doc  on (Doc.DocTemplateId=DR.SourceId)
  left join CNF_user as US on (DR.DestId = US.UserId and DR.DestType = 145)
  left join CNF_UserGroup as ROL on (DR.DestId = ROl.UserGroupId and DR.DestType = 146)
 where         
   DR.SourceType in (148) and
   (RightAk ='EntityViewPermission')
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>delete from DATA_Right where DataRightId in 
(
SELECT distinct
  DR.DataRightId
from CNF_Right as CR
  inner join DATA_Right as DR  on (CR.RightId=DR.RightId)
 where       
   DR.SourceType in (148) and
   RightAk ='EntityViewPermission'

)
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AndreaLollobrigida</ADDEDBY>
			<SQLVERSION>1.822</SQLVERSION>
			<RMTRACKLINK>56248</RMTRACKLINK>
			<REASON>DATA_Coupon
[0] add filed State SmallInt
[1] update State on Data_Coupon</REASON>
			<TABLENAMES>DATA_Coupon=CouponId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'StateCoupon' AND
                Object_ID  = Object_ID(N'DATA_Coupon'))
BEGIN
  ALTER TABLE DATA_Coupon ADD [StateCoupon] smallint DEFAULT 0 NOT NULL
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> UPDATE DATA_Coupon 
   SET DATA_Coupon.[StateCoupon] = 2 -- Lk_CouponUseState_Used
WHERE DATA_Coupon.CouponId IN (SELECT DATA_SaleCoupon.CouponId
                                 FROM DATA_SaleCoupon
                               INNER JOIN CNF_Promotion ON (CNF_Promotion.PromotionId = DATA_SaleCoupon.PromotionId)  
                                WHERE CNF_Promotion.PromotionType = 4) --Lk_Promotiontype_MasterCoupon
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AndreaLollobrigida</ADDEDBY>
			<SQLVERSION>1.821</SQLVERSION>
			<RMTRACKLINK>56865</RMTRACKLINK>
			<REASON>Alter Stored procedure spCalcPMPState
[0] Delete spCalcPMPState if Exists
[1] Create spCalcPMPState </REASON>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>IF (EXISTS (SELECT *
              FROM   sys.objects
             WHERE  object_id = OBJECT_ID(N'[spCalcPMPState]')
               AND type IN (N'P', N'PC')))
  DROP PROCEDURE [spCalcPMPState];
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE PROCEDURE spCalcPMPState(@AEnabled INT)
AS
BEGIN
  MERGE INTO CNF_ExternalTicketRange
    USING
	 (SELECT
	    B.ExternalTicketRangeId,
        ISNULL(COUNT(CASE WHEN DATA_Ticket.CreationType = 4               THEN ISNULL(DATA_Ticket.TicketId, 0) END), 0) NumPMPGenerate,
        ISNULL(COUNT(CASE WHEN DATA_Ticket.VoidType     = 0               THEN ISNULL(DATA_Ticket.TicketId, 0) END), 0) NumPMPSold,
        ISNULL(COUNT(CASE WHEN DATA_Ticket.VoidType     IN (2, 205)       THEN ISNULL(DATA_Ticket.TicketId, 0) END), 0) NumPMPBlocked,
        ISNULL(COUNT(CASE WHEN DATA_Ticket.VoidType     = 204             THEN ISNULL(DATA_Ticket.TicketId, 0) END), 0) NumPMPStillToBeActivate,
        ISNULL(COUNT(CASE WHEN DATA_Ticket.VoidType NOT IN (0,2, 205,204) THEN ISNULL(DATA_Ticket.TicketId, 0) END), 0) NumPMPOthers
       FROM CNF_ExternalTicketRange B WITH(NOLOCK)
       LEFT OUTER JOIN CNF_FuncListIdentifierCodeFromExternal(@AEnabled) A ON A.ExternalTicketRangeId       = B.ExternalTicketRangeId
       LEFT OUTER JOIN DATA_Ticket       WITH(NOLOCK)	                   ON (DATA_Ticket.MatrixCellId     = B.MatrixCellId)
       LEFT OUTER JOIN DATA_Ticket2Media WITH(NOLOCK)                      ON (DATA_Ticket.TicketId         = DATA_Ticket2Media.TicketId)
        INNER JOIN DATA_MediaIdentifier  WITH(NOLOCK)                      ON (DATA_MediaIdentifier.Mediaid = DATA_Ticket2Media.MediaId)
                              AND DATA_MediaIdentifier.IdentifierType = 5
                              AND DATA_MediaIdentifier.IdentifierCode = A.IdentifierCode
		WHERE (B.ExtRangeType = 2) AND --External to Activate
			  (B.ExternalTicketRangeIdParent is null)
              --AND (B.Enabled=1)
      GROUP BY
        B.ExternalTicketRangeId) C ON C.ExternalTicketRangeId = CNF_ExternalTicketRange.ExternalTicketRangeId
WHEN MATCHED AND (CNF_ExternalTicketRange.ExtRangeType = 2 AND CNF_ExternalTicketRange.ExternalTicketRangeIdParent is null) THEN
 UPDATE SET CNF_ExternalTicketRange.NumPMPGenerate          = ISNULL(C.NumPMPGenerate,          0),
            CNF_ExternalTicketRange.NumPMPSold              = ISNULL(C.NumPMPSold,              0),
			CNF_ExternalTicketRange.NumPMPBlocked           = ISNULL(C.NumPMPBlocked,           0),
			CNF_ExternalTicketRange.NumPMPStillToBeActivate = ISNULL(C.NumPMPStillToBeActivate, 0),
			CNF_ExternalTicketRange.NumPMPOthers            = ISNULL(C.NumPMPOthers,            0);

      UPDATE CNF_ExternalTicketRange
         SET CNF_ExternalTicketRange.NumPMPGenerate          = 0,
             CNF_ExternalTicketRange.NumPMPSold              = 0,
             CNF_ExternalTicketRange.NumPMPBlocked           = 0,             
             CNF_ExternalTicketRange.NumPMPStillToBeActivate = 0,             
             CNF_ExternalTicketRange.NumPMPOthers            = 0
       WHERE CNF_ExternalTicketRange.ExtRangeType = 2 -- External to Activate
         AND CNF_ExternalTicketRange.UserId IS NULL        
         AND CNF_ExternalTicketRange.NumPMPGenerate IS NULL            
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.820</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>DATA_AccountFinancia
[0] add filed userId
[1] add FK on UserId</REASON>
			<TABLENAMES>DATA_AccountFinancial=AccountId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_AccountFinancial
  add UserId integer null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> Alter table [DATA_AccountFinancial] 
 add  foreign key([UserId]) references [CNF_User] ([UserId])  
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FCARAMELLA</ADDEDBY>
			<SQLVERSION>1.819</SQLVERSION>
			<RMTRACKLINK/>
			<REASON/>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FCARAMELLA</ADDEDBY>
			<SQLVERSION>1.818</SQLVERSION>
			<RMTRACKLINK/>
			<REASON/>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FCARAMELLA</ADDEDBY>
			<SQLVERSION>1.817</SQLVERSION>
			<RMTRACKLINK/>
			<REASON/>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FCARAMELLA</ADDEDBY>
			<SQLVERSION>1.816</SQLVERSION>
			<RMTRACKLINK/>
			<REASON/>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FCARAMELLA</ADDEDBY>
			<SQLVERSION>1.815</SQLVERSION>
			<RMTRACKLINK/>
			<REASON/>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FCARAMELLA</ADDEDBY>
			<SQLVERSION>1.814</SQLVERSION>
			<RMTRACKLINK/>
			<REASON/>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FCARAMELLA</ADDEDBY>
			<SQLVERSION>1.813</SQLVERSION>
			<RMTRACKLINK/>
			<REASON/>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FCARAMELLA</ADDEDBY>
			<SQLVERSION>1.812</SQLVERSION>
			<RMTRACKLINK/>
			<REASON/>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FCARAMELLA</ADDEDBY>
			<SQLVERSION>1.811</SQLVERSION>
			<RMTRACKLINK/>
			<REASON/>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FCARAMELLA</ADDEDBY>
			<SQLVERSION>1.810</SQLVERSION>
			<RMTRACKLINK/>
			<REASON/>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FedericoCaramella</ADDEDBY>
			<SQLVERSION>1.809</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>CNF_DocTemplate_Permission
[0] create table
[1] add FK on WksId
[2] add FK on  AccountId
[3] add FK on  DmgCategoryId
[4] add FK on  DocTemplateId
[5] add FK on  OperatingAreaId
[6] add FK on  UserGroupId
[7] add FK on  UserId
[8] add FK on  SiteId
			</REASON>
			<TABLENAMES>CNF_DocTemplate_Permission=DocTemplatePermissionId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>  Create table [CNF_DocTemplate_Permission]
(
	[DocTemplatePermissionId] Integer Identity(1,1) NOT NULL,
	[DocTemplateId] Integer NOT NULL,
	[SiteId] Integer NULL,
	[WorkstationId] Integer NULL,
	[DmgCategoryId] Integer NULL,
	[UserId] Integer NULL,
	[UserGroupId] Integer NULL,
	[AccountId] Integer NULL,
	[OperatingAreaId] Integer NULL,
	[Allow] Smallint NULL,
Primary Key ([DocTemplatePermissionId])
) 


				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_DocTemplate_Permission] 
add  foreign key([WorkstationId]) references [CNF_Workstation] ([WorkstationId])  

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_DocTemplate_Permission] 
add  foreign key([AccountId]) references [DATA_Account] ([AccountId]) 


				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_DocTemplate_Permission] 
add  foreign key([DmgCategoryId]) references [CNF_DmgCategory] ([DmgCategoryId])  

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_DocTemplate_Permission] 
add  foreign key([DocTemplateId]) references [CNF_DocTemplate] ([DocTemplateId])  

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> Alter table [CNF_DocTemplate_Permission] 
 add  foreign key([OperatingAreaId]) references [CNF_OperatingArea] ([OperatingAreaId])  

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> Alter table [CNF_DocTemplate_Permission] 
 add  foreign key([UserGroupId]) references [CNF_UserGroup] ([UserGroupId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_DocTemplate_Permission] add  
  foreign key([UserId]) references [CNF_User] ([UserId])   


				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_DocTemplate_Permission] 
add  foreign key([SiteId]) references [CNF_Site] ([SiteId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_DataMask set 
 MinLength = cast( FieldRulesXML as XML).value('(/ROOT/FIELDRULELIST/FIELDRULE/MINLENGTH)[1]', 'int'),
 DefaultValue =cast( FieldRulesXML as XML).value('(/ROOT/FIELDRULELIST/FIELDRULE/DEFAULTVALUE)[1]', 'nvarchar(30)')
where
 FieldRulesXML is not null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.808</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>CNF_DataMask
[0] add field Default Value
[1] add field MinLength
			</REASON>
			<TABLENAMES>CNF_DataMask=DataMaskId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT> 
 IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'defaultValue' AND
                Object_ID  = Object_ID(N'CNF_DataMAsk'))
BEGIN
   alter table CNF_DataMask      
   add DefaultValue Nvarchar(30) NULL
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> 
 IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'MinLength' AND
                Object_ID  = Object_ID(N'CNF_DataMAsk'))
BEGIN
   alter table CNF_DataMask   
  add MinLength Smallint NULL
END


				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.807</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>[0] Update Permission for CNF_DmgCategory
[1] delete old rights</REASON>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>INSERT INTO CNF_DMGCategory_Permission
           (ParentDmgCatId
           ,UserId
           ,UserGroupId
           ,Allow)

SELECT distinct
  DR.SourceId as DmgCatId,
  US.UserId, 
  ROl.UserGroupId,
  DR.StrValue
from CNF_Right as CR
  inner join DATA_Right as DR  on (CR.RightId=DR.RightId)
  inner join CNF_DmgCategory as CNF_DmgCategory  on (CNF_DmgCategory.DmgCategoryId=DR.SourceId)
  left join CNF_user as US on (DR.DestId = US.UserId and DR.DestType = 145)
  left join CNF_UserGroup as ROL on (DR.DestId = ROl.UserGroupId and DR.DestType = 146)
 where         
   DR.SourceType = 113 and
   RightAk ='EntityViewPermission'
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>delete from DATA_Right where DataRightId in 
(
SELECT distinct
  DR.DataRightId
from CNF_Right as CR
  inner join DATA_Right as DR  on (CR.RightId=DR.RightId)
 where       
   DR.SourceType = 113 and
   RightAk ='EntityViewPermission'

)
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.806</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>CNF_DmgCategory_Permission
[0] create table
[1] add FK on WksId
[2] add FK on  AccountId
[3] add FK on  DmgCategoryId
[4] add FK on  ParentDmgCatId
[5] add FK on  OperatingAreaId
[6] add FK on  UserGroupId
[7] add FK on  UserId
[8] add FK on  SiteId
			</REASON>
			<TABLENAMES>CNF_DmgCategory_Permission=DmgCategoryPermissionId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>  Create table [CNF_DmgCategory_Permission]
(
	[DmgCategoryPermissionId] Integer Identity(1,1) NOT NULL,
	[ParentDmgCatId] Integer NOT NULL,
	[SiteId] Integer NULL,
	[WorkstationId] Integer NULL,
	[DmgCategoryId] Integer NULL,
	[UserId] Integer NULL,
	[UserGroupId] Integer NULL,
	[AccountId] Integer NULL,
	[OperatingAreaId] Integer NULL,
	[Allow] Smallint NULL,
Primary Key ([DmgCategoryPermissionId])
) 


				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_DmgCategory_Permission] 
add  foreign key([WorkstationId]) references [CNF_Workstation] ([WorkstationId])  

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_DmgCategory_Permission] 
add  foreign key([AccountId]) references [DATA_Account] ([AccountId]) 


				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_DmgCategory_Permission] 
add  foreign key([DmgCategoryId]) references [CNF_DmgCategory] ([DmgCategoryId])  

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_DmgCategory_Permission] 
add  foreign key([ParentDmgCatId]) references [CNF_DmgCategory] ([DmgCategoryId])  

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> Alter table [CNF_DmgCategory_Permission] 
 add  foreign key([OperatingAreaId]) references [CNF_OperatingArea] ([OperatingAreaId])  

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> Alter table [CNF_DmgCategory_Permission] 
 add  foreign key([UserGroupId]) references [CNF_UserGroup] ([UserGroupId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_DmgCategory_Permission] add  
  foreign key([UserId]) references [CNF_User] ([UserId])   


				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_DmgCategory_Permission] 
add  foreign key([SiteId]) references [CNF_Site] ([SiteId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AndreaLollobrigida</ADDEDBY>
			<SQLVERSION>1.805</SQLVERSION>
			<RMTRACKLINK>55399</RMTRACKLINK>
			<REASON>Alterd view AccountHistory

Script[0] Drop view if exists

Script[1] Create or Recrate view</REASON>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT *
             FROM INFORMATION_SCHEMA.VIEWS
            WHERE table_name = 'AccountHistory'
             and table_schema = 'dbo')
	DROP VIEW [dbo].[AccountHistory]
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> CREATE VIEW [dbo].[AccountHistory]
AS
SELECT 
        DateOrd,
	DatePayment, 
	DateCreation, 
	ReservationAK, 
	TransactionAK,
	AccountId, 
	paymentamount,
	Debit, 
	Credit, 
	AmountDisc, 
	UserName,
	Note,
	SettleCreditPayType
FROM (SELECT P.PaymentDate    AS DateOrd,
             P.FPaymentDate    AS DatePayment, 
             dtcreation.trdate AS DateCreation, 
             dr.ReservationAK, 
             dt.TransactionAK,
			 PC.AccountId, 
			 P.PaymentAmount  AS paymentamount, 
             CASE WHEN p.paymentamount &gt; 0 THEN p.paymentamount ELSE 0 END AS Debit, 
             CASE WHEN p.paymentamount &lt; 0 THEN case when dt.TransactionType &lt;&gt; 5 then ABS(p.paymentamount) else ABS(p.paymentamount) end ELSE 0 END AS Credit, 
			 PC.AmountDisc, 
             cu.UserName,
			 dn.Note,
			 (case when pc.SettleTransactionId = dt.TransactionId then '' else cl.description end) SettleCreditPayType
        FROM dbo.DATA_PaymentCredit AS PC WITH(NOLOCK)                                    --HERE
             INNER JOIN      dbo.DATA_Payment     AS  P WITH(NOLOCK) ON (P.PaymentId     = PC.PaymentId and P.PaymentStatus = 1)
             left  JOIN      dbo.DATA_Transaction AS dt WITH(NOLOCK) ON dt.TransactionId = P.TransactionId 
             LEFT OUTER JOIN dbo.CNF_User         AS cu WITH(NOLOCK) ON cu.UserId        = dt.UserId 
             left JOIN       dbo.DATA_Sale        AS ds WITH(NOLOCK) ON ds.SaleId        = dt.SaleId 
             left JOIN       dbo.DATA_Note        AS dn WITH(NOLOCK) ON dn.NoteKey       = ds.SaleId AND dn.NoteType = 161 
             left JOIN       dbo.DATA_Reservation AS dr WITH(NOLOCK) ON dr.SaleId        = ds.SaleId 
             LEFT OUTER JOIN(SELECT MIN(FTransactionDate) AS trdate, 
                                    SaleId
                               FROM dbo.DATA_Transaction AS dt  WITH(NOLOCK) 
                             GROUP BY SaleId) AS dtcreation ON dtcreation.SaleId = ds.SaleId 
             LEFT OUTER JOIN (SELECT MIN(PaymentType) AS pttype, 
                              TransactionId
                                FROM dbo.DATA_Payment AS dp  WITH(NOLOCK) 	
                               WHERE dp.PaymentStatus = 1 --HERE
                              GROUP BY TransactionId) AS cs ON cs.TransactionId = PC.SettleTransactionId 
             LEFT OUTER JOIN dbo.CNF_LookUp AS cl ON cl.ItemId = cs.pttype AND cl.LookUpTableId = 7  AND P.PaymentStatus = 1 
UNION ALL
SELECT dt.TransactionDate AS DateOrd, 
       dt.FTransactionDate AS DatePayment, 
       dt.FTransactionDate AS DateCreation, 
	   NULL AS Expr1, 
	   dt.TransactionAk AS Expr2, 
	   L.ReferenceId AS AccountId, 
                     -- ISSUE #55399 2015 05 15
       L.EntryAmount + ISNULL(dpf.AmountFail,0) AS Expr3, 
	   case when L.EntryAmount &gt; 0 then L.EntryAmount else 0 end AS Debit, 
                                                           -- ISSUE #55399 2015 05 15
	   case when L.EntryAmount &lt; 0 then ABS(L.EntryAmount) - ISNULL(dpf.AmountFail,0) else 0 end AS Credit, 
	   NULL AS Expr4,
       cu.UserName,
	   dn.Note AS Expr5, 
	   cl.description SettleCreditPayType
 FROM dbo.DATA_Transaction AS dt WITH(NOLOCK) 
LEFT  JOIN DATA_Note as dn WITH(NOLOCK) on  dn.NoteKey = dt.SaleId AND dn.NoteType = 161  
INNER JOIN dbo.DATA_Ledger AS L WITH(NOLOCK) ON L.TransactionId = dt.TransactionId 
INNER JOIN dbo.CNF_User AS cu WITH(NOLOCK) ON cu.UserId = dt.UserId 
inner JOIN dbo.CNF_LedgerAccount AS LA WITH(NOLOCK) ON L.LedgerAccountId = LA.LedgerAccountId 
INNER JOIN (SELECT MIN(PaymentType) AS pttype, TransactionId
              FROM dbo.DATA_Payment AS dp  WITH(NOLOCK) 
            -- ISSUE #55399 2015 05 15 
            WHERE  dp.PaymentStatus = 1 
            GROUP BY TransactionId) AS cs_1 ON cs_1.TransactionId = dt.TransactionId 
LEFT OUTER JOIN dbo.CNF_LookUp AS cl ON cl.ItemId = cs_1.pttype AND cl.LookUpTableId = 7 
       --- ISSUE #55399 2015 05 15
       LEFT OUTER JOIN (SELECT SUM(ISNULL(DATA_Payment.PaymentAmount, 0)) AmountFail,
                               DATA_Payment.TransactionId
                          FROM DATA_Payment
                         WHERE DATA_Payment.PaymentStatus = 2
                         GROUP BY DATA_Payment.TransactionId) AS dpF ON dpF.TransactionId = dt.TransactionId 

       --- ISSUE #55399 2015 05 15

       WHERE (dt.TransactionType in (34,6)) 
	   AND LA.SystemAccountId= 7
	   AND (L.ReferenceTable = 197)) AS CreditDebit
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>dpiazzolla</ADDEDBY>
			<SQLVERSION>1.804</SQLVERSION>
			<RMTRACKLINK>56579</RMTRACKLINK>
			<REASON>Table CNF_Costcenter
  Added Field Enabled (U_Type)</REASON>
			<TABLENAMES>CNF_CostCenter=CostCenterId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Enabled' AND
                Object_ID  = Object_ID(N'CNF_CostCenter'))
BEGIN
  ALTER TABLE CNF_CostCenter ADD Enabled smallint DEFAULT 1 NOT NULL
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Damiani Franco</ADDEDBY>
			<SQLVERSION>1.803</SQLVERSION>
			<RMTRACKLINK>55553</RMTRACKLINK>
			<REASON>update all null values in DATA_TriggerItem.Attempts</REASON>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_TriggerItem 
set Attempts = 0 
where Attempts is NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Damiani Franco</ADDEDBY>
			<SQLVERSION>1.802</SQLVERSION>
			<RMTRACKLINK>55553</RMTRACKLINK>
			<REASON>added field attempts</REASON>
			<TABLENAMES>DATA_TriggerItem=TriggerItemID</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'Attempts' AND
                Object_ID  = Object_ID(N'DATA_TriggerItem'))
BEGIN
  ALTER TABLE DATA_TriggerItem ADD Attempts int NULL
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AndreaLollobrigida</ADDEDBY>
			<SQLVERSION>1.801</SQLVERSION>
			<RMTRACKLINK>55759</RMTRACKLINK>
			<REASON>Added  Field to CNF_ExternalTicketRange
[0]  CNF_ExternalTicketRange] ADD [NumPMPGenerate] int
[1] CNF_ExternalTicketRange] ADD [NumPMPSold] int
[2] CNF_ExternalTicketRange] ADD [NumPMPBlocked] int
[3] CNF_ExternalTicketRange] ADD [NumPMPStillToBeActivate] int
[4] CNF_ExternalTicketRange] ADD [NumPMPOthers] int  

Added Function 
			</REASON>
			<TABLENAMES>CNF_ExternalTicketRange=ExternalTicketRangeId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'NumPMPGenerate' AND
                Object_ID  = Object_ID(N'CNF_ExternalTicketRange'))
BEGIN
  ALTER TABLE CNF_ExternalTicketRange ADD NumPMPGenerate int DEFAULT 0 NULL

END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'NumPMPSold' AND
                Object_ID  = Object_ID(N'CNF_ExternalTicketRange'))
BEGIN
  ALTER TABLE CNF_ExternalTicketRange ADD NumPMPSold int DEFAULT 0 NULL
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'NumPMPBlocked' AND
                Object_ID  = Object_ID(N'CNF_ExternalTicketRange'))
BEGIN
  ALTER TABLE CNF_ExternalTicketRange ADD NumPMPBlocked int DEFAULT 0 NULL
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'NumPMPStillToBeActivate' AND
                Object_ID  = Object_ID(N'CNF_ExternalTicketRange'))
BEGIN
  ALTER TABLE CNF_ExternalTicketRange ADD NumPMPStillToBeActivate int DEFAULT 0 NULL
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'NumPMPOthers' AND
                Object_ID  = Object_ID(N'CNF_ExternalTicketRange'))
BEGIN
  ALTER TABLE CNF_ExternalTicketRange ADD NumPMPOthers int DEFAULT 0 NULL
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF (EXISTS (SELECT *
           FROM   sys.objects
           WHERE  object_id = OBJECT_ID(N'[CNF_FuncListIdentifierCodeFromExternal]')
                  AND type IN (N'FN', N'IF', N'TF', N'FS', N'FT')))
	DROP FUNCTION [CNF_FuncListIdentifierCodeFromExternal];
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE function [CNF_FuncListIdentifierCodeFromExternal] (@AEnabled INT)
  RETURNS @ListIdentifierCodeFromExternal TABLE(
    ExternalTicketRangeId INT NOT NULL,
    MatrixCellId          INT,
    IdentifierCode        NVARCHAR(MAX),
    Enabled               INT)

BEGIN
  DECLARE @ExternalTicketRangeId INT;
  DECLARE @MatrixCellId          INT;
  DECLARE @MatrixCode            NVARCHAR(MAX);
  DECLARE @FromNumber            INT;
  DECLARE @ToNumber              INT;
  DECLARE @FromNumberStr         NVARCHAR(MAX);
  DECLARE @ToNumberStr           NVARCHAR(MAX);
  DECLARE @Enabled               INT;
  DECLARE @i                     INT;
  DECLARE @len                   INT;

  IF @AEnabled = 2
    DECLARE ExternalRangeList CURSOR FOR
      SELECT CNF_ExternalTicketRange.ExternalTicketRangeId,
             CNF_MatrixCell.MatrixCellId,
             CNF_MatrixCell.Code,
             CNF_ExternalTicketRange.FromNumber,
             CNF_ExternalTicketRange.ToNumber,
             CNF_ExternalTicketRange.Enabled
        FROM CNF_ExternalTicketRange WITH(Nolock)
       LEFT OUTER JOIN CNF_MatrixCell WITH(Nolock) ON (CNF_MatrixCell.MatrixCellId = CNF_ExternalTicketRange.MatrixCellId)
       WHERE (CNF_ExternalTicketRange.ExtRangeType = 2 )
         AND (CNF_ExternalTicketRange.ExternalTicketRangeIdParent IS NULL)
  ELSE
    DECLARE ExternalRangeList CURSOR FOR
      SELECT CNF_ExternalTicketRange.ExternalTicketRangeId,
             CNF_MatrixCell.MatrixCellId,
             CNF_MatrixCell.Code,
             CNF_ExternalTicketRange.FromNumber,
             CNF_ExternalTicketRange.ToNumber,
             CNF_ExternalTicketRange.Enabled
        FROM CNF_ExternalTicketRange WITH(Nolock)
       LEFT OUTER JOIN CNF_MatrixCell WITH(Nolock) ON (CNF_MatrixCell.MatrixCellId = CNF_ExternalTicketRange.MatrixCellId)
       WHERE (CNF_ExternalTicketRange.ExtRangeType = 2 )
         AND (CNF_ExternalTicketRange.ExternalTicketRangeIdParent IS NULL)
         AND (CNF_ExternalTicketRange.Enabled = @AEnabled)

  OPEN ExternalRangeList FETCH
  NEXT FROM ExternalRangeList INTO @ExternalTicketRangeId, @MatrixCellId, @MatrixCode, @FromNumberstr, @ToNumberstr, @Enabled

  WHILE @@FETCH_STATUS &lt;&gt; -1
  BEGIN
    SET @FromNumber = @FromNumberstr
    SET @ToNumber = @ToNumberstr
    SET @len = LEN(@FromNumberstr)
    SET @i = @FromNumber

    WHILE @i &lt;= @ToNumber
    BEGIN
        INSERT INTO @ListIdentifierCodeFromExternal
        SELECT
            @ExternalTicketRangeId AS ExternalTicketRangeId,
            @MatrixCellId AS MatrixCellId,
            @MatrixCode + REPLICATE('0',@len-LEN(convert(Varchar(MAX),  @i))) +convert(Varchar(MAX),  @i) AS IdentifierCode,
            @Enabled AS Enabled
        SET @i = @i + 1
    END

    FETCH NEXT FROM ExternalRangeList INTO @ExternalTicketRangeId, @MatrixCellId, @MatrixCode, @FromNumberstr, @ToNumberstr, @Enabled
  END

  DEALLOCATE ExternalRangeList;

  RETURN;
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF (EXISTS (SELECT *
           FROM   sys.objects
           WHERE  object_id = OBJECT_ID(N'[spCalcPMPState]')
                  AND type IN (N'P', N'PC')))
	DROP PROCEDURE [spCalcPMPState];
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE PROCEDURE spCalcPMPState(@AEnabled INT)
AS
BEGIN
  MERGE INTO CNF_ExternalTicketRange
USING
	 (SELECT
	    B.ExternalTicketRangeId,
        COUNT(CASE WHEN DATA_Ticket.CreationType = 4               THEN ISNULL(DATA_Ticket.TicketId, 0) END) NumPMPGenerate,
        COUNT(CASE WHEN DATA_Ticket.VoidType = 0                   THEN ISNULL(DATA_Ticket.TicketId, 0) END) NumPMPSold,
        COUNT(CASE WHEN DATA_Ticket.VoidType in (2, 205)           THEN ISNULL(DATA_Ticket.TicketId, 0) END) NumPMPBlocked,
        COUNT(CASE WHEN DATA_Ticket.VoidType = 204                 THEN ISNULL(DATA_Ticket.TicketId, 0) END) NumPMPStillToBeActivate,
        COUNT(CASE WHEN DATA_Ticket.VoidType NOT IN (0,2, 205,204) THEN ISNULL(DATA_Ticket.TicketId, 0) END) NumPMPOthers
       FROM CNF_ExternalTicketRange B with(Nolock)
       LEFT OUTER JOIN CNF_FuncListIdentifierCodeFromExternal(@AEnabled) A ON A.ExternalTicketRangeId       = B.ExternalTicketRangeId
       LEFT OUTER JOIN DATA_Ticket        with(Nolock)	                   ON (DATA_Ticket.MatrixCellId     = B.MatrixCellId)
        LEFT OUTER JOIN DATA_Ticket2Media with(Nolock)                     ON (DATA_Ticket.TicketId         = DATA_Ticket2Media.TicketId)
        INNER JOIN DATA_MediaIdentifier   with(Nolock)                     ON (DATA_MediaIdentifier.Mediaid = DATA_Ticket2Media.MediaId)
                              AND DATA_MediaIdentifier.IdentifierType = 5
                              AND DATA_MediaIdentifier.IdentifierCode = A.IdentifierCode
		WHERE (B.ExtRangeType=2) AND
			  (B.ExternalTicketRangeIdParent is null)
              --AND (B.Enabled=1)
      GROUP BY
        B.ExternalTicketRangeId) C ON C.ExternalTicketRangeId = CNF_ExternalTicketRange.ExternalTicketRangeId
WHEN MATCHED AND (CNF_ExternalTicketRange.ExtRangeType = 2 AND CNF_ExternalTicketRange.ExternalTicketRangeIdParent is null) THEN
 UPDATE SET CNF_ExternalTicketRange.NumPMPGenerate          = ISNULL(C.NumPMPGenerate, 0),
            CNF_ExternalTicketRange.NumPMPSold              = ISNULL(C.NumPMPSold, 0),
			CNF_ExternalTicketRange.NumPMPBlocked           = ISNULL(C.NumPMPBlocked, 0),
			CNF_ExternalTicketRange.NumPMPStillToBeActivate = ISNULL(C.NumPMPStillToBeActivate, 0),
			CNF_ExternalTicketRange.NumPMPOthers            = ISNULL(C.NumPMPOthers, 0);
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AndreaLollobrigida</ADDEDBY>
			<SQLVERSION>1.800</SQLVERSION>
			<RMTRACKLINK>55926</RMTRACKLINK>
			<REASON>Modifiied some column size

[0] CNF_Attribute.Name to 256
[1] CNF_Attribute.Code to 128
[2] CNF_MatrixSheet.Code to 128
[3] STOCK_CNF_Product SKU to 64
[4] STOCK_CNF_ProductBarcodes to 64</REASON>
			<TABLENAMES>CNF_Attribute=AttributeId
CNF_MatrixSheet=MatrixSheetId
STOCK_CNF_Product=MatrixCellId
STOCK_CNF_ProductBarcodes=ProductBarcodeIf
STOCK_CNF_ProductCategory=CategoryId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
            WHERE Name = N'Name' AND
            Object_ID  = Object_ID(N'CNF_Attribute'))
BEGIN
  ALTER TABLE CNF_Attribute ALTER COLUMN [Name] NVARCHAR(256)
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
            WHERE Name = N'Code' AND
            Object_ID  = Object_ID(N'CNF_Attribute'))
BEGIN
  ALTER TABLE CNF_Attribute ALTER COLUMN [Code] NVARCHAR(128) NOT NULL
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * 
            FROM sys.indexes 
           WHERE name='IDX_CNF_MatrixSheet_Code' AND object_id = OBJECT_ID('CNF_MatrixSheet'))
BEGIN
   DROP INDEX [IDX_CNF_MatrixSheet_Code] ON [CNF_MatrixSheet]   
END

ALTER TABLE [CNF_MatrixSheet] ALTER COLUMN [Code] NVARCHAR(128) 

CREATE NONCLUSTERED INDEX [IDX_CNF_MatrixSheet_Code] ON [CNF_MatrixSheet] ([Code])
WITH (
  PAD_INDEX = OFF,
  DROP_EXISTING = OFF,
  STATISTICS_NORECOMPUTE = OFF,
  SORT_IN_TEMPDB = OFF,
  ONLINE = OFF,
  ALLOW_ROW_LOCKS = ON,
  ALLOW_PAGE_LOCKS = ON)
ON [PRIMARY]
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
            WHERE Name = N'SKU' AND
            Object_ID  = Object_ID(N'STOCK_CNF_Product'))
BEGIN
  ALTER TABLE STOCK_CNF_Product ALTER COLUMN [SKU] NVARCHAR(64) NOT NULL
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE [STOCK_CNF_ProductCategory] ALTER COLUMN [Description] NVARCHAR(128) NOT NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * 
            FROM sys.indexes 
           WHERE name='IdxSTOCK_CNF_ProductCategory_ExternalCode' AND object_id = OBJECT_ID('STOCK_CNF_ProductCategory'))
BEGIN
   DROP INDEX [IdxSTOCK_CNF_ProductCategory_ExternalCode] ON [STOCK_CNF_ProductCategory]   
END

ALTER TABLE [STOCK_CNF_ProductCategory] ALTER COLUMN [ExternalCode] NVARCHAR(64)

CREATE NONCLUSTERED INDEX [IdxSTOCK_CNF_ProductCategory_ExternalCode] ON [STOCK_CNF_ProductCategory]
  ([ExternalCode])
WITH (
  PAD_INDEX = OFF,
  DROP_EXISTING = OFF,
  STATISTICS_NORECOMPUTE = OFF,
  SORT_IN_TEMPDB = OFF,
  ONLINE = OFF,
  ALLOW_ROW_LOCKS = ON,
  ALLOW_PAGE_LOCKS = ON)
ON [PRIMARY]
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>rfabio</ADDEDBY>
			<SQLVERSION>1.799</SQLVERSION>
			<RMTRACKLINK/>
			<REASON/>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT
* 
FROM sys.indexes 
WHERE name='idxDataShopCartItemSearchCapacityEnvelop')
BEGIN
  CREATE NONCLUSTERED INDEX [idxDataShopCartItemSearchCapacityEnvelop] ON [dbo].[DATA_ShopCartItem]
(
[EnvelopeCapacityId] ASC,[ItemGuid] ASC
) ON [PRIMARY]

END

IF NOT EXISTS (SELECT
* 
FROM sys.indexes 
WHERE name ='idxEmptyDataShopCartItem')
BEGIN
  CREATE NONCLUSTERED INDEX [idxEmptyDataShopCartItem] ON [dbo].[DATA_ShopCartItem]
(
[WorkstationId] ASC, [UserId] ASC
) ON [PRIMARY]

END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AndreaLollobrigida</ADDEDBY>
			<SQLVERSION>1.798</SQLVERSION>
			<RMTRACKLINK>55350</RMTRACKLINK>
			<REASON>[0] Modified lenght columns Name from NVArChart(50) to NVarChar(128)

[1] Add additional FlexPaymentStatus for Partial Payments</REASON>
			<TABLENAMES>CNF_Attribute=AttributeId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
            WHERE Name = N'Name' AND
            Object_ID  = Object_ID(N'CNF_Attribute'))
BEGIN
  ALTER TABLE CNF_Attribute ALTER COLUMN [Name] nvarchar(128)
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AndreaLollobrigida</ADDEDBY>
			<SQLVERSION>1.797</SQLVERSION>
			<RMTRACKLINK>55350</RMTRACKLINK>
			<REASON>[0] Correction collection</REASON>
			<TABLENAMES>CNF_Attribute=AttributeId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
            WHERE Name = N'Code' AND
            Object_ID  = Object_ID(N'CNF_Attribute'))
BEGIN
  ALTER TABLE CNF_Attribute ALTER COLUMN [Code] nvarchar(64) NOT NULL
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AndreaLollobrigida</ADDEDBY>
			<SQLVERSION>1.796</SQLVERSION>
			<RMTRACKLINK>55350</RMTRACKLINK>
			<REASON>[0] Modified lenght columns Code from NVArChart(10) to NVarChar(64)</REASON>
			<TABLENAMES>CNF_Attribute=AttributeId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.columns
            WHERE Name = N'Code' AND
            Object_ID  = Object_ID(N'CNF_Attribute'))
BEGIN
  ALTER TABLE CNF_Attribute ALTER COLUMN [Code] nvarchar(64) NOT NULL
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>smcdonald</ADDEDBY>
			<SQLVERSION>1.795</SQLVERSION>
			<RMTRACKLINK>52807</RMTRACKLINK>
			<REASON>Add new AppliedAmount column to DATA_PaymentPlan for RMTrack # 52807</REASON>
			<TABLENAMES>DATA_PaymentPlan=PaymentPlanID</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>if not exists(select * from sys.columns where Name = N'AppliedAmount' and Object_ID = Object_ID(N'DATA_PaymentPlan'))
begin
  ALTER TABLE DATA_PaymentPlan ADD AppliedAmount Float NULL;
end

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if exists(select * from sys.columns where Name = N'AppliedAmount' and Object_ID = Object_ID(N'DATA_PaymentPlan'))
begin
  UPDATE DATA_PaymentPlan
    SET AppliedAmount = Amount
  WHERE AppliedAmount IS NULL AND PaymentDate IS NOT NULL;
end

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if exists(select * from sys.columns where Name = N'AppliedAmount' and Object_ID = Object_ID(N'DATA_PaymentPlan'))
begin
  UPDATE DATA_PaymentPlan
    SET AppliedAmount = 0.00
  WHERE AppliedAmount IS NULL;
end

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if exists(select * from sys.columns where Name = N'AppliedAmount' and Object_ID = Object_ID(N'DATA_PaymentPlan'))
begin
  ALTER TABLE [dbo].[DATA_PaymentPlan] ALTER COLUMN [AppliedAmount] float NOT NULL;
end 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>OTNALO</ADDEDBY>
			<SQLVERSION>1.794</SQLVERSION>
			<RMTRACKLINK>52136</RMTRACKLINK>
			<REASON>[0] Added columns PerformanceId to CNF_AlternativeCodes</REASON>
			<TABLENAMES>CNF_AlternativeCodes=AlternativeCodesId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'PerformanceId' AND
                Object_ID  = Object_ID(N'CNF_AlternativeCodes'))
BEGIN
  ALTER TABLE CNF_AlternativeCodes ADD PerformanceId int NULL
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>rfabio</ADDEDBY>
			<SQLVERSION>1.793</SQLVERSION>
			<RMTRACKLINK>55301</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>RES_CNF_ResourceRequirementAllowed=ResourceRequirementAllowedId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>
 IF OBJECT_ID (N'RES_CNF_ResourceRequirementAllowed', N'U') IS NULL 
 begin
Create table [RES_CNF_ResourceRequirementAllowed]
(
	[ResourceRequirementAllowedId] Integer Identity(1,1) NOT NULL,
	[ResourceTypeId] Integer NOT NULL,
	[RequirementTypeId] Integer NOT NULL,
Primary Key ([ResourceRequirementAllowedId])
) 

Alter table [RES_CNF_ResourceRequirementAllowed] add constraint FK_RES_CNF_ResourceRequirementAllowed_ResourceType foreign key([ResourceTypeId]) references [RES_CNF_ResourceType] ([ResourceTypeId])
Alter table [RES_CNF_ResourceRequirementAllowed] add constraint FK_RES_CNF_ResourceRequirementAllowed_RequirementType foreign key([RequirementTypeId]) references [RES_CNF_RequirementType] ([RequirementTypeId])  
end
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>1.792</SQLVERSION>
			<RMTRACKLINK>50911</RMTRACKLINK>
			<REASON>[0] - In table SIAE_Category removed FK liked to MatrixCellId</REASON>
			<TABLENAMES>SIAE_Category=SiaeCategoryId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>declare @foreign_key_name nvarchar(max),
@dropstmt nvarchar(max);

select @foreign_key_name = f.name
from sys.foreign_keys AS f
inner join sys.foreign_key_columns AS fc 
on  f.object_id = fc.constraint_object_id    
where  f.parent_object_id = object_id(N'[dbo].[SIAE_Category]')
and  f.referenced_object_id = object_id(N'[dbo].[CNF_MatrixCell]')   
and COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'MatrixCellId';

if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [SIAE_Category] DROP CONSTRAINT [' + @foreign_key_name + ']'; 
  execute sp_executesql @dropstmt
end;
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AndreaDavanzo</ADDEDBY>
			<SQLVERSION>1.791</SQLVERSION>
			<RMTRACKLINK>54650</RMTRACKLINK>
			<REASON>[0] Added columns AcqRefData to DATA_PaymentCard
[1] Added columns RecordNo to DATA_PaymentCard
[2] Added columns ProcessData to DATA_PaymentCard</REASON>
			<TABLENAMES>DATA_PaymentCard=PaymentId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>if not exists(SELECT * 
              FROM sys.columns 
              WHERE [name] = N'AcqRefData' AND [object_id] = OBJECT_ID(N'DATA_PaymentCard'))           
BEGIN
ALTER TABLE DATA_PaymentCard
ADD AcqRefData varchar(100) NULL
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if not exists(SELECT * 
              FROM sys.columns 
              WHERE [name] = N'RecordNo' AND [object_id] = OBJECT_ID(N'DATA_PaymentCard'))           
BEGIN
ALTER TABLE DATA_PaymentCard
ADD RecordNo varchar(100) NULL
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if not exists(SELECT * 
              FROM sys.columns 
              WHERE [name] = N'ProcessData' AND [object_id] = OBJECT_ID(N'DATA_PaymentCard'))           
BEGIN
ALTER TABLE DATA_PaymentCard
ADD ProcessData varchar(50) NULL
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>skhan2</ADDEDBY>
			<SQLVERSION>1.790</SQLVERSION>
			<RMTRACKLINK/>
			<REASON/>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>DROP TABLE [dbo].[CNF_SALTO_ZONE];

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DROP TABLE [dbo].[CNF_SALTO_PREIPHERALS];

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_SALTO_ZONE]
(
	[RowID] Integer Identity(1,1) NOT NULL,
	[Name] Nvarchar(50) NULL,
	[ZoneId] Nvarchar(50) NULL, UNIQUE ([ZoneId]),
	[Status] Smallint NULL,
Primary Key ([RowID])
); 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_SALTO_PERIPHERALS]
(
	[RowID] Integer Identity(1,1) NOT NULL,
	[Name] Nvarchar(50) NOT NULL,
	[Description] Nvarchar(100) NULL,
	[IpAddress] Nvarchar(30) NULL,
Primary Key ([RowID])
); 
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AndreaLollobrigida</ADDEDBY>
			<SQLVERSION>1.789</SQLVERSION>
			<RMTRACKLINK>54545</RMTRACKLINK>
			<REASON>RES_CNF_Resource
[0] Made Duplicated ResourseCode Unique
[1] Made null ResourceCode equals ResourceId
[2] Set RES_CNF_Resource as NOT NULL
[3] Create an Unique index on ResourceCode</REASON>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>UPDATE RES_CNF_Resource
   SET RES_CNF_Resource.ResourceCode = 
   		RES_CNF_Resource.ResourceCode + '_' + CAST(RES_CNF_Resource.ResourceId AS VARCHAR)
WHERE
 (SELECT COUNT(RC.ResourceCode)
    FROM RES_CNF_Resource RC
WHERE RC.ResourceCode = RES_CNF_Resource.ResourceCode    
GROUP BY RC.ResourceCode)  &gt; 1
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>UPDATE RES_CNF_Resource
   SET RES_CNF_Resource.ResourceCode = 
   		 '_' + CAST(RES_CNF_Resource.ResourceId AS VARCHAR)
WHERE RES_CNF_Resource.ResourceCode IS NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE [dbo].[RES_CNF_Resource]
ALTER COLUMN [ResourceCode] varchar(32) COLLATE Latin1_General_CI_AS NOT NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> ALTER TABLE [dbo].[RES_CNF_Resource]
ADD CONSTRAINT [IDX_RES_CNF_Resource_ResourceCode_uq] 
UNIQUE NONCLUSTERED ([ResourceCode])
WITH (
  PAD_INDEX = OFF,
  IGNORE_DUP_KEY = OFF,
  STATISTICS_NORECOMPUTE = OFF,
  ALLOW_ROW_LOCKS = ON,
  ALLOW_PAGE_LOCKS = ON)
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>skhan2</ADDEDBY>
			<SQLVERSION>1.788</SQLVERSION>
			<RMTRACKLINK/>
			<REASON/>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_SALTO_ZONE]
(
	[ID] Integer NOT NULL,
	[name] Nvarchar(50) NULL,
	[ZoneId] Nvarchar(50) NULL, UNIQUE ([ZoneId]),
	[Status] Smallint NULL,
Primary Key ([ID])
);
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_SALTO_PREIPHERALS]
(
	[id] Integer NOT NULL,
	[Name] Nvarchar(50) NOT NULL,
	[Description] Nvarchar(100) NULL,
	[IpAddress] Nvarchar(30) NULL,
Primary Key ([id])
);
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>rfabio</ADDEDBY>
			<SQLVERSION>1.787</SQLVERSION>
			<RMTRACKLINK>54497</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>DATA_Sale=SaleId
DATA_Account=AccountId
DATA_triggerItem=TriggerItemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>if not exists(SELECT * 
              FROM sys.columns 
              WHERE [name] = N'LanguageId' AND [object_id] = OBJECT_ID(N'DATA_Sale'))           
BEGIN
	alter table data_sale add LanguageId int;                                         
	Alter table [DATA_Sale] add constraint FK_DATA_Sale_LanguageId  foreign key([LanguageId]) references [CNF_Language] ([LanguageId]);


end


if not exists(SELECT * 
              FROM sys.columns 
              WHERE [name] = N'LanguageId' AND [object_id] = OBJECT_ID(N'DATA_Account'))           
BEGIN
	alter table data_account add LanguageId int;
	Alter table [DATA_Account] add constraint FK_Data_Account_LanguageID foreign key([LanguageId]) references [CNF_Language] ([LanguageId]);


end


				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if not exists(SELECT * 
              FROM sys.columns 
              WHERE [name] = N'AdditionalFilters' AND [object_id] = OBJECT_ID(N'DATA_triggerItem'))           
BEGIN
  alter table DATA_triggerItem Add AdditionalFilters ntext null
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF (NOT EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                 WHERE TABLE_NAME = 'SYS_LockQty'))                  
begin
Create table [SYS_LockQty]
(
	[Context] varchar(5) NOT NULL,
	[Key] varchar(10) NOT NULL,
	[Who] varchar(20) NOT NULL,
	[Qty] Integer NULL,
	[LastUsage] Datetime NULL,
Primary Key ([Context],[Key],[Who])
) 
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.objects WHERE type = 'P' AND name = 'sp_GetLocksQty')
DROP PROCEDURE sp_GetLocksQty
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> create procedure sp_GetLocksQty
@Context varchar(5),
@Key varchar(10),
@Who varchar(20),
@Locked integer output,
@InUse integer output
as
begin

 select @Locked = IsNull(sum( Qty ),0)
 from SYS_LockQty with (READCOMMITTEDLOCK, ROWLOCK)
 where context = @context and [key] = @key and who &lt;&gt; @who

 select @InUse = IsNull(sum( Qty ),0)
 from SYS_LockQty with (READCOMMITTEDLOCK, ROWLOCK)
 where context = @context and [key] = @key and who = @who

end
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>rfabio</ADDEDBY>
			<SQLVERSION>1.786</SQLVERSION>
			<RMTRACKLINK/>
			<REASON/>
			<TABLENAMES>CNF_Workstation=Workstationid</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.columns
                WHERE Name = N'version' AND
                Object_ID  = Object_ID(N'cnf_workstation'))
BEGIN
  alter table cnf_workstation add version varchar(20)
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FCARAMELLA</ADDEDBY>
			<SQLVERSION>1.785</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.2.13.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FCARAMELLA</ADDEDBY>
			<SQLVERSION>1.784</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.2.13.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FCARAMELLA</ADDEDBY>
			<SQLVERSION>1.783</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.2.13.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FCARAMELLA</ADDEDBY>
			<SQLVERSION>1.782</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.2.13.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FCARAMELLA</ADDEDBY>
			<SQLVERSION>1.781</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.2.13.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FCARAMELLA</ADDEDBY>
			<SQLVERSION>1.780</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.2.13.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FCARAMELLA</ADDEDBY>
			<SQLVERSION>1.779</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.2.13.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FCARAMELLA</ADDEDBY>
			<SQLVERSION>1.778</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.2.13.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FCARAMELLA</ADDEDBY>
			<SQLVERSION>1.777</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.2.13.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FCARAMELLA</ADDEDBY>
			<SQLVERSION>1.776</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.2.13.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fesposito</ADDEDBY>
			<SQLVERSION>1.775</SQLVERSION>
			<RMTRACKLINK>53699</RMTRACKLINK>
			<REASON>Try to catch problem of "Orphan Seals" in some circustances.</REASON>
			<TABLENAMES>SIAE_SiaeLog=SiaeLogId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF not EXISTS(SELECT *
          FROM   INFORMATION_SCHEMA.COLUMNS
          WHERE  TABLE_NAME = 'SIAE_SiaeLog'
                 AND COLUMN_NAME = 'MediaIdentifierId')
alter table SIAE_SiaeLog Add MediaIdentifierId int;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF not EXISTS(SELECT *
          FROM   INFORMATION_SCHEMA.COLUMNS
          WHERE  TABLE_NAME = 'SIAE_SiaeLog'
                 AND COLUMN_NAME = 'Provenance')
alter table SIAE_SiaeLog Add Provenance int;
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>rfabio</ADDEDBY>
			<SQLVERSION>1.774</SQLVERSION>
			<RMTRACKLINK>54180</RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES>RES_ScheduleType=ScheduleTypeId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF not EXISTS(SELECT *
          FROM   INFORMATION_SCHEMA.COLUMNS
          WHERE  TABLE_NAME = 'RES_ScheduleType'
                 AND COLUMN_NAME = 'Hidden')
				 alter table RES_ScheduleType Add Hidden Smallint not null default 0;
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.773</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>SIAE_SiaeLog
[0] set TicketId as Null
[1] Update TicketId as Null where = 0
[2] Add FK on DATA_Ticket</REASON>
			<TABLENAMES>SIAE_SiaeLog=SiaeLogId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table SIAE_SiaeLog 
  alter column TicketId Integer null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update SIAE_SiaeLog
set TicketId = null where TicketId = 0
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update SIAE_SiaeLog SET TicketId = NULL where TicketId &gt; 0 and not exists (select 1 from DATA_Ticket T where T.TicketId = SIAE_SiaeLog.TicketId)  


				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [SIAE_SiaeLog] add  foreign key([TicketId]) references [DATA_Ticket] ([TicketId])
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.772</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>DATA_Ticket2Performance
[0] create Table
[1] add FK on TicketId
[2] Add FK on PerformanceId
[3] add IDX on PerformanceId
[4] add IDX on TicketId</REASON>
			<TABLENAMES>DATA_Ticket2Performance=Ticket2PerformanceId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [DATA_Ticket2Performance]
(
	[Ticket2PerformanceId] Integer Identity(1,1) NOT NULL,
	[TicketId] Integer NOT NULL,
	[PerformanceId] Integer NOT NULL,
Primary Key ([Ticket2PerformanceId])
) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_Ticket2Performance] 
add  foreign key([TicketId]) references [DATA_Ticket] ([TicketId])

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_Ticket2Performance] 
add  foreign key([PerformanceId]) references [CNF_Performance] ([PerformanceId])  
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create Index [Idx_DATA_Ticket2Performance_PerformanceId] ON [DATA_Ticket2Performance] ([PerformanceId] ) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create Index [Idx_DATA_Ticket2Performance_TicketId] ON [DATA_Ticket2Performance] ([TicketId] ) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fesposito</ADDEDBY>
			<SQLVERSION>1.771</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>IsExternal on Siae_Card</REASON>
			<TABLENAMES>SIAE_Card=CardId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
              WHERE name = N'IsExternal'
                AND Object_ID = Object_ID(N'SIAE_Card'))
BEGIN
   ALTER TABLE [SIAE_Card]
     ADD [IsExternal] smallint NOT NULL DEFAULT 0
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE SIAE_Card ALTER COLUMN SystemId Int Null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.770</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES>DATA_ExternalServiceLog=ExternalServiceLogId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [DATA_ExternalServiceLog]
(
	[ExternalServiceLogId] Integer Identity(1,1) NOT NULL,
	[LogDateTime] Datetime NOT NULL,
	[LogType] Smallint NOT NULL,
	[Request] Ntext NULL,
	[Response] Ntext NULL,
	[KeyField] Nvarchar(250) NULL,
	[ExternalKey] Nvarchar(250) NULL,
	[UserId] Integer NOT NULL,
	[WorkstationId] Integer NOT NULL,
Primary Key ([ExternalServiceLogId])
)
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_ExternalServiceLog] 
add  foreign key([WorkstationId]) references [CNF_Workstation] ([WorkstationId]) 



				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_ExternalServiceLog] add  foreign key([UserId]) references [CNF_User] ([UserId]) 


				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AndreaLollobrigida</ADDEDBY>
			<SQLVERSION>1.769</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>New Table CNF_AiternativeCodes used for CNF_Event and CNF_MatrixCell

[0] - Create Table with foreign key</REASON>
			<TABLENAMES>CNF_AlternativeCodes=AlternativeCodesId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT (EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                 WHERE TABLE_SCHEMA = 'dbo' 
                 AND  TABLE_NAME = 'CNF_AlternativeCodes'))     
BEGIN                                      
  CREATE TABLE [dbo].[CNF_AlternativeCodes] (
    [AlternativeCodesId] int IDENTITY(1, 1) NOT NULL,
    [EventId] int NULL,
    [MatrixCellId] int NULL,
    [AccountId] int NULL,
    [Code] varchar(32) COLLATE Latin1_General_CI_AS NOT NULL,
    PRIMARY KEY CLUSTERED ([AlternativeCodesId])
      WITH (
        PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF,
        ALLOW_ROW_LOCKS = OFF, ALLOW_PAGE_LOCKS = OFF),
    CONSTRAINT [CNF_AlternativeCodes_fkCNF_Event] FOREIGN KEY ([EventId]) 
    REFERENCES [dbo].[CNF_Event] ([EventId]) 
    ON UPDATE NO ACTION
    ON DELETE NO ACTION,
    CONSTRAINT [CNF_AlternativeCodes_fkCNF_MatrixCell] FOREIGN KEY ([MatrixCellId]) 
    REFERENCES [dbo].[CNF_MatrixCell] ([MatrixCellId]) 
    ON UPDATE NO ACTION
    ON DELETE NO ACTION,
    CONSTRAINT [CNF_AlternativeCodes_fkDATA_Account] FOREIGN KEY ([AccountId]) 
    REFERENCES [dbo].[DATA_Account] ([AccountId]) 
    ON UPDATE NO ACTION
    ON DELETE NO ACTION
  )
  ON [PRIMARY]  
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>angelomangiaracina</ADDEDBY>
			<SQLVERSION>1.768</SQLVERSION>
			<RMTRACKLINK>44236</RMTRACKLINK>
			<REASON>Delete base objtypes </REASON>
			<TABLENAMES>DATA_DmgData=DmgDataId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>delete from DATA_DmgData
WHERE       DmgType = 1  and(ObjType IN (1, 3, 6, 21, 31, 55) OR
                         (ObjType BETWEEN 8 AND 15)) 
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Esposito</ADDEDBY>
			<SQLVERSION>1.767</SQLVERSION>
			<RMTRACKLINK>53183</RMTRACKLINK>
			<REASON>Add link to SIAE Check before sell a matrixcell in order to avoid a ticket with wrong configuration
			</REASON>
			<TABLENAMES>CNF_MatrixCell=MatrixCellId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
           WHERE name = N'SaleableState' AND Object_ID = Object_ID(N'CNF_MatrixCell'))
BEGIN
   ALTER TABLE [CNF_MatrixCell]
     ADD [SaleableState] int NULL
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AndreaLollobrigida</ADDEDBY>
			<SQLVERSION>1.766</SQLVERSION>
			<RMTRACKLINK>53770</RMTRACKLINK>
			<REASON>[0] Add fiield UserLogId to CNF_Workstation

[1] Uppdate fields UserLogId</REASON>
			<TABLENAMES>CNF_Workstation=WorkstationId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS(SELECT * FROM sys.columns
           WHERE name = N'UserLogId' AND Object_ID = Object_ID(N'CNF_Workstation'))
BEGIN
   ALTER TABLE [CNF_Workstation]
     ADD [UserLogId] int NULL
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>UPDATE CNF_Workstation
   SET CNF_Workstation.UserLogId =
     (SELECT MAX(DATA_UserLog.LogID) 
        FROM DATA_UserLog 
       WHERE DATA_UserLog.WorkstationId = CNF_Workstation.WorkstationId)
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AndreaLollobrigida</ADDEDBY>
			<SQLVERSION>1.765</SQLVERSION>
			<RMTRACKLINK>53770</RMTRACKLINK>
			<REASON>Modify FieldName on DATA_History_Operation
LookUpId -&gt; HistoryLogType</REASON>
			<TABLENAMES>DATA_History_Operation=HistoryOperationId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS(SELECT * FROM sys.columns 
           WHERE [name] = N'LookUpId' AND [object_id] = OBJECT_ID(N'DATA_History_Operation'))
BEGIN
  EXEC sp_rename N'[dbo].[DATA_History_Operation].[LookUpId]', N'HistoryLogType', 'COLUMN'  
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AndreaLollobrigida</ADDEDBY>
			<SQLVERSION>1.764</SQLVERSION>
			<RMTRACKLINK>53770</RMTRACKLINK>
			<REASON>New Table DATA_History_Operation used to get log about user operation

[0] - Create Table with foreign key</REASON>
			<TABLENAMES>DATA_History_Operation=HistoryOperationId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF (NOT EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                 WHERE TABLE_SCHEMA = 'dbo' 
                 AND  TABLE_NAME = 'DATA_History_Operation')) 
BEGIN                 
CREATE TABLE [dbo].[DATA_History_Operation] (
    [HistoryOperationId] int IDENTITY(1, 1) NOT NULL,
    [LookUpId] int NOT NULL,
    [UserId] int NOT NULL,
    [DateOperation] datetime NOT NULL,
    [Note] nvarchar(4000) COLLATE Latin1_General_CI_AS NULL,
    CONSTRAINT PK_DATA_History_Operation
    PRIMARY KEY CLUSTERED ([HistoryOperationId])
      WITH (
        PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF,
        ALLOW_ROW_LOCKS = OFF, ALLOW_PAGE_LOCKS = OFF)
  )
  ON [PRIMARY]
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FedericoCaramella</ADDEDBY>
			<SQLVERSION>1.763</SQLVERSION>
			<RMTRACKLINK>51389</RMTRACKLINK>
			<REASON>0 - Add MinVariablePrice on CNF_MatrixCell
1 - Add MaxVariablePrice on CNF_MatrixCell</REASON>
			<TABLENAMES>CNF_MatrixCell=MatrixCellId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>if not exists(select * from sys.columns 
            where Name = N'MinVariablePrice' and Object_ID = Object_ID(N'CNF_MatrixCell'))             
begin
ALTER TABLE CNF_MatrixCell
ADD MinVariablePrice float NULL
end

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if not exists(select * from sys.columns 
            where Name = N'MaxVariablePrice' and Object_ID = Object_ID(N'CNF_MatrixCell'))             
begin
ALTER TABLE CNF_MatrixCell
ADD MaxVariablePrice float NULL
end

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>rfabio</ADDEDBY>
			<SQLVERSION>1.762</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>script 2 and 3 added for FPK Export </REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF (NOT EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                 WHERE TABLE_NAME = 'SYS_LockQty'))                  
begin
Create table [SYS_LockQty]
(
	[Context] varchar(5) NOT NULL,
	[Key] varchar(10) NOT NULL,
	[Who] varchar(20) NOT NULL,
	[Qty] Integer NULL,
	[LastUsage] Datetime NULL,
Primary Key ([Context],[Key],[Who])
)
end 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT * FROM sys.objects WHERE type = 'P' AND name = 'sp_GetLocksQty')
DROP PROCEDURE sp_GetLocksQty



				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>create procedure sp_GetLocksQty
@Context varchar(5),
@Key varchar(10),
@Who varchar(20),
@Locked integer output,
@InUse integer output
as
begin

 select @Locked = IsNull(sum( Qty ),0)
 from SYS_LockQty with (READCOMMITTEDLOCK, ROWLOCK)
 where context = @context and [key] = @key and who &lt;&gt; @who

 select @InUse = IsNull(sum( Qty ),0)
 from SYS_LockQty with (READCOMMITTEDLOCK, ROWLOCK)
 where context = @context and [key] = @key and who = @who

end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> IF OBJECT_ID('ExportEncodedReservations', 'V') IS NOT NULL
  DROP VIEW ExportEncodedReservations
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>create view ExportEncodedReservations as
  SELECT 
   TR.TransactionId,
   TR.TransactionAK,
   TR.Completed,
   TR.SiteId,
   PAYTR.TransactionId PAYTrId, 
   PAYTR.TransactionAK PAYTrAK, 
   APPTR.TransactionId APPTrId, 
   APPTR.TransactionAK APPTrAK 
 from DATA_Transaction TR (nolock) 
   inner join DATA_Sale Sale (nolock) on TR.SaleId = Sale.SaleId 
   inner join DATA_Transaction PAYTR (nolock) on Sale.SaleId = PAYTR.SaleId 
     and PAYTR.Paid &gt; 0 and PAYTR.Encoded = 0 
     and PAYTR.TransactionType = 16
   inner join DATA_Transaction APPTR (nolock) on Sale.SaleId = APPTR.SaleId 
     and APPTR.Approved &gt; 0 and APPTR.Encoded = 0 
     and APPTR.TransactionType = 16
 WHERE TR.Encoded = 1 AND
       TR.Paid = 0
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Esposito</ADDEDBY>
			<SQLVERSION>1.761</SQLVERSION>
			<RMTRACKLINK>51002</RMTRACKLINK>
			<REASON>Fiscalizzazione al tornello</REASON>
			<TABLENAMES>SIAE_ExternalTicketRange=SiaeExternalTicketRangeId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS 
                 WHERE TABLE_NAME = 'SIAE_ExternalTicketRange' 
                   AND COLUMN_NAME = 'EventId' )

BEGIN


ALTER TABLE SIAE_ExternalTicketRange ADD 
  EventId Int NULL;

ALTER TABLE SIAE_ExternalTicketRange ADD CONSTRAINT
	fk_EventId FOREIGN KEY
	(
	EventId
	) REFERENCES dbo.CNF_Event
	(
	EventId
	) ON UPDATE  NO ACTION 
	 ON DELETE  NO ACTION 

END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FedericoCaramella</ADDEDBY>
			<SQLVERSION>1.760</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES>DATA_SaleCoupon=SaleCouponId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>if not exists(select * from sys.columns 
            where Name = N'SaleItemId' and Object_ID = Object_ID(N'DATA_SaleCoupon'))             
begin
ALTER TABLE [dbo].[DATA_SaleCoupon]
ADD [SaleItemId] int NULL
end
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AndreaDavanzo</ADDEDBY>
			<SQLVERSION>1.759</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>[0] Drop MediaId foreign key
[1] Drop DriverId foreign key
[2] Drop DATA_Biometric table
[3] Create DATA_Biometric table
[4] Create DeviceId foreign key
[5] Create TicketId foreign key
[6] Create Unique Index on TicketId
[7] Alter store procedure for update on DATA_Biometric
[8] Alter store procedure for insert on DATA_Biometric</REASON>
			<TABLENAMES>DATA_Biometric=BiometricId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>declare @foreign_key_name nvarchar(max),
@dropstmt nvarchar(max);

select @foreign_key_name = f.name
from sys.foreign_keys AS f
inner join sys.foreign_key_columns AS fc 
on  f.object_id = fc.constraint_object_id    
where  f.parent_object_id = object_id(N'[dbo].[DATA_Biometric]')
and  f.referenced_object_id = object_id(N'[dbo].[DATA_Media]')   
and COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'MediaId';

if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [DATA_Biometric] DROP CONSTRAINT [' + @foreign_key_name + ']'; 
  execute sp_executesql @dropstmt
end;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>declare @foreign_key_name nvarchar(max),
@dropstmt nvarchar(max);

select @foreign_key_name = f.name
from sys.foreign_keys AS f
inner join sys.foreign_key_columns AS fc 
on  f.object_id = fc.constraint_object_id    
where  f.parent_object_id = object_id(N'[dbo].[DATA_Biometric]') 
and  f.referenced_object_id = object_id(N'[dbo].[CNF_Driver]')    
and COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'DriverId'; 

if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[DATA_Biometric] DROP CONSTRAINT [' + @foreign_key_name + ']'; 
  execute sp_executesql @dropstmt
end;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DROP TABLE [DATA_Biometric]
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE TABLE [DATA_Biometric](
	[BiometricId] [int] IDENTITY(1,1) NOT NULL,
	[TicketId] [int] NOT NULL,
	[DeviceId] [int] NOT NULL,
	[EnrollmentDate] [datetime] NOT NULL,
	[BiometricLen] [int] NOT NULL,
	[BiometricInfo] [varbinary](max) NOT NULL,
PRIMARY KEY CLUSTERED 
(
	[BiometricId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_Biometric] add constraint fkDATA_Biometric_CNF_Device foreign key([DeviceId]) 
REFERENCES [CNF_Device] ([DeviceId])
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_Biometric] add constraint fkDATA_Biometric_DATA_Ticket foreign key([TicketId]) 
REFERENCES [DATA_Ticket] ([TicketId])
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE UNIQUE NONCLUSTERED INDEX [IDX_BIOM_TICKETID] ON [dbo].[DATA_Biometric]
(
	[TicketId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER procedure sp_ui_DATA_Biometric_update
  @BiometricId int,
  @TicketId int,
  @DeviceId int,
  @EnrollmentDate datetime,
  @BiometricLen int,
  @BiometricInfo varbinary(max)
as
begin
  update DATA_Biometric
  set
    TicketId=@TicketId,
    DeviceId=@DeviceId,
    EnrollmentDate=@EnrollmentDate,
    BiometricLen=@BiometricLen,
    BiometricInfo=@BiometricInfo
  where
    BiometricId=@BiometricId
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER procedure sp_ui_DATA_Biometric_insert
  @BiometricId Integer output,
  @TicketId int,
  @DeviceId int,
  @EnrollmentDate datetime,
  @BiometricLen int,
  @BiometricInfo varbinary(max)
as
begin
  insert into DATA_Biometric (
    TicketId,
    DeviceId,
    EnrollmentDate,
    BiometricLen,
    BiometricInfo
  ) values (
    @TicketId,
    @DeviceId,
    @EnrollmentDate,
    @BiometricLen,
    @BiometricInfo
  )

  select @BiometricId=SCOPE_IDENTITY()

end
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>1.758</SQLVERSION>
			<RMTRACKLINK>51002</RMTRACKLINK>
			<REASON>Rename column from "ProgressivoAbbonamento" to "ProducerId" on table SIAE_ExteranlTicketRange

[0] - Rename Column
[1] - Add foreign key on SIAE_Producer</REASON>
			<TABLENAMES>SIAE_ExternalTicketRange=SiaeExternalTicketRangeId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>

SP_Rename 'SIAE_ExternalTicketRange.ProgressivoAbbonamento', 'ProducerId', 'COLUMN' 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>

ALTER TABLE [dbo].[SIAE_ExternalTicketRange]  WITH CHECK ADD  CONSTRAINT [fk_ProducerId] FOREIGN KEY([ProducerId])
REFERENCES [dbo].[SIAE_Producer] ([ProducerId])
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>io</ADDEDBY>
			<SQLVERSION>1.757</SQLVERSION>
			<RMTRACKLINK>50940</RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES>cnf_promotion=promotionid
cnf_promotionitem=promotionitemid</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table cnf_promotion add UseQuota smallint default 0;
alter table cnf_promotionitem add UseQuota smallint default 0;
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>1.756</SQLVERSION>
			<RMTRACKLINK>51002</RMTRACKLINK>
			<REASON>New table SIAE_ExternallTicketRange

[0] - Create Table
[1] - Add Foreign key on TipoTitolo 
[2] - Add Foreign key on CausaleRiduzione
[3] - Add Foreign key on OrdinePosto
[4] - Add Foreign key on ExternalTicketRangeId </REASON>
			<TABLENAMES>SIAE_ExternalTicketRange=SiaeExternalTicketRangeId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [SIAE_ExternalTicketRange]
(
	[SiaeExternalTicketRangeId] Integer Identity(1,1) NOT NULL, UNIQUE ([SiaeExternalTicketRangeId]),
	[ExternalTicketRangeId] Integer NOT NULL,
	[TipoTitolo] Integer NOT NULL,
	[CausaleRiduzione] Integer NOT NULL,
	[OrdinePosto] Integer NOT NULL,
	[Smaterializzato] Smallint NOT NULL,
	[TipoTassazione] Integer NOT NULL,
	[PrezzoTitolo] Float NOT NULL,
	[IvaTitolo] Float NOT NULL,
	[CodiceAbbonamento] Char(8) NULL,
	[ProgressivoAbbonamento] Integer NULL,
	[TipoTurno] Varchar(1) NULL,
	[NumPrestMax] Integer NULL,
	[PerformanceIds] Varchar(4000) NULL,
	[Rateo] Float NULL,
	[IvaRateo] Float NULL,
	[DataLimiteValidita] Datetime NULL,
Primary Key ([SiaeExternalTicketRangeId])
) 


				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>

ALTER TABLE [dbo].[SIAE_ExternalTicketRange]  WITH CHECK ADD  CONSTRAINT [fk_TipoTitolo_AttributeId] FOREIGN KEY([TipoTitolo])
REFERENCES [dbo].[CNF_Attribute] ([AttributeId])
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>
ALTER TABLE [dbo].[SIAE_ExternalTicketRange]  WITH CHECK ADD  CONSTRAINT [fk_CausaleRiduzione_AttributeId] FOREIGN KEY([CausaleRiduzione])
REFERENCES [dbo].[CNF_Attribute] ([AttributeId])
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>
ALTER TABLE [dbo].[SIAE_ExternalTicketRange]  WITH CHECK ADD  CONSTRAINT [fk_OrdinePosto_AttributeId] FOREIGN KEY([OrdinePosto])
REFERENCES [dbo].[CNF_Attribute] ([AttributeId])
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>
ALTER TABLE [dbo].[SIAE_ExternalTicketRange]  WITH CHECK ADD  CONSTRAINT [fk_ExternalTicketRangeId] FOREIGN KEY([ExternalTicketRangeId])
REFERENCES [dbo].[CNF_ExternalTicketRange] ([ExternalTicketRangeId])
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>angelomangiaracina</ADDEDBY>
			<SQLVERSION>1.755</SQLVERSION>
			<RMTRACKLINK>51100</RMTRACKLINK>
			<REASON>0 - modify column notes from text to ntext on cnf_promotion
1 - modify column notes from text to ntext on cnf_promotionItem</REASON>
			<TABLENAMES>CNF_Promotion=PromotionId
CNF_PromotionItem=PromotionItemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table cnf_promotion add notes_new ntext null; 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> update cnf_promotion set notes_new = notes; 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table cnf_promotion drop column notes; 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>exec SP_RENAME 'cnf_promotion.notes_new', 'notes', 'COLUMN';
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table cnf_promotionItem add notes_new ntext null;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update cnf_promotionItem set notes_new = notes;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table cnf_promotionItem drop column notes;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>exec SP_RENAME 'cnf_promotionItem.notes_new', 'notes', 'COLUMN'; 
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FedericoCaramella</ADDEDBY>
			<SQLVERSION>1.754</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>0 - Add SubscriptionId on DATA_SaleItem
1 - Add SubscriptionId on DATA_TransactionItem</REASON>
			<TABLENAMES>DATA_SaleItem=SaleItemId
DATA_TransactionItem=ItemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>if not exists(select * from sys.columns 
            where Name = N'SubscriptionId' and Object_ID = Object_ID(N'DATA_SaleItem'))             
begin
ALTER TABLE [dbo].[DATA_SaleItem]
ADD [SubscriptionId] int NULL
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if not exists(select * from sys.columns 
            where Name = N'SubscriptionId' and Object_ID = Object_ID(N'DATA_TransactionItem'))             
begin
ALTER TABLE [dbo].[DATA_TransactionItem]
ADD [SubscriptionId] int NULL
end
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>rfabio</ADDEDBY>
			<SQLVERSION>1.753</SQLVERSION>
			<RMTRACKLINK>50940</RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES>CNF_Promotion=PromotionId
CNF_PromotionItem=PromotionItemId
CNF_Promotion_Quota=PromotionQuotaId
CNF_PromotionItem_Quota=PromotionItemQuotaId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>
Create table [CNF_Promotion_Quota]
(
	[PromotionQuotaId] Integer Identity(1,1) NOT NULL, UNIQUE ([PromotionQuotaId]),
	[PromotionId] Integer NOT NULL,
	[MaxUsage] Integer NOT NULL,
	[Period] Datetime NULL,
	[Reversed] Integer NULL,
	[Usage] Integer NULL,
Primary Key ([PromotionQuotaId])
) 


Create Index [idxPromotonUsage_PromotionId] ON [CNF_Promotion_Quota] ([PromotionId] ) 


Create table [CNF_PromotionItem_Quota]
(
	[PromotionItemQuotaId] Integer Identity(1,1) NOT NULL, UNIQUE ([PromotionItemQuotaId]),
	[PromotionItemId] Integer NOT NULL,
	[MaxUsage] Integer NOT NULL,
	[Period] Datetime NULL,
	[Reversed] Integer NULL,
	[Usage] Integer NULL,
Primary Key ([PromotionItemQuotaId])
) 


Create Index [idxPromotionItem_Usage] ON [CNF_PromotionItem_Quota] ([PromotionItemId] ) 

alter table CNF_Promotion add [PeriodMaxUsage] Integer NULL;
alter table CNF_Promotion add [PeriodKind] Smallint NULL;

alter table CNF_PromotionItem add [PeriodMaxUsage] Integer NULL;
alter table CNF_PromotionItem add [PeriodKind] Smallint NULL;

Alter table [CNF_Promotion_Quota] add constraint fkCNF_Promotion_Quota foreign key([PromotionId]) references [CNF_Promotion] ([PromotionId]);
Alter table [CNF_PromotionItem_Quota] add constraint fkCNF_PromotionItem_Quota foreign key([PromotionItemId]) references [CNF_PromotionItem] ([PromotionItemId]);



				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>1.752</SQLVERSION>
			<RMTRACKLINK>49926</RMTRACKLINK>
			<REASON>[0] Add new record in CNF_DbInfo in order to handle
SIAE version updating BOS 
Fieldname: SiaeBuild </REASON>
			<TABLENAMES>CNF_DBInfo=DBInfoId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>
  if not exists
  (select 1 from CNF_DBInfo where ParamName = 'SiaeBuild')
  begin

INSERT INTO CNF_DBInfo
           (DBInfoType
           ,ParamName
           ,ParamValue
           ,FileTimestamp
           )
     VALUES
           (1,
            'SiaeBuild',
            '0',
            0
           )


  end



				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>1.751</SQLVERSION>
			<RMTRACKLINK>52090</RMTRACKLINK>
			<REASON>SIAE
Update SIAE_SiaeLog field "TipoTurno"
in order to handle new logic for "Abbonamenti"

[0] Abbonamenti a Turno Fisso
[1] Abbonamenti a Turno Libero e Open

			</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>update SIAE_SiaeLog
set TipoTurno = 0
where TipoTurno is null
and Operazione = 0
and TipoTitolo in
(
  select ATT.AttributeId 
  from CNF_Attribute ATT 
  inner join CNF_AttributeTemplate ATT_TEMP on ATT_TEMP.AttributeTemplateId = ATT.AttributeTemplateId
  where ATT_TEMP.AttributeTemplateCode = 'SIAE_TA' 
  and ATT.Code in ('AFN', 'AFF')
)

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update SIAE_SiaeLog
set TipoTurno = 1
where TipoTurno is null
and Operazione = 0
and TipoTitolo in
(
  select ATT.AttributeId 
  from CNF_Attribute ATT 
  inner join CNF_AttributeTemplate ATT_TEMP on ATT_TEMP.AttributeTemplateId = ATT.AttributeTemplateId
  where ATT_TEMP.AttributeTemplateCode = 'SIAE_TA' 
  and ATT.Code in ('ON', 'ALN', 'ALF', 'OF')
)

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Esposito</ADDEDBY>
			<SQLVERSION>1.750</SQLVERSION>
			<RMTRACKLINK>51967</RMTRACKLINK>
			<REASON>Update of the index [idxCounterAk]</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>if Exists(SELECT 1
            FROM sys.indexes 
           WHERE name='idxCounterAk' AND object_id = OBJECT_ID('SIAE_SiaeCounter'))
BEGIN
DROP INDEX [idxCounterAk] ON [SIAE_SiaeCounter]
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if Exists(SELECT 1
            FROM sys.indexes 
           WHERE name='idxSiaeCounterAk' AND object_id = OBJECT_ID('SIAE_SiaeCounter'))
BEGIN
DROP INDEX [idxSiaeCounterAk] ON [SIAE_SiaeCounter]
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create UNIQUE Index [idxSiaeCounterAk] ON [SIAE_SiaeCounter] ([CounterType] ,[IdentifierAK] ,[ReferenceTime] ) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>If Not Exists(SELECT 1 FROM SIAE_SiaeCounter)

INSERT INTO SIAE_SiaeCounter (CounterType, IdentifierAK, ReferenceTime, Counter, LastUpdateGuid)
SELECT 0, CAST(SEVN.OrganizzatoreId AS VARCHAR) + '.' + SSL.CodiceAbbonamento, 'NEVER', 
       CASE WHEN COUNT(*) &gt;= Max(SSL.ProgressivoAbbonamento) THEN COUNT(*)
            ELSE Max(SSL.ProgressivoAbbonamento)
       END, NULL
  FROM SIAE_SiaeLog SSL
 inner join DATA_TICKET TKT on SSL.TicketId = TKT.TicketId
 inner join CNF_MATRIXCELL MCL on TKT.MatrixCellId = MCL.MatrixCellId
 inner join CNF_AttributeSetDetail ATS on ATS.AttributeSetId = MCL.AttributeSetId
 inner join CNF_ProductValidity2Event PVE on PVE.ReferenceTable = 105 AND ATS.AttributeId = PVE.ReferenceId
 inner join SIAE_Event SEVN on SEVN.EventId = PVE.EventId
 WHERE Operazione = 0 
   and CodiceAbbonamento is NOT NULL   
   and TipoTitolo &lt;&gt;  (SELECT CNF_Attribute.AttributeId
                         FROM CNF_Attribute 
                        INNER JOIN CNF_AttributeTemplate ON CNF_Attribute.AttributeTemplateId = CNF_AttributeTemplate.AttributeTemplateId
                        WHERE CNF_AttributeTemplate.AttributeTemplateCode = 'SIAE_TA'
                          AND CNF_Attribute.Code = 'BAB')
 group by CAST(SEVN.OrganizzatoreId AS VARCHAR) + '.' + SSL.CodiceAbbonamento

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Esposito</ADDEDBY>
			<SQLVERSION>1.749</SQLVERSION>
			<RMTRACKLINK>51967</RMTRACKLINK>
			<REASON>New Store Procedure per SIAE_SiaeCounter</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>if exists (SELECT * FROM sys.objects WHERE type = 'P' AND name = 'spui_GetSiaeCounter')
DROP PROCEDURE spui_GetSiaeCounter
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE PROCEDURE [dbo].[spui_GetSiaeCounter]
 -- Add the parameters for the stored procedure here
 @CounterType smallint,
 @IdentifierAK varchar(32),
 @ReferenceTime varchar(32),
 @Counter integer output  
AS
BEGIN

 insert into SIAE_SiaeCounter (CounterType, IdentifierAK, ReferenceTime, Counter) 
 select @CounterType, @IdentifierAK, IsNull(@ReferenceTime,'Never'), 0
 where 
 0 = (select count(*) from SIAE_SiaeCounter with (READCOMMITTEDLOCK, ROWLOCK) where CounterType = @CounterType and IdentifierAK = @IdentifierAK and
  IsNull(@ReferenceTime,'NEVER') = IsNull(ReferenceTime,'NEVER'))


   update SIAE_SiaeCounter with (READCOMMITTEDLOCK, ROWLOCK)
   set    @Counter = Counter = Counter +1 
   where  CounterType = @CounterType and IdentifierAK = @IdentifierAK and
		IsNull(@ReferenceTime,'NEVER') = IsNull(ReferenceTime,'NEVER')

end
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Esposito</ADDEDBY>
			<SQLVERSION>1.748</SQLVERSION>
			<RMTRACKLINK>51967</RMTRACKLINK>
			<REASON>New table SiaeCounter for management of "Progressivo Abbonamento".</REASON>
			<TABLENAMES>SIAE_SiaeCounter=CounterId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>if not exists (select * from sys.tables WHERE NAME = 'SIAE_SiaeCounter')
begin
  Create table [SIAE_SiaeCounter]
  (
  	[CounterId] Integer Identity(1,1) NOT NULL, UNIQUE ([CounterId]),
	[CounterType] Smallint NOT NULL,
	[IdentifierAK] Varchar(32) NOT NULL,
	[ReferenceTime] Varchar(32) NOT NULL,
	[Counter] Integer NOT NULL,
	[LastUpdateGuid] Varchar(32) NULL,
  Primary Key ([CounterId])
 )
end

if not Exists(SELECT 1
              FROM sys.indexes 
              WHERE name='idxSiaeCounterAk' AND object_id = OBJECT_ID('SIAE_SiaeCounter'))                
begin
   Create Index [idxSiaeCounterAk] ON [SIAE_SiaeCounter] ([CounterType] ,[IdentifierAK] ,[ReferenceTime] )   
end

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>1.747</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>Add indexes on table SIAE_SiaeLog

			</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT> if not Exists(SELECT 1
               FROM sys.indexes 
               WHERE name='IdxCodiceAbbonamento' AND object_id = OBJECT_ID('SIAE_SiaeLog'))
 BEGIN
   Create Index [IdxCodiceAbbonamento] ON [SIAE_SiaeLog] ([CodiceAbbonamento] ,[Operazione]) 
 end
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AndreaDavanzo</ADDEDBY>
			<SQLVERSION>1.746</SQLVERSION>
			<RMTRACKLINK>49958</RMTRACKLINK>
			<REASON>Drop and create of DATA_NFCIdentifier table </REASON>
			<TABLENAMES>DATA_NFCIdentifier=IdentifierId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE [dbo].[DATA_NFCIdentifier] DROP CONSTRAINT [FK_DATA_NFCIdentifier_DATA_Media]
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DROP TABLE [dbo].[DATA_NFCIdentifier]
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE TABLE [dbo].[DATA_NFCIdentifier](
	[IdentifierId] [int] IDENTITY(1,1) NOT NULL,
	[MSISDN] [nvarchar](50) NOT NULL,
	[RecordId] [int] NOT NULL,
	[MediaId] [int] NOT NULL,
	[AuthId] [nvarchar](50) NULL,
	[RequestId] [int] NULL,
	[Status] [int] NULL,
	[Device] [int] NULL,
	[ErrorCode] [int] NULL,
	[ErrorDescription] [nvarchar](50) NULL,
	[LineState] [int] NULL,
	[ChangeStatusReason] [int] NULL,
	[DateTimeChange] [datetime] NULL,
	[DateTimeCall] [datetime] NULL,
	[ChangeLineStateReason] [int] NULL,
 CONSTRAINT [PK_DATA_NFCIdentifier] PRIMARY KEY CLUSTERED 
(
	[IdentifierId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE [dbo].[DATA_NFCIdentifier]  WITH CHECK ADD  CONSTRAINT [FK_DATA_NFCIdentifier_DATA_Media] FOREIGN KEY([MediaId])
REFERENCES [dbo].[DATA_Media] ([MediaId])
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE [dbo].[DATA_NFCIdentifier] CHECK CONSTRAINT [FK_DATA_NFCIdentifier_DATA_Media]
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE NONCLUSTERED INDEX [IX_DATA_NFCIdentifier_MSISDN] ON [dbo].[DATA_NFCIdentifier]
(
	[MSISDN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE NONCLUSTERED INDEX [IX_DATA_NFCIdentifier_RequestId] ON [dbo].[DATA_NFCIdentifier]
(
	[RequestId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.745</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>[0] add index on DATA_Account Relationship
[1] add index on DATA_Transaction Tax</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>if not Exists(SELECT 1
               FROM sys.indexes 
               WHERE name='IDX_DATA_AccountRelationshipSearch' AND object_id = OBJECT_ID('DATA_AccountRelationship'))
 BEGIN
   Create Index [IDX_DATA_AccountRelationshipSearch] ON [DATA_AccountRelationship] ([FatherAccountId] ,[ChildAccountId] ,[RelationType] ) 
 end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if not Exists(SELECT 1
               FROM sys.indexes 
               WHERE name='idxTransactiontax' AND object_id = OBJECT_ID('DATA_TransactionTax'))
 BEGIN
   Create Index [idxTransactiontax] ON [DATA_TransactionTax] ([TransactionId] ,[TaxId] ) 
end
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>1.744</SQLVERSION>
			<RMTRACKLINK>50910</RMTRACKLINK>
			<REASON>Empty number due DB model error 
Add FK not needed on table SIAE_Location</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>1.743</SQLVERSION>
			<RMTRACKLINK>50910</RMTRACKLINK>
			<REASON>SIAE - Change logic for table SIAE_Location

[0] Add column AccessConfigurationId on Table SIAE_Location
[1] Create support table for SIAE_Location
[2] Fill support table with records of original table SIAE_Location
[3] Clone records for each Siae_Location record and Admission profiles founded
[4] Update new records with correct data
[5] Rename Table SIAE_Location to SIAE_Location_OLD
[6] Rename Table SIAE_LocationTMP to SIAE_Location





			</REASON>
			<TABLENAMES>SIAE_Location=SiaeLocationId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>-- [0] Add column AccessConfigurationId on Table SIAE_Location

  if not exists(select * from sys.columns where Name = N'AccessConfigurationId' and Object_ID = Object_ID(N'SIAE_Location'))
    ALTER TABLE [dbo].[SIAE_Location] ADD [AccessConfigurationId] INT NULL

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>
-- [1] Create support table for SIAE_Location

if not exists (select * from sys.tables WHERE NAME = 'SIAE_Location_OLD')
begin

CREATE TABLE [dbo].[SIAE_LocationTMP] (

[SiaeLocationId] int IDENTITY(1, 1) NOT NULL,
[LocationId] [int] NOT NULL,
[CodiceLocale] [nvarchar](13) NOT NULL,
[Denominazione] [nvarchar](30) NOT NULL,
[Indirizzo] [nvarchar](100) NOT NULL,
[Citta] [nvarchar](20) NOT NULL,
[Provincia] [nvarchar](2) NOT NULL,
[Capienza] [int] NULL,
[AccessConfigurationId] [int] NULL,

  PRIMARY KEY CLUSTERED ([SiaeLocationId])
    WITH (
      PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF,
      ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON),      

  CONSTRAINT [fkSiaeLocationLocationId] FOREIGN KEY ([LocationId]) 
  REFERENCES [dbo].[CNF_Location] ([LocationId]) 
  ON UPDATE NO ACTION
  ON DELETE NO ACTION,

  CONSTRAINT [fkSiaeLocationAccessConfigurationId] FOREIGN KEY ([AccessConfigurationId]) 
  REFERENCES [dbo].[ADM_AccessConfiguration] ([AccessConfigurationId]) 
  ON UPDATE NO ACTION
  ON DELETE NO ACTION,

)
ON [PRIMARY];

end

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>-- [2] Fill support table with records of original table SIAE_Location

INSERT INTO SIAE_LocationTMP
 (
 [LocationId]
,[CodiceLocale]
,[Denominazione]
,[Indirizzo]
,[Citta]
,[Provincia]
 )
SELECT 
 [LocationId]
,[CodiceLocale]
,[Denominazione]
,[Indirizzo]
,[Citta]
,[Provincia]
FROM SIAE_Location

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>-- [3] Clone records for each Siae_Location record and Admission profiles founded 

insert into SIAE_LocationTMP
(
 LocationId
,CodiceLocale
,Denominazione
,Indirizzo
,Citta
,Provincia
,AccessConfigurationId
)

select distinct
  LocationId,
  '0000000000',
  '**',
  '**',
  '**',
  '**',
  AccessConfigurationId
from 
  ADM_AccessConfiguration

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>-- [4] Update new records with correct data

UPDATE SIAE_LocationTMP
SET 
   CodiceLocale = SOURCE_TBL.CodiceLocale
  ,Denominazione = SOURCE_TBL.Denominazione
  ,Indirizzo = SOURCE_TBL.Indirizzo
  ,Citta = SOURCE_TBL.Citta
  ,Provincia = SOURCE_TBL.Provincia
FROM
  (SELECT *
   FROM
   SIAE_LocationTMP 
   WHERE AccessConfigurationId is null 
  ) SOURCE_TBL

WHERE SIAE_LocationTMP.LocationId = SOURCE_TBL.LocationId

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>
-- [5] Rename Table SIAE_Location to SIAE_Location_OLD

 EXEC sp_rename N'[dbo].[SIAE_Location]', N'SIAE_Location_OLD', 'OBJECT'
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>-- [6] Rename Table SIAE_LocationTMP to SIAE_Location

 EXEC sp_rename N'[dbo].[SIAE_LocationTMP]', N'SIAE_Location', 'OBJECT' 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>1.742</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.2.9.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************
			</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>1.741</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.2.9.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************
			</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>1.740</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.2.9.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************
			</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>1.739</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.2.9.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************
			</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>1.738</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>
***********************************************************************************
 EMPTY PATCH - Can be used in release 7.2.9.X

PLEASE... if you want use this empty space, don't forget to fill the real patch number used in BETA
and check "if not exist..." in order to avoid apply twice same patch

***********************************************************************************
			</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>dapicella</ADDEDBY>
			<SQLVERSION>1.737</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>[0] Add index on table DATA_Reservation ReservationAK
[0] Add index on table DATA_Reservation ExternalResCode</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>if not Exists(SELECT 1
                FROM sys.indexes 
               WHERE name='IDX_DATA_Reservation_ReservationAK' AND object_id = OBJECT_ID('DATA_Reservation'))
 BEGIN              
CREATE NONCLUSTERED INDEX [IDX_DATA_Reservation_ReservationAK] ON [dbo].[DATA_Reservation]
(
	[ReservationAK]
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
 END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if not Exists(SELECT 1
                FROM sys.indexes 
               WHERE name='IDX_DATA_Reservation_ExternalResCode' AND object_id = OBJECT_ID('DATA_Reservation'))
 BEGIN              
CREATE NONCLUSTERED INDEX [IDX_DATA_Reservation_ExternalResCode] ON [dbo].[DATA_Reservation]
(
	[ExternalResCode]
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
 END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>1.736</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>[0] Add index on table DATA_SaleTax
[1] update stored procedure  spui_GetCounter</REASON>
			<TABLENAMES>DATA_SaleTax=SaleTaxId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>
if not Exists(SELECT 1
                FROM sys.indexes 
               WHERE name='idxSaleTax' AND object_id = OBJECT_ID('DATA_SaleTax'))
 BEGIN              
CREATE NONCLUSTERED INDEX [idxSaleTax] ON [dbo].[DATA_SaleTax]
(
	[SaleId] ASC,
	[TaxId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
 END

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>  
ALTER PROCEDURE [dbo].[spui_GetCounter]
 -- Add the parameters for the stored procedure here
 @CounterType smallint,
 @IdentifierAK varchar(32),
 @ReferenceTime varchar(32),
 @Counter integer output  
AS
BEGIN


 SET NOCOUNT ON;


 insert into DATA_Counter (CounterType, IdentifierAK, ReferenceTime, Counter) 
 select @CounterType, @IdentifierAK, IsNull(@ReferenceTime,'Never'), 0
 where 
 0 = (select count(*) from DATA_Counter with (READCOMMITTEDLOCK, ROWLOCK) where CounterType = @CounterType and IdentifierAK = @IdentifierAK and
  IsNull(@ReferenceTime,'NEVER') = IsNull(ReferenceTime,'NEVER'))


   update DATA_Counter with (READCOMMITTEDLOCK, ROWLOCK)
   set    @Counter = Counter = Counter +1 
   where  CounterType = @CounterType and IdentifierAK = @IdentifierAK and
		IsNull(@ReferenceTime,'NEVER') = IsNull(ReferenceTime,'NEVER')

end

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>francescosalvi</ADDEDBY>
			<SQLVERSION>1.735</SQLVERSION>
			<RMTRACKLINK>51086</RMTRACKLINK>
			<REASON>Added field  CNF_DocTemplate.DocTemplateGroup</REASON>
			<TABLENAMES>CNF_DocTemplate=DocTemplateId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE CNF_DocTemplate ADD DocTemplateGroup varchar(50)
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FedericoCaramella</ADDEDBY>
			<SQLVERSION>1.734</SQLVERSION>
			<RMTRACKLINK>50629</RMTRACKLINK>
			<REASON>[0] Added field Active on DATA_Coupon</REASON>
			<TABLENAMES>DATA_Coupon=CouponId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE DATA_Coupon ADD Active smallint NOT NULL DEFAULT 1
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if not exists (
SELECT * 
FROM sys.indexes 
WHERE name='IDX_DATA_AccountRelationshipSearch' AND object_id = OBJECT_ID('DATA_AccountRelationship'))


CREATE NONCLUSTERED INDEX IDX_DATA_AccountRelationshipSearch ON [dbo].[DATA_AccountRelationship]
(
 [FatherAccountId] ASC,
 ChildAccountId ASC,
 RelationType ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>OTNALO</ADDEDBY>
			<SQLVERSION>1.733</SQLVERSION>
			<RMTRACKLINK>51282</RMTRACKLINK>
			<REASON>[0] Added field  NoUserId on CNF_ExternalTicketRange</REASON>
			<TABLENAMES>CNF_ExternalTicketRange=ExternalTicketRangeId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>if exists (select * from sys.tables WHERE NAME = 'CNF_ExternalTicketRange')
begin
  if not exists(select * from sys.columns where Name = N'NoUserId' and Object_ID = Object_ID(N'CNF_ExternalTicketRange'))
    ALTER TABLE [dbo].[CNF_ExternalTicketRange] ADD [NoUserId] INT NULL
end



				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>rfabio</ADDEDBY>
			<SQLVERSION>1.732</SQLVERSION>
			<RMTRACKLINK>51592</RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES>RES_CNF_RequirementTemplate=RequirementTemplateId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table RES_CNF_RequirementTemplate add DuplicateResourceAllowed smallint not null default 0;
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FedericoCaramella</ADDEDBY>
			<SQLVERSION>1.731</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>FPK Export Views</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF OBJECT_ID('ExportNoPayTransactions', 'V') IS NOT NULL
  DROP VIEW ExportNoPayTransactions
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>create view ExportNoPayTransactions as
  SELECT 
   SI.SiteName, 
   S.SaleId, 
   TR.TransactionId, 
   TR.Completed, 
   TR.Encoded, 
   0 as PaymentId, 
   TR.SiteId,
   TR.TransactionAk, 
   TR.FTransactionDate, 
   WS.WorkstationAK, 
   US.UserCode, 
   OP.AreaCode, 
   TR.TransactionType, 
   LkTRType.Description as TransactionTypeDesc, 
   0 as PaymentType, 
   'NOPAY' as PaymentMethodDesc, 
   TR.Revenue as TransactionAmount, 
   CUR.ISOCode, 
   CUR.ExchangeRate, 
   'FALSE' as CREDIT, 
   RES.ReservationAK, 
   RES_AC.AccountId RES_AccountId, 
   RES_AC.AccountAk RES_AccountAk

 from DATA_Transaction TR (nolock) 
   inner join DATA_Sale S (nolock) on TR.SaleId = S.SaleId 
   inner join CNF_Workstation WS (nolock) on TR.WorkstationId = WS.WorkstationId 
   inner join CNF_User US (nolock) on TR.UserId = US.UserId 
   inner join CNF_OperatingArea OP (nolock) on TR.OperatingAreaId = OP.OperatingAreaId 
   inner join CNF_Site SI (nolock) on TR.SiteId = SI.SiteId 
   inner join CNF_LookUp LkTRType (nolock) on TR.TransactionType = LkTRType.ItemId 
      and LkTRType.LookUpTableId = 3 
   left outer join DATA_Reservation RES (nolock) on TR.SaleId = RES.SaleId 
   left outer join DATA_Account RES_AC (nolock) on RES.AccountId = RES_AC.AccountId 
   inner join CNF_Currency CUR (nolock) on CUR.CurrencyType = 1 
   left outer join DATA_Payment PAY (nolock) on TR.TransactionId = PAY.TransactionId 

where
          TR.Paid = 1
          and S.Paid = 1
          and PAY.PaymentId is null

          and TR.TransactionType &lt;&gt; 4

          and ( (    TR.TransactionType &lt;&gt; 7
          and TR.Quantity &gt; 0
          and TR.Items &gt; 0)
          or 
          (TR.TransactionType = 7
          and TR.Quantity = 0
          and TR.Items &gt; 0))

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF OBJECT_ID('ExportTicketReissue', 'V') IS NOT NULL
  DROP VIEW ExportTicketReissue
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>create view ExportTicketReissue as
SELECT
   TI.ItemId,
   CNF_Site.SiteName, 
   WS.WorkstationAK, 
   US.UserCode, 
   OP.AreaCode, 
   MC.MatrixCellId, 
   MS.ProductType, 
   MC.Code as ProductCode,
   TCK.TicketId, 
   SI.TicketId ReplacedTicketId, 
   SI.ItemTicketId VoidedTicketId, 
   LkTRType.Description as TransactionTypeDesc, 
   TR.TransactionId, 
   TR.TransactionDate, 
   TR.Completed, 
   TR.TransactionType,
   TR.SiteId 

 from DATA_TransactionItem TI (nolock) 
      inner join DATA_Transaction TR (nolock) on TI.TransactionId = TR.TransactionId 
      inner join DATA_SaleItem SI (nolock) on TI.SaleItemId = SI.SaleItemId 
      inner join CNF_Workstation WS (nolock) on TR.WorkstationId = WS.WorkstationId 
      inner join CNF_User US (nolock) on TR.UserId = US.UserId 
      inner join CNF_OperatingArea OP (nolock) on TR.OperatingAreaId = OP.OperatingAreaId 
      inner join CNF_Site (nolock) on TR.SiteId = CNF_Site.SiteId 
      inner join CNF_LookUp LkTRType (nolock) on TR.TransactionType = LkTRType.ItemId and LkTRType.LookUpTableId = 3

      inner join CNF_MatrixCell MC (nolock) on SI.MatrixCellId = MC.MatrixCellId 
      inner join CNF_MatrixSheet MS (nolock) on MC.MatrixSheetId = MS.MatrixSheetId 
 left outer join CNF_AttributeSet ASet (nolock) on ASet.AttributeSetId = MC.AttributeSetId 
 left outer join DATA_SaleItem2Ticket S2T (nolock) on SI.SaleItemId = S2T.SaleItemId 
 left outer join DATA_Ticket TCK (nolock) on TCK.TicketId = S2T.TicketId 
 WHERE TR.TransactionType = 4

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF OBJECT_ID('ExportTicketUsages', 'V') IS NOT NULL
  DROP VIEW ExportTicketUsages
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>create view ExportTicketUsages as
select    
   S.SiteName,
   TR.TransactionAK, 
   TR.TransactionType, 
   TU.UsageId, 
   FTU.UsageId as FirstUsageId, 
   TU.UsageDate, 
   WS.WorkstationAK, 
   'SYSTEM' as UserCode, 
   OP.AreaCode, 
   TU.UsageType, 
   lkUT.Description ActionType, 
   MC_Type.OptionValue as CardActionType, 
   MC.MatrixCellId, 
   MS.ProductType, 
   MC.Code as ProductCode,
   TCK.TicketId, 
   TCK.Serial, 
   TCK.Price as Amount, 
   CASE 
    WHEN (CNF_CostCenter_Validity.Percentage IS NULL AND CNF_CostCenter_Validity.Price IS NULL) THEN TCK.Price 
    WHEN (COALESCE(CNF_CostCenter_Validity.Percentage,0) &gt; 0) THEN TCK.Price * ((100-CNF_CostCenter_Validity.Percentage)/100) 
    WHEN (COALESCE(CNF_CostCenter_Validity.Price,0) &gt; 0)      THEN TCK.Price -CNF_CostCenter_Validity.Price 
   END Amount_c, 
   CASE 
    WHEN (CNF_CostCenter_Validity.Percentage IS NULL AND CNF_CostCenter_Validity.Price IS NULL) THEN 0 
    WHEN (COALESCE(CNF_CostCenter_Validity.Percentage,0) &gt; 0) THEN TCK.Price * (CNF_CostCenter_Validity.Percentage/100) 
    WHEN (COALESCE(CNF_CostCenter_Validity.Price,0) &gt; 0)      THEN CNF_CostCenter_Validity.Price 
   END ExternalAmount, 
   MC_Amount.OptionValue as StoredValue, 
   AC.AccountAk, 
   AC.AccountId, 
   RES.ReservationAK, 
   TU.ValidateResult
  from DATA_TicketUsage TU (nolock) 
      inner join (select MIN(UsageId) usageid,TicketID from DATA_TicketUsage with(nolock) group by TicketID ) FTU  on  FTU.TicketId = TU.TicketId 
      inner join DATA_Ticket TCK (nolock) on TU.TicketId = TCK.TicketId 
      inner join DATA_Transaction2Ticket T2T (nolock) on TCK.TicketId = T2T.TicketId and T2T.OperationType = 1
      inner join DATA_Transaction TR (nolock) on T2T.TransactionId = TR.TransactionId 
      inner join CNF_Workstation WS (nolock) on TU.WorkstationId = WS.WorkstationId 
      inner join CNF_OperatingArea OP (nolock) on WS.OperatingAreaId = OP.OperatingAreaId 
      inner join CNF_Site S (nolock) on WS.SiteId = S.SiteId 
      inner join CNF_MatrixCell MC (nolock) on TCK.MatrixCellId = MC.MatrixCellId 
      inner join CNF_MatrixSheet MS (nolock) on MC.MatrixSheetId = MS.MatrixSheetId 
 left outer join CNF_AttributeSet ASet (nolock) on ASet.AttributeSetId = MC.AttributeSetId 
 left outer join CNF_LookUp lkUT (nolock) on TU.UsageType = lkUT.ItemId and lkUT.LookUpTableId = 69
 left outer join DATA_Reservation RES (nolock) on TR.SaleId = RES.SaleId 
 left outer join DATA_Account AC (nolock) on RES.AccountId = AC.AccountId 
 left outer join DATA_TicketUsageOption MC_Amount (nolock) on TU.UsageId = MC_Amount.UsageId and MC_Amount.OptionType = 5
 left outer join DATA_TicketUsageOption MC_Type (nolock) on TU.UsageId = MC_Type.UsageId and MC_Type.OptionType = 4
 LEFT OUTER JOIN CNF_CostCenter_Validity (nolock) ON (CNF_CostCenter_Validity.SiteId           = S.SiteId
                                             AND CNF_CostCenter_Validity.MatrixCellId = MC.MatrixCellId)
 where 
   TU.ValidateResult &lt; 99
   and TR.TransactionType &lt;&gt; 4
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF OBJECT_ID('ExportTransactionItems', 'V') IS NOT NULL
  DROP VIEW ExportTransactionItems
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE VIEW ExportTransactionItems AS  
 select 
   SI.SaleItemId, 
   TI.ItemId, 
   abs(TI.Quantity) as Quantity, 
   TI.ProductType, 
   CNF_Site.SiteName, 
   TR.TransactionId, 
   TR.TransactionAK, 
   TR.TransactionDate, 
   TR.Completed,
   TR.Siteid, 
   WS.WorkstationAK, 
   US.UserCode, 
   OP.AreaCode, 
   LkTRType.Description as TransactionTypeDesc, 
   SI.MatrixCellId, 
   MC.Code as ProductCode,
   TCK.TicketId, 
   TCK.VoidType, 
   S2T.OperationType,
   case when TCK.PrintDateTime is null then TCK.FEncodeDate else TCK.PrintDateTime end as EncodeDateTime, 
   TI.TransactionItemOperation, 
   TI.UnitPrice, 
 CASE 
 WHEN (CNF_CostCenter_Validity.Percentage IS NULL AND CNF_CostCenter_Validity.Price IS NULL) THEN TI.UnitPrice 
   WHEN (COALESCE(CNF_CostCenter_Validity.Percentage,0) &gt; 0) THEN TI.UnitPrice * ((100-CNF_CostCenter_Validity.Percentage)/100) 
   WHEN (COALESCE(CNF_CostCenter_Validity.Price,0) &gt; 0)      THEN TI.UnitPrice -CNF_CostCenter_Validity.Price 
 END UnitPrice_c, 
 CASE 
   WHEN (CNF_CostCenter_Validity.Percentage IS NULL AND CNF_CostCenter_Validity.Price IS NULL) THEN 0 
   WHEN (COALESCE(CNF_CostCenter_Validity.Percentage,0) &gt; 0) THEN TI.UnitPrice * (CNF_CostCenter_Validity.Percentage/100) 
   WHEN (COALESCE(CNF_CostCenter_Validity.Price,0) &gt; 0)      THEN CNF_CostCenter_Validity.Price 
 END ExternalAmount, 
   TI.TotalAmount, 
 CASE 
 WHEN (CNF_CostCenter_Validity.Percentage IS NULL AND CNF_CostCenter_Validity.Price IS NULL) THEN TI.TotalAmount 
   WHEN (COALESCE(CNF_CostCenter_Validity.Percentage,0) &gt; 0) THEN TI.TotalAmount * ((100-CNF_CostCenter_Validity.Percentage)/100) 
   WHEN (COALESCE(CNF_CostCenter_Validity.Price,0) &gt; 0)      THEN TI.TotalAmount -CNF_CostCenter_Validity.Price 
 END TotalAmount_c, 
 CASE 
   WHEN (CNF_CostCenter_Validity.Percentage IS NULL AND CNF_CostCenter_Validity.Price IS NULL) THEN 0 
   WHEN (COALESCE(CNF_CostCenter_Validity.Percentage,0) &gt; 0) THEN TI.TotalAmount * (CNF_CostCenter_Validity.Percentage/100) 
   WHEN (COALESCE(CNF_CostCenter_Validity.Price,0) &gt; 0)      THEN CNF_CostCenter_Validity.Price 
 END ExternalAmount1, 
   TI.UnitRecharge, 
   AC.AccountAk, 
   AC.AccountId, 
   RES.ReservationAK, 
   TR.TransactionType 
 from DATA_TransactionItem TI (nolock) 
   inner join DATA_Transaction TR (nolock) on TI.TransactionId = TR.TransactionId 
   inner join DATA_SaleItem SI (nolock) on TI.SaleItemId = SI.SaleItemId 
   inner join CNF_Workstation WS (nolock) on TR.WorkstationId = WS.WorkstationId 
   inner join CNF_User US (nolock) on TR.UserId = US.UserId 
   inner join CNF_OperatingArea OP (nolock) on TR.OperatingAreaId = OP.OperatingAreaId 
   inner join CNF_Site (nolock) on TR.SiteId = CNF_Site.SiteId 
   inner join CNF_LookUp LkTRType (nolock) on TR.TransactionType = LkTRType.ItemId and LkTRType.LookUpTableId = 3
   inner join CNF_MatrixCell MC (nolock) on SI.MatrixCellId = MC.MatrixCellId 
   left outer join CNF_AttributeSet ASet (nolock) on ASet.AttributeSetId = MC.AttributeSetId 
   left outer join DATA_SaleItem2Ticket S2T (nolock) on SI.SaleItemId = S2T.SaleItemId

 left outer join DATA_Ticket TCK (nolock) on TCK.TicketId = S2T.TicketId 
             and TCK.VoidType in (0,1,102,107,108,109,111,125) 
 left outer join DATA_Reservation RES (nolock) on TR.SaleId = RES.SaleId or (RES.SaleId IN (SELECT SaleID FROM DATA_Transaction2Ticket (nolock)  
                  inner join DATA_Transaction (nolock)  on DATA_Transaction2Ticket.TransactionId = DATA_Transaction.TransactionId  
												 WHERE DATA_Transaction2Ticket.TicketId = TCK.TicketId))  
 left outer join DATA_Account AC (nolock) on RES.AccountId = AC.AccountId 
 LEFT OUTER JOIN CNF_CostCenter_Validity (nolock) ON (CNF_CostCenter_Validity.SiteId           = TR.SiteId 
                                    AND CNF_CostCenter_Validity.MatrixCellId = MC.MatrixCellId) 
  where  TR.TransactionType &lt;&gt;4 AND
         ((TI.ProductType = 1 and TCK.TicketId is not null) or 
         (TI.ProductType = 2))
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF OBJECT_ID('ExportTransactionPayments', 'V') IS NOT NULL
  DROP VIEW ExportTransactionPayments
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE VIEW ExportTransactionPayments AS 
   SELECT 
   SI.SiteName, 
   TR.TransactionAk, 
   PAY.PaymentId, 
   PAY.FPaymentDate, 
   WS.WorkstationAK, 
   US.UserCode, 
   OP.AreaCode, 
   LkTRType.Description as TransactionTypeDesc, 
   PM.Description as PaymentMethodDesc, 
   CNFPAYC.CCName, 
   PAYC.AuthorizationCode, 
   PAYC.DevResponseCode, 
   PAY.PaymentAmount, 
   TR.Revenue as TransactionAmount, 
   CREDIT = case when PAYCR.PaymentId &gt; 0 then 'TRUE' else 'FALSE' end, 
   TR.TransactionId, 
   TR.Completed, 
   TR.Encoded, 
   TR.Items, 
   TR.TransactionType, 
   PAY.PaymentType, 
   LkPAYType.Description as PaymentTypeDesc, 
   CUR.ISOCode, 
   PAY.ExchangeRate, 
   AC.AccountId, 
   AC.AccountAk, 
   V.VoucherCode, 
   RES.ReservationAK, 
   RES_AC.AccountId RES_AccountId, 
   RES_AC.AccountAk RES_AccountAk, 
   DEBT.PaymentId DEBT_ID, 
   DEBT_RES.ReservationAK DEBT_ReservationAK, 
   DEBT_V.VoucherCode DEBT_VoucherCode, 
   DEBT_AC.AccountId DEBT_AccountId, 
   DEBT_AC.AccountAk DEBT_AccountAk, 

   TR.FTransactionDate, 
   TR.SiteId
 from DATA_Payment PAY (nolock) 
   inner join DATA_Transaction TR (nolock) on TR.TransactionId = PAY.TransactionId 
   inner join CNF_PaymentMethod PM (nolock) on PAY.PaymentMethodId = PM.PaymentMethodId 
   inner join CNF_Workstation WS (nolock) on TR.WorkstationId = WS.WorkstationId 
   inner join CNF_User US (nolock) on TR.UserId = US.UserId 
   inner join CNF_OperatingArea OP (nolock) on TR.OperatingAreaId = OP.OperatingAreaId 
   inner join CNF_Site SI (nolock) on TR.SiteId = SI.SiteId 
   inner join CNF_LookUp LkTRType (nolock) on TR.TransactionType = LkTRType.ItemId and LkTRType.LookUpTableId = 3
   inner join CNF_LookUp LkPAYType (nolock) on PAY.PaymentType = LkPAYType.ItemId and LkPAYType.LookUpTableId = 7
   left outer join DATA_PaymentCard PAYC (nolock) on PAY.PaymentId = PAYC.PaymentId 
   left outer join CNF_PaymentCard CNFPAYC (nolock) on PAYC.PaymentCardId = CNFPAYC.PaymentCardId 
   left outer join DATA_PaymentCredit PAYCR (nolock) on PAY.PaymentId = PAYCR.PaymentId 
   left outer join DATA_Account AC (nolock) on PAYCR.AccountId = AC.AccountId 
   left outer join DATA_Voucher V (nolock) on PAYCR.EntityId = V.VoucherId and PAYCR.EntityTable = 186
   left outer join DATA_Reservation RES (nolock) on TR.SaleId = RES.SaleId 
   left outer join DATA_Account RES_AC (nolock) on RES.AccountId = RES_AC.AccountId 
   left outer join DATA_PaymentCredit DEBT (nolock) on PAY.TransactionId = DEBT.SettleTransactionId 
   left outer join DATA_Account DEBT_AC (nolock) on DEBT.AccountId = DEBT_AC.AccountId 
   left outer join DATA_Voucher DEBT_V (nolock) on DEBT.EntityId = DEBT_V.VoucherId and DEBT.EntityTable = 186
   left outer join DATA_Payment DEBT_PAY (nolock) on DEBT.PaymentId = DEBT_PAY.PaymentId 
   left outer join DATA_Transaction DEBT_TR (nolock) on DEBT_PAY.TransactionId = DEBT_TR.TransactionId 
   left outer join DATA_Reservation DEBT_RES (nolock) on DEBT_TR.SaleId = DEBT_RES.SaleId 
   inner join CNF_Currency CUR (nolock) on PAY.CurrencyId = CUR.CurrencyId 
WHERE (DEBT_TR.TransactionType &lt;&gt; 22 or DEBT_TR.TransactionType is null)
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> IF OBJECT_ID('ExportEncodedReservations', 'V') IS NOT NULL
  DROP VIEW ExportEncodedReservations
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>create view ExportEncodedReservations as
  SELECT 
   TR.TransactionId,
   TR.TransactionAK,
   TR.Completed,
   TR.SiteId,
   PAYTR.TransactionId PAYTrId, 
   PAYTR.TransactionAK PAYTrAK, 
   APPTR.TransactionId APPTrId, 
   APPTR.TransactionAK APPTrAK 
 from DATA_Transaction TR (nolock) 
   inner join DATA_Sale Sale (nolock) on TR.SaleId = Sale.SaleId 
   inner join DATA_Transaction PAYTR (nolock) on Sale.SaleId = PAYTR.SaleId 
     and PAYTR.Paid &gt; 0 and PAYTR.Encoded = 0 
     and PAYTR.TransactionType = 16
   inner join DATA_Transaction APPTR (nolock) on Sale.SaleId = APPTR.SaleId 
     and APPTR.Approved &gt; 0 and APPTR.Encoded = 0 
     and APPTR.TransactionType = 16
 WHERE TR.Encoded = 1 AND
       TR.Paid = 0
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>rfabio</ADDEDBY>
			<SQLVERSION>1.730</SQLVERSION>
			<RMTRACKLINK>51246</RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES>RES_CNF_RequirementTemplate=RequirementTemplateId
RES_CNF_Requirement=RequirementId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT> alter table RES_CNF_RequirementTemplate add OrigRequirementTemplateId Integer;

Alter table [RES_CNF_RequirementTemplate] add constraint RES_CNF_RequirementTemplate_OrigRequirementTemplateId foreign key([OrigRequirementTemplateId]) references [RES_CNF_RequirementTemplate] ([RequirementTemplateId]);

alter table RES_CNF_Requirement add OrigRequirementId Integer;

Alter table [RES_CNF_Requirement] add constraint RES_CNF_Requirement_OrigRequirementId foreign key([OrigRequirementId]) references [RES_CNF_Requirement] ([RequirementId]); 
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AndreaDavanzo</ADDEDBY>
			<SQLVERSION>1.729</SQLVERSION>
			<RMTRACKLINK>49958</RMTRACKLINK>
			<REASON>Drop and create of table DATA_NCFIdentifier due to a not copleted define of the primary key</REASON>
			<TABLENAMES>DATA_NFCIdentifier=IdentifierId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE [dbo].[DATA_NFCIdentifier] DROP CONSTRAINT [FK_DATA_NFCIdentifier_DATA_Media]
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DROP TABLE [dbo].[DATA_NFCIdentifier]
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE TABLE [dbo].[DATA_NFCIdentifier](
	[IdentifierId] [int] IDENTITY(1,1) NOT NULL,
	[MSISDN] [nvarchar](50) NOT NULL,
	[RecordId] [int] NOT NULL,
	[MediaId] [int] NOT NULL,
	[AuthId] [int] NULL,
	[IccId] [int] NULL,
	[RequestId] [int] NULL,
	[Status] [int] NULL,
	[Device] [int] NULL,
	[ErrorCode] [int] NULL,
	[ErrorDescription] [nvarchar](50) NULL,
	[ProviderId] [int] NULL,
	[ServiceId] [int] NULL,
	[Service_Version] [nvarchar](50) NULL,
	[Action] [int] NULL,
	[MMI_Action] [int] NULL,
	[MMI_Version] [nvarchar](50) NULL,
	[LineState] [int] NULL,
	[ChangeStatusReason] [int] NULL,
	[DateTimeChange] [datetime] NULL,
	[DateTimeCall] [datetime] NULL,
	[ChangeLineStateReason] [int] NULL,
 CONSTRAINT [PK_DATA_NFCIdentifier] PRIMARY KEY CLUSTERED 
(
	[IdentifierId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE [dbo].[DATA_NFCIdentifier]  WITH CHECK ADD  CONSTRAINT [FK_DATA_NFCIdentifier_DATA_Media] FOREIGN KEY([MediaId])
REFERENCES [dbo].[DATA_Media] ([MediaId])
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE [dbo].[DATA_NFCIdentifier] CHECK CONSTRAINT [FK_DATA_NFCIdentifier_DATA_Media]
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE UNIQUE NONCLUSTERED INDEX [IX_DATA_NFCIdentifier_MSISDN] ON [dbo].[DATA_NFCIdentifier]
(
	[MSISDN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE NONCLUSTERED INDEX [IX_DATA_NFCIdentifier_RequestId] ON [dbo].[DATA_NFCIdentifier]
(
	[RequestId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>andrealollobrigida</ADDEDBY>
			<SQLVERSION>1.728</SQLVERSION>
			<RMTRACKLINK>51545</RMTRACKLINK>
			<REASON>Table  RES_CNF_Resource
Added columns:
[0] ResourceCode VarChar(32) null
[1] Add constraint UNIQUE</REASON>
			<TABLENAMES>RES_CNF_Resource=ResourceId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>if exists (select * from sys.tables WHERE NAME = 'RES_CNF_Resource')
begin
  if not exists(select * from sys.columns where Name = N'ResourceCode' and Object_ID = Object_ID(N'RES_CNF_Resource'))
    ALTER TABLE [dbo].[RES_CNF_Resource] ADD [ResourceCode] varchar(32) NULL
end 
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AndreaDavanzo</ADDEDBY>
			<SQLVERSION>1.727</SQLVERSION>
			<RMTRACKLINK>49958</RMTRACKLINK>
			<REASON>[0] Column Reason renamed to ChangeStatusReason
[1] Added column ChangeLineStatusReason</REASON>
			<TABLENAMES>DATA_NFCIdentifier=IdentifierId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>if exists (select * from sys.tables WHERE NAME = 'DATA_NFCIdentifier')
begin
  if exists(select * from sys.columns where Name = N'Reason' and Object_ID = Object_ID(N'DATA_NFCIdentifier'))
    EXEC sp_RENAME 'DATA_NFCIdentifier.Reason' , 'ChangeStatusReason', 'COLUMN'
end 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if exists (select * from sys.tables WHERE NAME = 'DATA_NFCIdentifier')
begin
  if not exists(select * from sys.columns where Name = N'ChangeLineStateReason' and Object_ID = Object_ID(N'DATA_NFCIdentifier'))
    ALTER TABLE DATA_NFCIdentifier ADD ChangeLineStateReason INT NULL
end 
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AndreaDavanzo</ADDEDBY>
			<SQLVERSION>1.726</SQLVERSION>
			<RMTRACKLINK>49958</RMTRACKLINK>
			<REASON>Added columns:
[0] LineState
[1] Reason
[2] DateTimeChange
[3] DateTimeCall</REASON>
			<TABLENAMES>DATA_NFCIdentifier=IdentifierId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>if exists (select * from sys.tables WHERE NAME = 'DATA_NFCIdentifier')
begin
  if not exists(select * from sys.columns where Name = N'LineState' and Object_ID = Object_ID(N'DATA_NFCIdentifier'))
    ALTER TABLE DATA_NFCIdentifier ADD LineState INT NULL
end 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if exists (select * from sys.tables WHERE NAME = 'DATA_NFCIdentifier')
begin
  if not exists(select * from sys.columns where Name = N'Reason' and Object_ID = Object_ID(N'DATA_NFCIdentifier'))
    ALTER TABLE DATA_NFCIdentifier ADD Reason INT NULL
end 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if exists (select * from sys.tables WHERE NAME = 'DATA_NFCIdentifier')
begin
  if not exists(select * from sys.columns where Name = N'DateTimeChange' and Object_ID = Object_ID(N'DATA_NFCIdentifier'))
    ALTER TABLE DATA_NFCIdentifier ADD DateTimeChange DATETIME NULL
end 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if exists (select * from sys.tables WHERE NAME = 'DATA_NFCIdentifier')
begin
  if not exists(select * from sys.columns where Name = N'DateTimeCall' and Object_ID = Object_ID(N'DATA_NFCIdentifier'))
    ALTER TABLE DATA_NFCIdentifier ADD DateTimeCall DATETIME NULL
end 
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>andreadavanzo</ADDEDBY>
			<SQLVERSION>1.725</SQLVERSION>
			<RMTRACKLINK>49958</RMTRACKLINK>
			<REASON>Added new table DATA_CNFIdentifier per Expo
[0] Create table
[1] [2] Create constraints
[3] [4] [5] Create indexes</REASON>
			<TABLENAMES>DATA_NFCIdentifier=IdentifierId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>if not exists (select * from sys.tables WHERE NAME = 'DATA_NFCIdentifier')
begin
CREATE TABLE [DATA_NFCIdentifier](
	[IdentifierId] [int] NOT NULL,
	[MSISDN] [nvarchar](50) NOT NULL,
	[RecordId] [int] NOT NULL,
	[MediaId] [int] NOT NULL,
	[AuthId] [int] NULL,
	[IccId] [int] NULL,
	[RequestId] [int] NULL,
	[Status] [int] NULL,
	[Device] [int] NULL,
	[ErrorCode] [int] NULL,
	[ErrorDescription] [nvarchar](50) NULL,
	[ProviderId] [int] NULL,
	[ServiceId] [int] NULL,
	[Service_Version] [nvarchar](50) NULL,
	[Action] [int] NULL,
	[MMI_Action] [int] NULL,
	[MMI_Version] [nvarchar](50) NULL,
 CONSTRAINT [PK_DATA_NFCIdentifier] PRIMARY KEY CLUSTERED 
(
	[IdentifierId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE [dbo].[DATA_NFCIdentifier]  WITH CHECK ADD  CONSTRAINT [FK_DATA_NFCIdentifier_DATA_Media] FOREIGN KEY([MediaId])
REFERENCES [dbo].[DATA_Media] ([MediaId])

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE [dbo].[DATA_NFCIdentifier] CHECK CONSTRAINT [FK_DATA_NFCIdentifier_DATA_Media]
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE UNIQUE NONCLUSTERED INDEX [IX_DATA_NFCIdentifier_MediaId] ON [dbo].[DATA_NFCIdentifier]
(
	[MediaId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE UNIQUE NONCLUSTERED INDEX [IX_DATA_NFCIdentifier_MSISDN] ON [dbo].[DATA_NFCIdentifier]
(
	[MSISDN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE NONCLUSTERED INDEX [IX_DATA_NFCIdentifier_RequestId] ON [dbo].[DATA_NFCIdentifier]
(
	[RequestId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>rfabio</ADDEDBY>
			<SQLVERSION>1.724</SQLVERSION>
			<RMTRACKLINK>51246</RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES>RES_CNF_Requirement=RequirementId
RES_CNF_RequirementType=RequirementTypeId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [RES_CNF_Requirement] drop constraint RES_CNF_Requirement_DefaultChoice;

Alter table [RES_CNF_Requirement] drop column  DefaultChoiceRequirementId;

alter table RES_CNF_RequirementType add DefaultRequirementId integer;

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>rfabio</ADDEDBY>
			<SQLVERSION>1.723</SQLVERSION>
			<RMTRACKLINK>51246</RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES>RES_CNF_RequirementTemplate=RequirementTemplateId
RES_CNF_Requirement=RequirementId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table RES_CNF_RequirementTemplate add DefaultRequirementTemplateId integer;
alter table RES_CNF_Requirement add DefaultChoiceRequirementId integer;

Alter table [RES_CNF_Requirement] add constraint RES_CNF_Requirement_DefaultChoice foreign key([DefaultChoiceRequirementId]) references [RES_CNF_Requirement] ([RequirementId])   
Alter table [RES_CNF_RequirementTemplate] add constraint RES_CNF_RequirementTemplate_DefaultRequirementTemplate  foreign key([DefaultRequirementTemplateId]) references [RES_CNF_RequirementTemplate] ([RequirementTemplateId])   
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.722</SQLVERSION>
			<RMTRACKLINK>50289 </RMTRACKLINK>
			<REASON>CNF_PromotionPermission
[0] add filed Ticket Id
[1]add FK on TicketId</REASON>
			<TABLENAMES>CNF_PromotionPermission=PromotionPermissionId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_PromotionPermission
  add TicketId Integer NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> Alter table CNF_PromotionPermission 
 add  foreign key(TicketId) references DATA_Ticket (TicketId)  

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FedericoCaramella</ADDEDBY>
			<SQLVERSION>1.721</SQLVERSION>
			<RMTRACKLINK>50882</RMTRACKLINK>
			<REASON>ALTER VIEW  vwStock_Inventory</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>DROP VIEW [dbo].[vwStock_Inventory]




				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE VIEW [dbo].[vwStock_Inventory]
AS
SELECT        SCP.MinStock, SCP.MatrixCellId, SCP.SKU AS Product, dbo.STOCK_CNF_Warehouse.WarehouseId, dbo.STOCK_CNF_Um.Description AS Um, 
                         dbo.STOCK_CNF_Warehouse.Description AS WareHouse, SUM(inventory.qtyleft) AS qtyleft, SUM(inventory.qtyout) AS qtyout, SUM(inventory.qtytomove) 
                         AS qtytomove
FROM            (SELECT        MatrixCellId, WarehouseId, SUM(QtyLeft) AS qtyleft, 0 AS qtyout, 0 AS qtytomove
                          FROM            dbo.STOCK_Movement WITH (nolock)
                          WHERE        (InOut = 1)
                          GROUP BY MatrixCellId, WarehouseId
                          UNION
                          SELECT        MatrixCellId, WarehouseId, 0 AS Expr1, SUM(Qty) AS qtyout, SUM(Qty - QtyMoved) AS qtytomove
                          FROM            dbo.STOCK_Movement AS STOCK_Movement_2 WITH (nolock)
                          WHERE        (InOut = - 1) AND (MovementDate = DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0))
                          GROUP BY MatrixCellId, WarehouseId
                          UNION
                          SELECT        MatrixCellId, WarehouseId, 0 AS Expr1, SUM(- Qty) AS qtyout, 0 AS qtytomove
                          FROM            dbo.STOCK_Movement AS STOCK_Movement_1 WITH (nolock)
                          WHERE        (InOut = 1) and MovementType in (5,6) AND (MovementDate = DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0))
                          GROUP BY MatrixCellId, WarehouseId) AS inventory INNER JOIN
                         dbo.STOCK_CNF_Product AS SCP WITH (nolock) ON inventory.MatrixCellId = SCP.MatrixCellId INNER JOIN
                         dbo.STOCK_CNF_Warehouse WITH (nolock) ON inventory.WarehouseId = dbo.STOCK_CNF_Warehouse.WarehouseId INNER JOIN
                         dbo.STOCK_CNF_Um WITH (nolock) ON dbo.STOCK_CNF_Um.UmId = SCP.UmId
GROUP BY SCP.MinStock, SCP.MatrixCellId, SCP.SKU, dbo.STOCK_CNF_Warehouse.WarehouseId, dbo.STOCK_CNF_Um.Description, dbo.STOCK_CNF_Warehouse.Description
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.720</SQLVERSION>
			<RMTRACKLINK>50289 </RMTRACKLINK>
			<REASON>CNF_matrixCellInfo
[0] add ActivatePromotionIDS  

CNF_PromotionPermission
[1] add FromDate 
[2] add ToDate 
[3] add Type 
[4] update type
[5] set Type as not Null</REASON>
			<TABLENAMES>CNF_MatrixCellInfo=MatrixCellInfoId
CNF_PromotionPermission=PromotionPermissionId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_MatrixCellInfo
  add ActivatePromotionIDs Nvarchar(1000) NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_PromotionPermission
  add FromDate Datetime NULL

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> alter table CNF_PromotionPermission
 add ToDate Datetime NULL

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_PromotionPermission
   add ValidityType Smallint NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> update CNF_PromotionPermission 
   set ValidityType = 0
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_PromotionPermission
  alter column ValidityType Smallint NOT NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>1.719</SQLVERSION>
			<RMTRACKLINK>51369</RMTRACKLINK>
			<REASON>Add indexes:

0 - [SIAE_Log2Performance_SiaeLogId]
1 - [SIAE_Log2Performance_PerformanceId]
2 - [SIAE_SiaeLog_DataEmissione]

			</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>
if not Exists(SELECT 1
                FROM sys.indexes 
               WHERE name='SIAE_Log2Performance_SiaeLogId' AND object_id = OBJECT_ID('SIAE_Log2Performance'))
 BEGIN              

CREATE NONCLUSTERED INDEX [SIAE_Log2Performance_SiaeLogId]
ON [dbo].[SIAE_Log2Performance] ([SiaeLogId])
INCLUDE ([PerformanceId])

 END





				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>

if not Exists(SELECT 1
                FROM sys.indexes 
               WHERE name='SIAE_Log2Performance_PerformanceId' AND object_id = OBJECT_ID('SIAE_Log2Performance'))
 BEGIN              

CREATE NONCLUSTERED INDEX [SIAE_Log2Performance_PerformanceId]
ON [dbo].[SIAE_Log2Performance] ([PerformanceId])
INCLUDE ([SiaeLogId])

 END


				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>

if not Exists(SELECT 1
                FROM sys.indexes 
               WHERE name='SIAE_SiaeLog_DataEmissione' AND object_id = OBJECT_ID('SIAE_SiaeLog'))
 BEGIN              

CREATE NONCLUSTERED INDEX [SIAE_SiaeLog_DataEmissione]
ON [dbo].[SIAE_SiaeLog] ([DataEmissione])
INCLUDE ([SiaeLogId],[Operazione],[OrdinePosto],[CausaleRiduzione],[TipoTitolo],[PrezzoTitolo],[IvaTitolo],[PrezzoPrevendita],[Rateo],[IvaRateo],[RateoIntrattenimenti],[ImponibileIntrattenimenti],[IvaIntrattenimenti],[IvaRateoIntrattenimenti])


 END

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>rfabio</ADDEDBY>
			<SQLVERSION>1.718</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES>RES_CNF_Resource=ResourceId
RES_CNF_ResourceType=ResourceTypeId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table RES_CNF_Resource add SchedulerSort integer;
alter table RES_CNF_ResourceType add SchedulerSort integer;

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>rfabio</ADDEDBY>
			<SQLVERSION>1.717</SQLVERSION>
			<RMTRACKLINK>50157</RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create Index [idx_StockMovement_TempKey] ON [STOCK_Movement] ([TempLock] ) 
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>angelomangiaracina</ADDEDBY>
			<SQLVERSION>1.716</SQLVERSION>
			<RMTRACKLINK>50892</RMTRACKLINK>
			<REASON>  [0] Added column skipAccountPickup to DATA_AccountFinancial</REASON>
			<TABLENAMES>DATA_AccountFinancial=AccountId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT> alter table DATA_AccountFinancial add SkipAccountPickup Smallint Default 0 NOT NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>1.715</SQLVERSION>
			<RMTRACKLINK>50911</RMTRACKLINK>
			<REASON>[0] Added column EventId in SIAE_Category
[1] Added column PriceTableId in SIAE_Category
[2] Added column MatrixCellId in SIAE_Category
[3-6] Create table move data and then delete old one in order to change structure</REASON>
			<TABLENAMES>SIAE_Category=SiaeCategoryId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>


if not exists(select * from sys.columns 
            where Name = N'EventId' and Object_ID = Object_ID(N'SIAE_Category'))
begin
  ALTER TABLE SIAE_Category ADD EventId int NULL
end


				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>


if not exists(select * from sys.columns 
            where Name = N'PriceTableId' and Object_ID = Object_ID(N'SIAE_Category'))
begin
  ALTER TABLE SIAE_Category ADD PriceTableId int NULL
end



				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>

if not exists(select * from sys.columns 
            where Name = N'MatrixCellId' and Object_ID = Object_ID(N'SIAE_Category'))
begin
  ALTER TABLE SIAE_Category ADD MatrixCellId int NULL
end


				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>--SCRIPT TO ADD NEW FIELD TO SIAE_Category

if not exists (select * from sys.tables WHERE NAME = 'SIAE_Category_OLD')
begin


CREATE TABLE [dbo].[SIAE_CategoryTMP] (
  [SiaeCategoryId] int IDENTITY(1, 1) NOT NULL,
  [SeatCategoryId] int NULL,
  [Capienza] int NULL,
  [LimiteOmaggi] int NULL,
  [IvaOmaggiTitoli] float NOT NULL,
  [MatrixCellId] int NULL,
  [AttributeId] int NULL,
  [EventId] int NULL,
  [PriceTableId] int NULL,
  PRIMARY KEY CLUSTERED ([SiaeCategoryId])
    WITH (
      PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF,
      ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON),      
  CONSTRAINT [fkSiaeCategorySeatCategoryId1] FOREIGN KEY ([SeatCategoryId]) 
  REFERENCES [dbo].[CNF_SeatCategory] ([SeatCategoryId]) 
  ON UPDATE NO ACTION
  ON DELETE NO ACTION,

  CONSTRAINT [fkSiaeCategoryEventId] FOREIGN KEY ([EventId]) 
  REFERENCES [dbo].[CNF_Event] ([EventId]) 
  ON UPDATE NO ACTION
  ON DELETE NO ACTION,

  CONSTRAINT [fkSiaeCategoryPriceTableId] FOREIGN KEY ([PriceTableId]) 
  REFERENCES [dbo].[CNF_PriceTable] ([PriceTableId]) 
  ON UPDATE NO ACTION
  ON DELETE NO ACTION,  

  CONSTRAINT [fkSiaeCategoryMatrixCellId] FOREIGN KEY ([MatrixCellId]) 
  REFERENCES [dbo].[CNF_MatrixCell] ([MatrixCellId]) 
  ON UPDATE NO ACTION
  ON DELETE NO ACTION,  

  CONSTRAINT [fkSiaeCategoryAttributeId] FOREIGN KEY ([AttributeId]) 
  REFERENCES [dbo].[CNF_Attribute] ([AttributeId]) 
  ON UPDATE NO ACTION
  ON DELETE NO ACTION  

)
ON [PRIMARY];


end


				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>        --SCRIPT TO ADD NEW FIELD TO SIAE_Category


INSERT INTO SIAE_CategoryTMP
 (SIAE_CategoryTMP.Capienza,
  SIAE_CategoryTMP.SeatCategoryId,
  SIAE_CategoryTMP.IvaOmaggiTitoli,
  SIAE_CategoryTMP.LimiteOmaggi)
SELECT SIAE_Category.Capienza,
       SIAE_Category.SeatCategoryId,
       SIAE_Category.IvaOmaggiTitoli,
       SIAE_Category.LimiteOmaggi
 FROM SIAE_Category   




				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> 
 EXEC sp_rename N'[dbo].[SIAE_Category]', N'SIAE_Category_OLD', 'OBJECT'





				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>


 EXEC sp_rename N'[dbo].[SIAE_CategoryTMP]', N'SIAE_Category', 'OBJECT' 





				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>rfabio</ADDEDBY>
			<SQLVERSION>1.714</SQLVERSION>
			<RMTRACKLINK>50157</RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES>STOCK_Movement=MovementId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table STOCK_Movement add TempLock varchar(10)
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>andrealollobrigida</ADDEDBY>
			<SQLVERSION>1.713</SQLVERSION>
			<RMTRACKLINK>50943</RMTRACKLINK>
			<REASON>Added script for UDF Split</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>  create function split (@list varchar(max), @delimiter char(1))
  returns @shards table (value varchar(8000))
  with schemabinding
  as
  begin
    declare @i int;
    set @i = 0;
    while @i &lt;= len(@list)
    begin
      declare @n int;
      set @n = charindex(@delimiter, @list, @i);
      if 0 = @n
      begin
         set @n = len(@list);
      end
      insert into @shards (value) 
        values (substring(@list, @i, @n-@i+1));
      set @i = @n+1;
    end
    return;
  end
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AndreaDavanzo</ADDEDBY>
			<SQLVERSION>1.712</SQLVERSION>
			<RMTRACKLINK>50425</RMTRACKLINK>
			<REASON>[0] Changed the default value of the constraint from 1 to 0</REASON>
			<TABLENAMES>CNF_PriceTable=PriceTableId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>if exists(select * from sys.columns 
            where Name = N'PriceTableType' and Object_ID = Object_ID(N'CNF_PriceTable'))
begin
  declare @a nvarchar(100)

  select @a = name
  from sys.all_objects
  where parent_object_id = (
  select object_id
  from sys.all_objects
  where Object_ID = Object_ID(N'CNF_PriceTable')) 
  and type = 'D'

  EXEC('ALTER TABLE CNF_PriceTable DROP CONSTRAINT ' + @a)

  alter table CNF_PriceTable drop column PriceTableType

  ALTER TABLE CNF_PriceTable ADD PriceTableType smallint NULL 
  ALTER TABLE CNF_PriceTable ADD CONSTRAINT DF_PriceTableType default 0 for PriceTableType  

  update CNF_PriceTable set PriceTableType = 0
end
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AndreaDavanzo</ADDEDBY>
			<SQLVERSION>1.711</SQLVERSION>
			<RMTRACKLINK>50425</RMTRACKLINK>
			<REASON>[0] Added column WebPriceTableId to CNF_Performance
[1] Added column PriceTableType to CNF_PriceTable</REASON>
			<TABLENAMES>CNF_Performance=PerformanceId
CNF_PriceTable=PriceTableId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>if not exists(select * from sys.columns 
            where Name = N'WebPriceTableId' and Object_ID = Object_ID(N'CNF_Performance'))
begin
  ALTER TABLE CNF_Performance ADD WebPriceTableId int NULL
  ALTER TABLE CNF_Performance ADD constraint fkPerformanceDefaulPriceTable foreign key([WebPriceTableId]) references [CNF_PriceTable] ([PriceTableId])
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if not exists(select * from sys.columns 
            where Name = N'PriceTableType' and Object_ID = Object_ID(N'CNF_PriceTable'))
begin
  ALTER TABLE CNF_PriceTable ADD PriceTableType smallint NOT NULL default 1
end
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>rfabio</ADDEDBY>
			<SQLVERSION>1.710</SQLVERSION>
			<RMTRACKLINK>50689</RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES>RES_CNF_Resource=ResourceId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table RES_CNF_Resource add Expired smallint; 
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>rfabio</ADDEDBY>
			<SQLVERSION>1.709</SQLVERSION>
			<RMTRACKLINK>49831</RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES>DATA_Reservation=SaleId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Reservation add batchcode varchar(30);
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.708</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES>DATA_Ticket=TicketId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Ticket
  add ExternalReferenceId Nvarchar(250) NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FedericoCaramella</ADDEDBY>
			<SQLVERSION>1.707</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES>RES_CNF_Requirement=RequirementId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE RES_CNF_Requirement Add CreatedBySystem smallint NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FedericoCaramella</ADDEDBY>
			<SQLVERSION>1.706</SQLVERSION>
			<RMTRACKLINK>50559</RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES>CNF_ExtCardTypePermission=ExtCardTypePermissionId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>if not exists (select * from sys.tables WHERE NAME = 'CNF_ExtCardTypePermission')
begin
Create table [CNF_ExtCardTypePermission]
(
	[ExtCardTypePermissionId] Integer Identity(1,1) NOT NULL,
	[ExternalCardTypeId] Integer NOT NULL,
	[SiteId] Integer NULL,
	[OperatingAreaId] Integer NULL,
	[WorkstationId] Integer NULL,
	[UserGroupId] Integer NULL,
	[UserId] Integer NULL,
	[AccountId] Integer NULL,
	[DmgCategoryId] Integer NULL,
	[Allow] Smallint NULL,
Primary Key ([ExtCardTypePermissionId])
) 
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if not exists (SELECT
    K_Table = FK.TABLE_NAME,
    FK_Column = CU.COLUMN_NAME,
    PK_Table = PK.TABLE_NAME,
    PK_Column = PT.COLUMN_NAME,
    Constraint_Name = C.CONSTRAINT_NAME
FROM
    INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK
    ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK
    ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU
    ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
INNER JOIN (
            SELECT
                i1.TABLE_NAME,
                i2.COLUMN_NAME
            FROM
                INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1
            INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2
                ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME
            WHERE
                i1.CONSTRAINT_TYPE = 'PRIMARY KEY'
           ) PT
    ON PT.TABLE_NAME = PK.TABLE_NAME

where FK.TABLE_NAME = 'CNF_ExtCardTypePermission' and CU.COLUMN_NAME = 'ExternalCardTypeId' )
begin
Alter table CNF_ExtCardTypePermission add foreign key(ExternalCardTypeId) 
references CNF_ExternalCardType (ExternalCardTypeId) on update no action on delete no action
end

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if not exists (SELECT
    K_Table = FK.TABLE_NAME,
    FK_Column = CU.COLUMN_NAME,
    PK_Table = PK.TABLE_NAME,
    PK_Column = PT.COLUMN_NAME,
    Constraint_Name = C.CONSTRAINT_NAME
FROM
    INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK
    ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK
    ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU
    ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
INNER JOIN (
            SELECT
                i1.TABLE_NAME,
                i2.COLUMN_NAME
            FROM
                INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1
            INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2
                ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME
            WHERE
                i1.CONSTRAINT_TYPE = 'PRIMARY KEY'
           ) PT
    ON PT.TABLE_NAME = PK.TABLE_NAME

where FK.TABLE_NAME = 'CNF_ExtCardTypePermission' and CU.COLUMN_NAME = 'SiteId' )
begin
 Alter table CNF_ExtCardTypePermission add foreign key(SiteId) references 
 CNF_Site (SiteId) on update no action on delete no action
end

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if not exists (SELECT
    K_Table = FK.TABLE_NAME,
    FK_Column = CU.COLUMN_NAME,
    PK_Table = PK.TABLE_NAME,
    PK_Column = PT.COLUMN_NAME,
    Constraint_Name = C.CONSTRAINT_NAME
FROM
    INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK
    ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK
    ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU
    ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
INNER JOIN (
            SELECT
                i1.TABLE_NAME,
                i2.COLUMN_NAME
            FROM
                INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1
            INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2
                ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME
            WHERE
                i1.CONSTRAINT_TYPE = 'PRIMARY KEY'
           ) PT
    ON PT.TABLE_NAME = PK.TABLE_NAME

where FK.TABLE_NAME = 'CNF_ExtCardTypePermission' and CU.COLUMN_NAME = 'OperatingAreaId' )
begin
Alter table CNF_ExtCardTypePermission add foreign key(OperatingAreaId) 
references CNF_OperatingArea (OperatingAreaId) on update no action on delete no action
end



				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if not exists (SELECT
    K_Table = FK.TABLE_NAME,
    FK_Column = CU.COLUMN_NAME,
    PK_Table = PK.TABLE_NAME,
    PK_Column = PT.COLUMN_NAME,
    Constraint_Name = C.CONSTRAINT_NAME
FROM
    INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK
    ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK
    ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU
    ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
INNER JOIN (
            SELECT
                i1.TABLE_NAME,
                i2.COLUMN_NAME
            FROM
                INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1
            INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2
                ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME
            WHERE
                i1.CONSTRAINT_TYPE = 'PRIMARY KEY'
           ) PT
    ON PT.TABLE_NAME = PK.TABLE_NAME

where FK.TABLE_NAME = 'CNF_ExtCardTypePermission' and CU.COLUMN_NAME = 'WorkstationId' )
begin
Alter table CNF_ExtCardTypePermission add foreign key(WorkstationId) 
references CNF_Workstation (WorkstationId) on update no action on delete no action
end

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if not exists (SELECT
    K_Table = FK.TABLE_NAME,
    FK_Column = CU.COLUMN_NAME,
    PK_Table = PK.TABLE_NAME,
    PK_Column = PT.COLUMN_NAME,
    Constraint_Name = C.CONSTRAINT_NAME
FROM
    INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK
    ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK
    ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU
    ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
INNER JOIN (
            SELECT
                i1.TABLE_NAME,
                i2.COLUMN_NAME
            FROM
                INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1
            INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2
                ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME
            WHERE
                i1.CONSTRAINT_TYPE = 'PRIMARY KEY'
           ) PT
    ON PT.TABLE_NAME = PK.TABLE_NAME

where FK.TABLE_NAME = 'CNF_ExtCardTypePermission' and CU.COLUMN_NAME = 'UserGroupId' )
begin
Alter table CNF_ExtCardTypePermission add foreign key(UserGroupId) 
references CNF_UserGroup (UserGroupId) on update no action on delete no action
end



				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if not exists (SELECT
    K_Table = FK.TABLE_NAME,
    FK_Column = CU.COLUMN_NAME,
    PK_Table = PK.TABLE_NAME,
    PK_Column = PT.COLUMN_NAME,
    Constraint_Name = C.CONSTRAINT_NAME
FROM
    INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK
    ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK
    ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU
    ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
INNER JOIN (
            SELECT
                i1.TABLE_NAME,
                i2.COLUMN_NAME
            FROM
                INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1
            INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2
                ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME
            WHERE
                i1.CONSTRAINT_TYPE = 'PRIMARY KEY'
           ) PT
    ON PT.TABLE_NAME = PK.TABLE_NAME

where FK.TABLE_NAME = 'CNF_ExtCardTypePermission' and CU.COLUMN_NAME = 'UserId' )
begin
Alter table CNF_ExtCardTypePermission add foreign key(UserId) 
references CNF_User (UserId) on update no action on delete no action
end



				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if not exists (SELECT
    K_Table = FK.TABLE_NAME,
    FK_Column = CU.COLUMN_NAME,
    PK_Table = PK.TABLE_NAME,
    PK_Column = PT.COLUMN_NAME,
    Constraint_Name = C.CONSTRAINT_NAME
FROM
    INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK
    ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK
    ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU
    ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
INNER JOIN (
            SELECT
                i1.TABLE_NAME,
                i2.COLUMN_NAME
            FROM
                INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1
            INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2
                ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME
            WHERE
                i1.CONSTRAINT_TYPE = 'PRIMARY KEY'
           ) PT
    ON PT.TABLE_NAME = PK.TABLE_NAME

where FK.TABLE_NAME = 'CNF_ExtCardTypePermission' and CU.COLUMN_NAME = 'DmgCategoryId' )
begin
Alter table CNF_ExtCardTypePermission add foreign key(DmgCategoryId) 
references CNF_DmgCategory (DmgCategoryId) on update no action on delete no action
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if not exists (SELECT
    K_Table = FK.TABLE_NAME,
    FK_Column = CU.COLUMN_NAME,
    PK_Table = PK.TABLE_NAME,
    PK_Column = PT.COLUMN_NAME,
    Constraint_Name = C.CONSTRAINT_NAME
FROM
    INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK
    ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK
    ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU
    ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
INNER JOIN (
            SELECT
                i1.TABLE_NAME,
                i2.COLUMN_NAME
            FROM
                INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1
            INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2
                ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME
            WHERE
                i1.CONSTRAINT_TYPE = 'PRIMARY KEY'
           ) PT
    ON PT.TABLE_NAME = PK.TABLE_NAME

where FK.TABLE_NAME = 'CNF_ExtCardTypePermission' and CU.COLUMN_NAME = 'AccountId' )
begin
Alter table CNF_ExtCardTypePermission add foreign key(AccountId) 
references DATA_Account (AccountId) on update no action on delete no action
end

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FedericoCaramella</ADDEDBY>
			<SQLVERSION>1.705</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>RES_CNF_RequirementTemplate
 Add CreatedBySystem</REASON>
			<TABLENAMES>RES_CNF_RequirementTemplate=RequirementTemplateId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE RES_CNF_RequirementTemplate Add CreatedBySystem smallint NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FedericoCaramella</ADDEDBY>
			<SQLVERSION>1.704</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES>CNF_ExternalCardType=ExternalCardTypeId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>if not exists(select * from sys.columns 
            where Name = N'MatrixCellId' and Object_ID = Object_ID(N'CNF_ExternalCardType'))
begin
  ALTER TABLE CNF_ExternalCardType Add MatrixCellId int NULL  
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if not exists (SELECT
    K_Table = FK.TABLE_NAME,
    FK_Column = CU.COLUMN_NAME,
    PK_Table = PK.TABLE_NAME,
    PK_Column = PT.COLUMN_NAME,
    Constraint_Name = C.CONSTRAINT_NAME
FROM
    INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK
    ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK
    ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU
    ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
INNER JOIN (
            SELECT
                i1.TABLE_NAME,
                i2.COLUMN_NAME
            FROM
                INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1
            INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2
                ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME
            WHERE
                i1.CONSTRAINT_TYPE = 'PRIMARY KEY'
           ) PT
    ON PT.TABLE_NAME = PK.TABLE_NAME

where FK.TABLE_NAME = 'CNF_ExternalCardType' and CU.COLUMN_NAME = 'MatrixCellId' )
begin
  ALTER TABLE [dbo].[CNF_ExternalCardType]  WITH CHECK ADD FOREIGN KEY([MatrixCellId])
  REFERENCES [dbo].[CNF_MatrixCell] ([MatrixCellId])
end
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FedericoCaramella</ADDEDBY>
			<SQLVERSION>1.703</SQLVERSION>
			<RMTRACKLINK>4973</RMTRACKLINK>
			<REASON>[0] Create Table [CNF_ExternalCardType]
[1] Add Foreign Key SystemId
[2] Add Foreign Key DriverId</REASON>
			<TABLENAMES>CNF_ExternalCardType=ExternalCardTypeId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>if not exists (select * from sys.tables WHERE NAME = 'CNF_ExternalCardType')
begin
CREATE TABLE [dbo].[CNF_ExternalCardType](
	[ExternalCardTypeId] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
	[Code] [nchar](8) NOT NULL,
	[Name] [nvarchar](50) NOT NULL,
	[Price] [float] NULL,
	[SystemId] [int] NOT NULL,
	[DriverId] [int] NOT NULL,
PRIMARY KEY CLUSTERED 
(
	[ExternalCardTypeId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
end

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if not exists (SELECT
    K_Table = FK.TABLE_NAME,
    FK_Column = CU.COLUMN_NAME,
    PK_Table = PK.TABLE_NAME,
    PK_Column = PT.COLUMN_NAME,
    Constraint_Name = C.CONSTRAINT_NAME
FROM
    INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK
    ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK
    ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU
    ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
INNER JOIN (
            SELECT
                i1.TABLE_NAME,
                i2.COLUMN_NAME
            FROM
                INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1
            INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2
                ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME
            WHERE
                i1.CONSTRAINT_TYPE = 'PRIMARY KEY'
           ) PT
    ON PT.TABLE_NAME = PK.TABLE_NAME

where FK.TABLE_NAME = 'CNF_ExternalCardType' and CU.COLUMN_NAME = 'SystemId' )
begin
ALTER TABLE [dbo].[CNF_ExternalCardType]  WITH CHECK ADD FOREIGN KEY([SystemId])
REFERENCES [dbo].[CNF_System] ([SystemId])
end



				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if not exists (SELECT
    K_Table = FK.TABLE_NAME,
    FK_Column = CU.COLUMN_NAME,
    PK_Table = PK.TABLE_NAME,
    PK_Column = PT.COLUMN_NAME,
    Constraint_Name = C.CONSTRAINT_NAME
FROM
    INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK
    ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK
    ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU
    ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
INNER JOIN (
            SELECT
                i1.TABLE_NAME,
                i2.COLUMN_NAME
            FROM
                INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1
            INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2
                ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME
            WHERE
                i1.CONSTRAINT_TYPE = 'PRIMARY KEY'
           ) PT
    ON PT.TABLE_NAME = PK.TABLE_NAME

where FK.TABLE_NAME = 'CNF_ExternalCardType' and CU.COLUMN_NAME = 'DriverId' )
begin
ALTER TABLE [dbo].[CNF_ExternalCardType]  WITH CHECK ADD FOREIGN KEY([DriverId])
REFERENCES [dbo].[CNF_Driver] ([DriverId])
end



				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>OTNALO</ADDEDBY>
			<SQLVERSION>1.702</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>[0]Added new field color to to RES_ScheduleType</REASON>
			<TABLENAMES>RES_ScheduleType=ScheduleTypeId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE [RES_ScheduleType]
ADD [Color] varchar(32) NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FedericoCaramella</ADDEDBY>
			<SQLVERSION>1.701</SQLVERSION>
			<RMTRACKLINK>4249</RMTRACKLINK>
			<REASON>Add AdditionalFilters </REASON>
			<TABLENAMES>DATA_triggerItem=TriggerItemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_triggerItem Add AdditionalFilters ntext null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>rfabio</ADDEDBY>
			<SQLVERSION>1.700</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES>RES_CNF_ResourceType=ResourceTypeId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>if not exists(select * from sys.columns 
            where Name = N'ImageUri' and Object_ID = Object_ID(N'RES_CNF_ResourceType'))
begin
  alter table RES_CNF_ResourceType add ImageUri VarChar(50)  
end
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>rfabio</ADDEDBY>
			<SQLVERSION>1.699</SQLVERSION>
			<RMTRACKLINK>5005</RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES>CNF_PromotionProduct=PromotionProductId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_PromotionProduct add DiscPerc Float;
alter table CNF_PromotionProduct add PromotionPrice Money;
alter table CNF_PromotionProduct add DiscForfait Money;
alter table CNF_PromotionProduct add ReplaceMatrixCellId integer;
alter table CNF_PromotionProduct add ReplaceAttributeId integer;
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>andreadavanzo</ADDEDBY>
			<SQLVERSION>1.698</SQLVERSION>
			<RMTRACKLINK>5032</RMTRACKLINK>
			<REASON>[0]Added 5 custom columns to CNF_Seat
			</REASON>
			<TABLENAMES>CNF_Seat=SeatId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>if not exists(select * from sys.columns 
            where Name = N'Custom1' and Object_ID = Object_ID(N'CNF_Seat'))
begin
  alter table CNF_Seat add Custom1 NVarChar(250) Null  
end

if not exists(select * from sys.columns 
            where Name = N'Custom2' and Object_ID = Object_ID(N'CNF_Seat'))
begin
  alter table CNF_Seat add Custom2 NVarChar(250) Null  
end

if not exists(select * from sys.columns 
            where Name = N'Custom3' and Object_ID = Object_ID(N'CNF_Seat'))
begin
  alter table CNF_Seat add Custom3 NVarChar(250) Null  
end

if not exists(select * from sys.columns 
            where Name = N'Custom4' and Object_ID = Object_ID(N'CNF_Seat'))
begin
  alter table CNF_Seat add Custom4 NVarChar(250) Null  
end

if not exists(select * from sys.columns 
            where Name = N'Custom5' and Object_ID = Object_ID(N'CNF_Seat'))
begin
  alter table CNF_Seat add Custom5 NVarChar(250) Null  
end
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>rfabio</ADDEDBY>
			<SQLVERSION>1.697</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>Resource Management</REASON>
			<TABLENAMES>RES_CNF_ResourceType=ResourceTypeId
RES_CNF_Resource=ResourceId
RES_CNF_ScheduleTypeAllowed=ScheduleTypeAllowedId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table RES_CNF_ResourceType add WarnMaxDayHours int;
alter table RES_CNF_ResourceType add MaxDayHours int;

alter table RES_CNF_Resource add WarnMaxDayHours int;
alter table RES_CNF_Resource add MaxDayHours int;


Create table [RES_CNF_ScheduleTypeAllowed]
(
	[ScheduleTypeAllowedId] Integer Identity(1,1) NOT NULL,
	[ScheduleTypeId] Integer NOT NULL,
	[ResourceTypeId] Integer NOT NULL,
Primary Key ([ScheduleTypeAllowedId])
) 


Alter table [RES_CNF_ScheduleTypeAllowed] add constraint FK_RES_CNF_ScheduleTypeAllowed_ResourceType foreign key([ResourceTypeId]) references [RES_CNF_ResourceType] ([ResourceTypeId])   
Alter table [RES_CNF_ScheduleTypeAllowed] add constraint FK_RES_CNF_ScheduleTypeAllowed_ScheduleType foreign key([ScheduleTypeId]) references [RES_ScheduleType] ([ScheduleTypeId])   





				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>1.696</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>Add new index for table SIAE_SiaeLog</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT> if not Exists(SELECT 1
                FROM sys.indexes 
               WHERE name=N'IDX_SIAE_SiaeLog_TicketId' AND object_id = OBJECT_ID('SIAE_SiaeLog'))
BEGIN              
  CREATE NONCLUSTERED INDEX [IDX_SIAE_SiaeLog_TicketId] ON [dbo].[SIAE_SiaeLog]
  ([TicketId])
 END

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>rfabio</ADDEDBY>
			<SQLVERSION>1.695</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES>RES_CNF_RequirementTemplateItem=RequirementTemplateItemId</TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>rfabio</ADDEDBY>
			<SQLVERSION>1.694</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES>RES_CNF_Requirement=RequirementId
RES_CNF_RequirementTemplateItem=RequirementTemplateItemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @ConstraintName nvarchar(200)
SELECT @ConstraintName = Name FROM SYS.DEFAULT_CONSTRAINTS
WHERE PARENT_OBJECT_ID = OBJECT_ID('RES_CNF_RequirementTemplateItem')
AND PARENT_COLUMN_ID = (SELECT column_id FROM sys.columns
                        WHERE NAME = N'AllocateOnCreation'
                        AND object_id = OBJECT_ID(N'RES_CNF_RequirementTemplateItem'))
IF @ConstraintName IS NOT NULL
begin
EXEC('ALTER TABLE RES_CNF_RequirementTemplateItem  DROP CONSTRAINT ' + @ConstraintName)
end

alter table RES_CNF_RequirementTemplateItem drop column AllocateOnCreation;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @ConstraintName nvarchar(200)  
SELECT @ConstraintName = Name FROM SYS.DEFAULT_CONSTRAINTS
WHERE PARENT_OBJECT_ID = OBJECT_ID('RES_CNF_RequirementTemplateItem')
AND PARENT_COLUMN_ID = (SELECT column_id FROM sys.columns
                        WHERE NAME = N'MinutesBeforePerf'
                        AND object_id = OBJECT_ID(N'RES_CNF_RequirementTemplateItem'))
IF @ConstraintName IS NOT NULL
begin
EXEC('ALTER TABLE RES_CNF_RequirementTemplateItem  DROP CONSTRAINT ' + @ConstraintName)
end

alter table RES_CNF_RequirementTemplateItem drop column  MinutesBeforePerf;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @ConstraintName nvarchar(200)   
SELECT @ConstraintName = Name FROM SYS.DEFAULT_CONSTRAINTS
WHERE PARENT_OBJECT_ID = OBJECT_ID('RES_CNF_RequirementTemplateItem')
AND PARENT_COLUMN_ID = (SELECT column_id FROM sys.columns
                        WHERE NAME = N'MinutesAfterPerf'
                        AND object_id = OBJECT_ID(N'RES_CNF_RequirementTemplateItem'))
IF @ConstraintName IS NOT NULL
begin
EXEC('ALTER TABLE RES_CNF_RequirementTemplateItem  DROP CONSTRAINT ' + @ConstraintName)
end
alter table RES_CNF_RequirementTemplateItem drop column  MinutesAfterPerf;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @ConstraintName nvarchar(200)         
SELECT @ConstraintName = Name FROM SYS.DEFAULT_CONSTRAINTS
WHERE PARENT_OBJECT_ID = OBJECT_ID('RES_CNF_RequirementTemplateItem')
AND PARENT_COLUMN_ID = (SELECT column_id FROM sys.columns
                        WHERE NAME = N'NotWhilePerformance'
                        AND object_id = OBJECT_ID(N'RES_CNF_RequirementTemplateItem'))
IF @ConstraintName IS NOT NULL
begin
EXEC('ALTER TABLE RES_CNF_RequirementTemplateItem  DROP CONSTRAINT ' + @ConstraintName)
end

alter table RES_CNF_RequirementTemplateItem drop column  NotWhilePerformance;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>
alter table RES_CNF_Requirement add AllocateOnCreation smallint default 0;
alter table RES_CNF_Requirement add MinutesBeforePerf  integer default 0;
alter table RES_CNF_Requirement add MinutesAfterPerf   integer default 0;
alter table RES_CNF_Requirement add NotWhilePerformance smallint default 0;
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FedericoCaramella</ADDEDBY>
			<SQLVERSION>1.693</SQLVERSION>
			<RMTRACKLINK>4900</RMTRACKLINK>
			<REASON>CREATE TABLE OFF_Performance]
			</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE TABLE [OFF_Performance](
	[PerformanceId] [int] NOT NULL,
	[EventId] [int] NOT NULL,
	[PriceTableId] [int] NULL,
	[PerformanceAK] [varchar](32) NOT NULL,
	[PerfDateTime] [datetime] NOT NULL,
	[AccessConfigurationId] [int] NULL,
	[Status] [smallint] NOT NULL,
	[PerfTurno] [varchar](10) NULL,
	[TimeOpening] [int] NOT NULL,
	[TimeLimit] [int] NOT NULL,
	[PerformanceEnd] [datetime] NULL,
	[PurgeDeltaTime] [datetime] NULL,
	[OnSaleFrom] [datetime] NULL,
	[OnSaleUntil] [datetime] NULL,
	[MoneyCardId] [int] NULL,
	[MoneyCardCost] [float] NULL,
	[DmgCategoryId] [int] NULL,
	[PerformanceCode] [nvarchar](100) NULL,
	[BlockPerformance] [smallint] NOT NULL,
	[MinonScreen] [int] NULL,
	[PerformanceName] [nvarchar](100) NULL,
	[BlockPerformanceOnSale] [smallint] NOT NULL,
	[OpeningTime] [datetime] NOT NULL,
	[ClosingTime] [datetime] NOT NULL
)
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FedericoCaramella</ADDEDBY>
			<SQLVERSION>1.692</SQLVERSION>
			<RMTRACKLINK>4900</RMTRACKLINK>
			<REASON>Table CNF_ExternalTicketRange
[0]Added column OnlyOffline</REASON>
			<TABLENAMES>CNF_ExternalTicketRange=ExternalTicketRangeId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_ExternalTicketRange add OnlyOffline Smallint null default 0
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>OTNALO</ADDEDBY>
			<SQLVERSION>1.691</SQLVERSION>
			<RMTRACKLINK>4926</RMTRACKLINK>
			<REASON>[1] Update CODE with attributeID on CNF_Attribute if CODE is NULL
[0] Modifiy field CODE to NOT NULL on CNF_Attribute</REASON>
			<TABLENAMES>CNF_Attribute=AttributeId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>UPDATE CNF_Attribute
  SET CNF_Attribute.Code = CNF_Attribute.AttributeId
WHERE CNF_Attribute.Code IS NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE [dbo].[CNF_Attribute]
ALTER COLUMN [Code] nvarchar(10) NOT NULL;
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AndreaDavanzo</ADDEDBY>
			<SQLVERSION>1.690</SQLVERSION>
			<RMTRACKLINK>4641</RMTRACKLINK>
			<REASON>[0] Created Index on SortOrder column</REASON>
			<TABLENAMES>ARC_Index=IndexId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>if not Exists(SELECT 1
                FROM sys.indexes 
               WHERE name=N'IDX_ARCIDX_SORTORDER' AND object_id = OBJECT_ID('ARC_Index'))
BEGIN              
  CREATE NONCLUSTERED INDEX [IDX_ARCIDX_SORTORDER] 
  ON [dbo].[ARC_Index] ([ObjectId],[DocumentId]) 
  INCLUDE ([SortOrder])
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>rfabio</ADDEDBY>
			<SQLVERSION>1.689</SQLVERSION>
			<RMTRACKLINK>4936</RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES>RES_CNF_ResourceType=ResourceTypeId
RES_CNF_Resource=ResourceId
RES_CNF_RequirementTemplateItem=RequirementTemplateItemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>
alter table    RES_CNF_ResourceType   add WarnMaxPerfInWeek integer;  
alter table    RES_CNF_ResourceType   add WarnMaxPerfInDay integer;            
alter table    RES_CNF_Resource       add WarnMaxPerfInWeek integer;  
alter table    RES_CNF_Resource       add WarnMaxPerfInDay integer;    
alter table    RES_CNF_Resource       add WarnQuantity integer;


alter table RES_CNF_RequirementTemplateItem add AllocateOnCreation smallint default 0;
alter table RES_CNF_RequirementTemplateItem add MinutesBeforePerf  integer default 0;
alter table RES_CNF_RequirementTemplateItem add MinutesAfterPerf   integer default 0;
alter table RES_CNF_RequirementTemplateItem add NotWhilePerformance smallint default 0;
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>rfabio</ADDEDBY>
			<SQLVERSION>1.688</SQLVERSION>
			<RMTRACKLINK>4250</RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES>CNF_Calendar=CalendarId
RES_CNF_Resource=ResourceId
RES_CNF_ResourceContract=ContractId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table cnf_calendar add Private smallint default 0;

alter table res_cnf_resource drop column StartDate;
alter table res_cnf_resource drop column EndDate;

Create table [RES_CNF_ResourceContract]
(
	[ContractId] Integer Identity(1,1) NOT NULL, UNIQUE ([ContractId]),
	[ResourceId] Integer NOT NULL,
	[Code] Varchar(10) NULL,
	[Description] Varchar(30) NULL,
	[ContractType] Smallint NOT NULL,
	[StartDate] Datetime NOT NULL,
	[EndDate] Datetime NULL,
Primary Key ([ContractId])
) 



Alter table [RES_CNF_ResourceContract] add constraint FK_RES_CNF_ResourceContract_CNF_Resource foreign key([ResourceId]) references [RES_CNF_Resource] ([ResourceId]) 




				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FedericoCaramella</ADDEDBY>
			<SQLVERSION>1.687</SQLVERSION>
			<RMTRACKLINK>4916</RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES>DATA_Account=AccountId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table data_account add LoginAttempts Smallint not null default 0
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AndreaDavanzo</ADDEDBY>
			<SQLVERSION>1.686</SQLVERSION>
			<RMTRACKLINK>4093</RMTRACKLINK>
			<REASON>Table RES_CNF_RequirementTemplateItem
[0]Added column Active</REASON>
			<TABLENAMES>RES_CNF_RequirementTemplateItem=RequirementTemplateItemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>if not exists(select * from sys.columns 
            where Name = N'Active' and Object_ID = Object_ID(N'RES_CNF_RequirementTemplateItem'))
begin
   ALTER TABLE [dbo].[RES_CNF_RequirementTemplateItem]
      ADD [Active] smallint DEFAULT 1 NOT NULL
end
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Fabio</ADDEDBY>
			<SQLVERSION>1.685</SQLVERSION>
			<RMTRACKLINK>4588</RMTRACKLINK>
			<REASON>cnf_survey
[0] added field SurveyDmgType to recognize manual survey and not</REASON>
			<TABLENAMES>CNF_Survey=SurveyId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>if not exists(select * from sys.columns 
            where Name = N'SurveyDmgType' and Object_ID = Object_ID(N'CNF_Survey'))
begin
   ALTER TABLE [dbo].[CNF_Survey]
      ADD [SurveyDmgType] int DEFAULT 14 NOT NULL
end
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>OTNALO</ADDEDBY>
			<SQLVERSION>1.684</SQLVERSION>
			<RMTRACKLINK>4719</RMTRACKLINK>
			<REASON>/*Parameters:*/
/*STRING   -&gt; string to split*/
/*DELIMTER -&gt; char used to separate substr*/
/*POS      -&gt; which part of string to you want*/</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS( SELECT * FROM sys.objects WHERE object_id = OBJECT_ID('[SplitBySeparatorAndPos]') AND type = 'TF') 
   DROP FUNCTION [SplitBySeparatorAndPos]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE FUNCTION [SplitBySeparatorAndPos]
/*Parameters*/
/*STRING   -&gt; string to split*/
/*DELIMTER -&gt; char used to separate substr*/
/*POS      -&gt; which part of string to you want*/
(
@STRING VARCHAR(MAX),
@DELIMITER CHAR(1),
@POS Integer
)
RETURNS @TEMPTABLE TABLE (ITEMS VARCHAR(MAX))
AS
BEGIN
    DECLARE @IDX INT
    DECLARE @SLICE VARCHAR(MAX)
    DECLARE @LOOP INTEGER

    SELECT @IDX = 1
        IF LEN(@STRING)&lt;1 OR @STRING IS NULL  RETURN
    SET @LOOP = 0;
    WHILE @IDX!= 0
    BEGIN
        SET @IDX = CHARINDEX(@DELIMITER,@STRING)
        IF @IDX!=0
            SET @SLICE = LEFT(@STRING,@IDX - 1)
        ELSE
            SET @SLICE = @STRING

        IF(LEN(@SLICE)&gt;0) AND (@POS = @LOOP)
            INSERT INTO @TEMPTABLE(ITEMS) VALUES(@SLICE)

        SET @STRING = RIGHT(@STRING,LEN(@STRING) - @IDX)
        SET @LOOP = @LOOP + 1
        IF LEN(@STRING) = 0 BREAK
    END
	RETURN
END

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.683</SQLVERSION>
			<RMTRACKLINK>4638</RMTRACKLINK>
			<REASON>Added a UDF to estract substring from a string field with separator</REASON>
			<TABLENAMES>CNF_PromotionEvent=PromotionEventId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table cnf_PromotionEvent alter column EventId integer null;


IF not EXISTS( SELECT * FROM INFORMATION_SCHEMA.COLUMNS 
            WHERE TABLE_NAME = 'cnf_PromotionEvent' 
           AND  COLUMN_NAME = 'DmgCategoryId')
begin

alter table cnf_PromotionEvent add DmgCategoryId integer null;

Alter table [CNF_PromotionEvent] add constraint fk_promotionevent_dmgcategoryid foreign key([DmgCategoryId]) references [CNF_DmgCategory] ([DmgCategoryId]) ;

end

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER procedure [dbo].[sp_ui_CNF_Promotion_insert]
  @PromotionId Integer output,
  @Description nvarchar(30),
  @Active smallint,
  @Code nvarchar(40),
  @Notes text,
  @PromotionType smallint,
  @CreatableOnPos smallint,
  @SupervisorOverride smallint,
  @MaxCouponsOnTransaction int,
  @DmgCategoryId int
as
begin
  insert into CNF_Promotion (
    Description,
    Active,
    Code,
    Notes,
    PromotionType,
    CreatableOnPos,
    SupervisorOverride,
    MaxCouponsOnTransaction,
    DmgCategoryId
  ) values (
    @Description,
    @Active,
    @Code,
    @Notes,
    @PromotionType,
    @CreatableOnPos,
    @SupervisorOverride,
    @MaxCouponsOnTransaction,
    @DmgCategoryId
  )

  select @PromotionId=SCOPE_IDENTITY()

end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER procedure [dbo].[sp_ui_CNF_Promotion_update]
  @PromotionId int,
  @Description nvarchar(30),
  @Active smallint,
  @Code nvarchar(40),
  @Notes text,
  @PromotionType smallint,
  @CreatableOnPos smallint,
  @SupervisorOverride smallint,
  @MaxCouponsOnTransaction int,
  @DmgCategoryId int
as
begin
  update CNF_Promotion
  set
    Description=@Description,
    Active=@Active,
    Code=@Code,
    Notes=@Notes,
    PromotionType=@PromotionType,
    CreatableOnPos=@CreatableOnPos,
    SupervisorOverride=@SupervisorOverride,
    MaxCouponsOnTransaction=@MaxCouponsOnTransaction,
    DmgCategoryId=@DmgCategoryId
  where
    PromotionId=@PromotionId
end



				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>angelomangiaracina</ADDEDBY>
			<SQLVERSION>1.682</SQLVERSION>
			<RMTRACKLINK>3468</RMTRACKLINK>
			<REASON>[0]removed unique index ItemCode on CNF_MaskTableItem</REASON>
			<TABLENAMES>CNF_MaskTableItem=MaskTableItemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @DropIndexName nvarchar(1000);
DECLARE @GetUqIndexName nvarchar(4000);
DECLARE @ParmDefinition nvarchar(500);
DECLARE @DropIndex      nvarchar(1000);

SET @GetUqIndexName = (

N'SELECT @DropIndexNameOut = si.name
FROM sysindexes si
JOIN (SELECT OBJECT_ID(''CNF_MaskTableItem'') [TableID]) x  -- HERE IS YOUR TABLE NAME
  ON si.id = x.TableID
-- This restricts the selection to your column.
JOIN (
    SELECT id, indid 
    FROM sysindexkeys
    WHERE colid IN (
        SELECT COLUMNPROPERTY(OBJECT_ID(''CNF_MaskTableItem''), ''ItemCode'', ''ColumnId'')
     --SELECT colid
        FROM syscolumns
        WHERE name IN (''ItemCode'')              -- HERE IS YOUR COLUMN NAME
    )
) y
  ON si.indid = y.indid
 AND x.TableID = y.id
WHERE si.status &lt;&gt; 0
  -- This eliminates occurrences of the column found in indexes with multiple columns.
  AND si.indid NOT IN (
    SELECT indid
    FROM sysindexkeys
    WHERE id = x.TableID
    GROUP BY indid
    HAVING COUNT(*) &gt; 1
) ' );

SET @ParmDefinition = N'@DropIndexNameOut varchar(30) OUTPUT';

EXECUTE sp_executesql @GetUqIndexName, @ParmDefinition, @DropIndexNameOut=@DropIndexName OUTPUT;

select @DropIndexName nomeIndice;

set @DropIndex = N'ALTER TABLE [dbo].[CNF_MaskTableItem] DROP CONSTRAINT ' + @DropIndexName;
if @DropIndexName is not null
begin
    begin transaction;
	EXECUTE sp_executesql  @DropIndex;
	commit;
end;

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Birtig</ADDEDBY>
			<SQLVERSION>1.681</SQLVERSION>
			<RMTRACKLINK>4388</RMTRACKLINK>
			<REASON>cnf_survey
[0] added field AskOnShopCartAdd</REASON>
			<TABLENAMES>CNF_Survey=SurveyId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>if not exists(select * from sys.columns 
            where Name = N'AskOnShopCartAdd' and Object_ID = Object_ID(N'CNF_Survey'))
begin
 ALTER TABLE CNF_Survey ADD
	AskOnShopCartAdd smallint NULL
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>  
ALTER procedure sp_ui_CNF_Survey_update
  @SurveyId int,
  @DmgCategoryId int,
  @SurveyType smallint,
  @SurveyName nvarchar(100),
  @Frequency int,
  @Enabled smallint,
  @AskOnShopCartAdd smallint
as
begin
  update CNF_Survey
  set
    DmgCategoryId=@DmgCategoryId,
    SurveyType=@SurveyType,
    SurveyName=@SurveyName,
    Frequency=@Frequency,
    Enabled=@Enabled,
	AskOnShopCartAdd=@AskOnShopCartAdd
  where
    SurveyId=@SurveyId
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>  ALTER procedure sp_ui_CNF_Survey_insert
  @SurveyId Integer output,
  @DmgCategoryId int,
  @SurveyType smallint,
  @SurveyName nvarchar(100),
  @Frequency int,
  @Enabled smallint,
  @AskOnShopCartAdd smallInt
as
begin
  insert into CNF_Survey (
    DmgCategoryId,
    SurveyType,
    SurveyName,
    Frequency,
    Enabled,
	AskOnShopCartAdd
  ) values (
    @DmgCategoryId,
    @SurveyType,
    @SurveyName,
    @Frequency,
    @Enabled,
	@AskOnShopCartAdd
  )

  select @SurveyId=SCOPE_IDENTITY()

end
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.680</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>CNF_Pay
[0] change Descrption from text to nvarchar(50)</REASON>
			<TABLENAMES>CNF_Pay=PayId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Pay
  alter column Description nvarchar(50) not null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.679</SQLVERSION>
			<RMTRACKLINK>4328</RMTRACKLINK>
			<REASON>Add Index

DATA_Account -&gt; AccountId
DATA_TicketUsage  -&gt; TicketId
DATA_Reservation -&gt; AccountId
DATA_Reservation-&gt; BillingAccountId
DATA_SaleCoupon -&gt; SaleId
DATA_Transaction -&gt;SaleId</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[DATA_Account]') AND name = N'IDX_DATA_Account_ParentAccountId')
create NONCLUSTERED index IDX_DATA_Account_ParentAccountId ON DATA_Account
(
    ParentAccountId ASC
) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[DATA_TicketUsage]') AND name = N'IDX_DATA_TicketUsage_TicketId')
create NONCLUSTERED index IDX_DATA_TicketUsage_TicketId ON DATA_TicketUsage
(
	TicketId ASC
) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[DATA_Reservation]') AND name = N'IDX_DATA_Reservation_AccountId')
create NONCLUSTERED index IDX_DATA_Reservation_AccountId ON DATA_Reservation
(
	AccountId ASC
) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[DATA_Reservation]') AND name = N'IDX_DATA_Reservation_BillingAccountId')
create NONCLUSTERED index IDX_DATA_Reservation_BillingAccountId ON DATA_Reservation
(
	BillingAccountId ASC
) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[DATA_SaleCoupon]') AND name = N'IDX_DATA_SaleCoupon_SaleId')
create NONCLUSTERED index IDX_DATA_SaleCoupon_SaleId ON DATA_SaleCoupon
(
	SaleId  ASC
) 

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[DATA_Transaction]') AND name = N'IDX_DATA_Transaction_SaleId')
create NONCLUSTERED index IDX_DATA_Transaction_SaleId ON DATA_Transaction
(
	SaleId  ASC
) 
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>1.678</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>Add new table SIAE_Abbonamento</REASON>
			<TABLENAMES>SIAE_Abbonamento=AbbonamentoId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>
IF (NOT EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                 WHERE TABLE_NAME = 'SIAE_Abbonamento'))
BEGIN

Create table [SIAE_Abbonamento]
(
	[AbbonamentoID] Integer Identity(1,1) NOT NULL,
	[CodiceSistemaEmissione] Nvarchar(8) NOT NULL,
	[CodiceCartaEmissione] Nvarchar(8) NOT NULL,
	[ProgressivoCartaEmissione] Integer NOT NULL,
	[SigilloEmissione] Nvarchar(16) NOT NULL,
	[CodiceCartaAnnullo] Nvarchar(8) NULL,
	[ProgressivoCartaAnnullo] Integer NULL,
	[SigilloAnnullo] Nvarchar(16) NULL,
	[CFOrganizzatore] Nvarchar(16) NOT NULL,
	[TipoAbbonamento] Nvarchar(1) NOT NULL,
	[CodiceAbbonamento] Nvarchar(8) NOT NULL,
	[ProgressivoAbbonamento] Integer NOT NULL,
	[CausaleRiduzione] Nvarchar(2) NOT NULL,
	[OrdinePosto] Nvarchar(2) NOT NULL,
	[PrezzoAbbonamento] Float NOT NULL,
	[TipoTassazione] Smallint NOT NULL,
	[IdentifierCode] Nvarchar(100) NOT NULL,
	[DataLimiteValidita] Datetime NOT NULL,
	[EventiAbilitati] Integer NOT NULL,
	[EventiUtilizzati] Integer NOT NULL,
	[EventId] Integer NULL,
	[MatrixCellId] Integer NULL,
	[CausaleRiduzioneId] Smallint NULL,
	[OrdinePostoId] Smallint NULL,
	[TicketId] Integer NOT NULL,
Primary Key ([AbbonamentoID])
) 


END




				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.677</SQLVERSION>
			<RMTRACKLINK>2943</RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES>RES_CNF_RequirementGroup=RequirementGroupId
RES_CNF_RequirementType=RequirementTypeId
RES_CNF_Requirement=RequirementId
RES_CNF_RequirementTemplateItem=RequirementTemplateItemId
RES_CNF_Resource=ResourceId
RES_CNF_ResourceType=ResourceTypeId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>
Create table [RES_CNF_RequirementType]
(
	[RequirementTypeId] Integer Identity(1,1) NOT NULL,
	[Code] Nvarchar(6) NULL,
	[Description] Nvarchar(50) NULL,
Primary Key ([RequirementTypeId])
) 

Create table [RES_CNF_RequirementGroup]
(
	[RequirementGroupId] Integer Identity(1,1) NOT NULL,
	[RequirementTypeId] Integer NULL,
	[MasterRequirementId] Integer NOT NULL,
	[ChildRequirementId] Integer NULL,
Primary Key ([RequirementGroupId])
) 

Alter Table RES_CNF_Requirement add [RequirementTypeId] Integer NULL;


Alter table [RES_CNF_Requirement] add constraint fkRequirementType_Requirement foreign key([RequirementTypeId]) references [RES_CNF_RequirementType] ([RequirementTypeId])

Alter table [RES_CNF_RequirementGroup] add constraint fkRequirement_Master foreign key([MasterRequirementId]) references [RES_CNF_Requirement] ([RequirementId])  
Alter table [RES_CNF_RequirementGroup] add constraint fkRequirement_Child foreign key([ChildRequirementId]) references [RES_CNF_Requirement] ([RequirementId])
Alter table [RES_CNF_RequirementGroup] add constraint fkRequirementType_Group foreign key([RequirementTypeId]) references [RES_CNF_RequirementType] ([RequirementTypeId])   

ALter table RES_CNF_Resource add [StartDate] Datetime NULL;
ALter table RES_CNF_Resource add [EndDate] Datetime NULL;
ALter table RES_CNF_Resource add [MaxPerfInWeek] Integer NULL;
ALter table RES_CNF_Resource add [MaxPerfInDay] Integer NULL;
ALter table RES_CNF_Resource add [MinutesBetWeenPerfs] Integer NULL;

ALter table RES_CNF_ResourceType add [MaxPerfInWeek] Integer NULL;
ALter table RES_CNF_ResourceType add [MaxPerfInDay] Integer NULL;
ALter table RES_CNF_ResourceType add [MinutesBetWeenPerfs] Integer NULL;

ALter table [RES_CNF_RequirementTemplateItem] add [RequirementTypeId] Integer NULL;
Alter Table [RES_CNF_RequirementTemplateItem] alter column [RequirementId] Integer NULL;

Alter table [RES_CNF_RequirementTemplateItem] add constraint fkRES_CNF_RequirementTemplateItem_RequirementTypeId foreign key([RequirementTypeId]) references [RES_CNF_RequirementType] ([RequirementTypeId]);


				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>OTNALO</ADDEDBY>
			<SQLVERSION>1.676</SQLVERSION>
			<RMTRACKLINK>4286</RMTRACKLINK>
			<REASON>[0] Added MovementId column to CNF_ExternalTicketRangetable</REASON>
			<TABLENAMES>CNF_ExternalTicketRange=ExternalTicketRangeId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>if not exists(select * from sys.columns 
            where Name = N'MovementId' and Object_ID = Object_ID(N'CNF_ExternalTicketRange'))             
begin
ALTER TABLE [dbo].[CNF_ExternalTicketRange]
ADD [MovementId] int NULL
end
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.675</SQLVERSION>
			<RMTRACKLINK>2943</RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE [dbo].[RES_ScheduleDetail] ALTER COLUMN [RequirementId] [int] NULL;
ALTER TABLE [dbo].[RES_ScheduleDetail] ALTER COLUMN [RequirementTemplateItemId] [int] NULL;


				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.674</SQLVERSION>
			<RMTRACKLINK>2943</RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES>CNF_EVENT=EventId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_EVENT add PriceTableId Integer null;

Alter table [CNF_Event] add constraint fkEventDefaulPriceTable foreign key([PriceTableId]) references [CNF_PriceTable] ([PriceTableId])
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.673</SQLVERSION>
			<RMTRACKLINK>2943</RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES>RES_ResourceCalendar_TimeFrame=ResourceCalendarTimeFrameId
RES_Schedule=ScheduleId
RES_ScheduleType=ScheduleTypeId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>
Create table [RES_ScheduleType]
(
	[ScheduleTypeId] Integer Identity(1,1) NOT NULL,
	[Code] Varchar(10) NULL,
	[Description] Varchar(50) NULL,
Primary Key ([ScheduleTypeId])
) 

Alter table [RES_Schedule] add [ScheduleTypeId] Integer NULL;

Alter table [RES_Schedule] add constraint fkSchedule_ScheduleType foreign key([ScheduleTypeId]) references [RES_ScheduleType] ([ScheduleTypeId])   

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.672</SQLVERSION>
			<RMTRACKLINK>2943</RMTRACKLINK>
			<REASON>Add</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE IMP_RESERVATION ADD [IMPORTUNIQUEKEY] Uniqueidentifier DEFAULT NEWID() not null;
ALTER TABLE IMP_RESERVATION_ITEM ADD [IMPORTUNIQUEKEY] Uniqueidentifier DEFAULT NEWID() not null;
ALTER TABLE IMP_RESOURCE ADD [IMPORTUNIQUEKEY] Uniqueidentifier DEFAULT NEWID() not null;
ALTER TABLE IMP_RESOURCE_AVAILABILITY ADD [IMPORTUNIQUEKEY] Uniqueidentifier DEFAULT NEWID() not null;
ALTER TABLE IMP_PERFORMANCE ADD [IMPORTUNIQUEKEY] Uniqueidentifier DEFAULT NEWID() not null;


				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE IMP_RESERVATION ADD PRIMARY KEY (IMPORTUNIQUEKEY);
ALTER TABLE IMP_RESERVATION_ITEM ADD PRIMARY KEY (IMPORTUNIQUEKEY);
ALTER TABLE IMP_RESOURCE ADD PRIMARY KEY (IMPORTUNIQUEKEY);
ALTER TABLE IMP_RESOURCE_AVAILABILITY ADD PRIMARY KEY (IMPORTUNIQUEKEY);
ALTER TABLE IMP_PERFORMANCE ADD PRIMARY KEY (IMPORTUNIQUEKEY);
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.671</SQLVERSION>
			<RMTRACKLINK>2943</RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>          
Create table [IMP_RESERVATION]
(
	[RESERVATIONKEY] Varchar(20) NULL,
	[ACCOUNTID] Integer NULL,
	[ACCOUNTKEY] Varchar(20) NULL,
	[IMPORTED] Smallint NULL,
	[ERROR] Smallint NULL,
	[ERRORMESSAGE] Varchar(200) NULL,
	[BOSID] Integer NULL
) 


Create table [IMP_RESERVATION_ITEM]
(
	[RESERVATIONKEY] Varchar(20) NULL,
	[TCKKEY] Varchar(20) NULL,
	[PEOPLECOUNT] Integer NULL,
	[IMPORTED] Smallint NULL,
	[ERROR] Smallint NULL,
	[ERRORMESSAGE] Varchar(200) NULL,
	[PRICE] Float NULL,
	[PERFORMANCEKEY] Varchar(20) NULL,
	[ACCOUNTID] Integer NULL,
	[ACCOUNTKEY] Varchar(20) NULL,
	[QUANTITY] Integer NULL,
	[BOSID] Integer NULL
) 


Create table [IMP_PERFORMANCE]
(
	[PERFORMANCEKEY] Varchar(20) NULL,
	[IMPORTED] Smallint NULL,
	[ERROR] Smallint NULL,
	[ERRORMESSAGE] Varchar(200) NULL,
	[BOSID] Integer NULL,
	[DATE] Datetime NULL,
	[STARTTIME] Datetime NULL,
	[ENDTIME] Datetime NULL,
	[EVENTKEY] Varchar(20) NULL,
	[EVENTID] Integer NULL,
	[RESOURCEKEY] Varchar(20) NULL,
	[RESOURCEID] Integer NULL
) 


Create table [IMP_RESOURCE_AVAILABILITY]
(
	[IMPORTED] Smallint NULL,
	[ERROR] Smallint NULL,
	[ERRORMESSAGE] Varchar(200) NULL,
	[BOSID] Integer NULL,
	[RESOURCEKEY] Varchar(20) NULL,
	[RESOURCEID] Integer NULL,
	[DATE] Datetime NULL,
	[FROMTIME] Datetime NULL,
	[TOTIME] Datetime NULL,
	[AVAILABILITYKEY] Varchar(20) NULL
) 


Create table [IMP_RESOURCE]
(
	[IMPORTED] Smallint NULL,
	[ERROR] Smallint NULL,
	[ERRORMESSAGE] Varchar(200) NULL,
	[BOSID] Integer NULL,
	[RESOURCEKEY] Varchar(20) NULL,
	[CATEGORYKEY] Varchar(20) NULL,
	[CATEGORYID] Integer NULL,
	[FIELDDATA1] Varchar(50) NULL,
	[FIELDOBJ1] Integer NULL
) 
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.670</SQLVERSION>
			<RMTRACKLINK>4313</RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES>DATA_SalePromotionRule=SalePromotionRuleID</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>
Create table [DATA_SalePromotionRule]
(
	[SalePromotionRuleID] Integer Identity(1,1) NOT NULL,
	[PromotionItemId] Integer NOT NULL,
	[PromotionItemRuleId] Integer NOT NULL,
	[SaleItemId] Integer NOT NULL,
Primary Key ([SalePromotionRuleID])
) 


				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>    Alter table [DATA_SalePromotionRule] add constraint fkSaleItem_SalePromotionRule foreign key([SaleItemId]) references [DATA_SaleItem] ([SaleItemId]);

    Alter table [DATA_SalePromotionRule] add constraint fkCNF_PromotionItem_SalePromotionRule foreign key([PromotionItemId]) references [CNF_PromotionItem] ([PromotionItemId])  on update no action on delete no action

    Alter table [DATA_SalePromotionRule] add constraint fkCNF_PromotionItemRule_SalePromotionRule foreign key([PromotionItemRuleId]) references [CNF_PromotionItemRule] ([PromotionItemRuleId])  on update no action on delete no action   
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.669</SQLVERSION>
			<RMTRACKLINK>4313</RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES>DATA_SaleItem=SaleItemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table data_saleitem add	[OrigMatrixCellId] Integer NULL;
alter table data_saleitem add	[OrigUnitSellPrice] Float NULL;


				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_SaleItem] add constraint fk_DATA_SaleItem_OrigMatrixCellId foreign key([OrigMatrixCellId]) references [CNF_MatrixCell] ([MatrixCellId])  

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.668</SQLVERSION>
			<RMTRACKLINK>4238, 4257</RMTRACKLINK>
			<REASON>DATA_AccountFinancial</REASON>
			<TABLENAMES>DATA_AccountFinancial=AccountId
DATA_Reservation=SaleId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_AccountFinancial
  add B2BPriceListId Integer NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_AccountFinancial] 
add  foreign key (B2BPriceListId) references CNF_PriceList (PriceListId)



				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Reservation
  add B2BAccountId Integer NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> Alter table [DATA_Reservation] 
 add  foreign key([B2BAccountId]) references [DATA_Account] ([AccountId])  
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>OTNALO</ADDEDBY>
			<SQLVERSION>1.667</SQLVERSION>
			<RMTRACKLINK>4183</RMTRACKLINK>
			<REASON>[0] Renamed field Active as Enabled on CNF_ExternalTicketRange</REASON>
			<TABLENAMES>CNF_ExternalTicketRange=ExternalTicketRangeId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>if exists(select * from sys.columns 
            where Name = N'Active' and Object_ID = Object_ID(N'CNF_ExternalTicketRange'))             
begin
if not exists(select * from sys.columns 
            where Name = N'Enabled' and Object_ID = Object_ID(N'CNF_ExternalTicketRange'))             
  begin
    EXEC sp_rename N'[dbo].[CNF_ExternalTicketRange].[Active]', N'Enabled', 'COLUMN'    
  end
end
else
if not exists(select * from sys.columns 
            where Name = N'Enabled' and Object_ID = Object_ID(N'CNF_ExternalTicketRange'))             
begin
 alter table CNF_ExternalTicketRange ADD Enabled smallint not null
end
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.666</SQLVERSION>
			<RMTRACKLINK>Expo</RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES>DATA_Sale=SaleId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table data_sale add Externalorderid varchar(255) null;
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.665</SQLVERSION>
			<RMTRACKLINK>3830</RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES>DATA_SaleTax=SaleTaxId
DATA_TransactionTax=TransactionTaxId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>
Create table [DATA_TransactionTax]
(
	[TransactionTaxId] Integer Identity(1,1) NOT NULL,
	[TransactionId] Integer NOT NULL,
	[TaxId] Integer NOT NULL,
	[TaxAmount] Float NULL,
	[Net] Money NULL,
	[Gros] Float NULL,
Primary Key ([TransactionTaxId])
) 



Create table [DATA_SaleTax]
(
	[SaleTaxId] Integer Identity(1,1) NOT NULL,
	[SaleId] Integer NOT NULL,
	[TaxId] Integer NOT NULL,
	[TaxAmount] Float NULL,
	[Net] Float NULL,
	[Gros] Float NULL,
Primary Key ([SaleTaxId])
) 

Alter table [DATA_SaleTax] add constraint FK_CNF_TAX_SALE  foreign key([TaxId]) references [CNF_Tax] ([TaxId])
Alter table [DATA_TransactionTax] add constraint FK_CNF_TAX_Transaction foreign key([TaxId]) references [CNF_Tax] ([TaxId]) 

Alter table [DATA_TransactionTax] add  constraint FK_DATA_Transaction_TransactionTax  foreign key([TransactionId]) references [DATA_Transaction] ([TransactionId])  on update no action on delete no action 
Alter table [DATA_SaleTax] add constraint FK_DATA_Sale_SaleTax foreign key([SaleId]) references [DATA_Sale] ([SaleId])  on update no action on delete no action 









				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.664</SQLVERSION>
			<RMTRACKLINK>3955</RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES>STOCK_CNF_ProductComboChoice=ComboChoiceId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table STOCK_CNF_ProductComboChoice add DefaultChoice smallint
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AndreaDavanzo</ADDEDBY>
			<SQLVERSION>1.663</SQLVERSION>
			<RMTRACKLINK>4010</RMTRACKLINK>
			<REASON>[0] Added DmgCategoryId column to CNF_Promotion table</REASON>
			<TABLENAMES>CNF_Promotion=PromotionId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF not EXISTS( SELECT * FROM INFORMATION_SCHEMA.COLUMNS 
            WHERE TABLE_NAME = 'cnf_Promotion' 
           AND  COLUMN_NAME = 'DmgCategoryId')
begin
alter table CNF_Promotion
add DmgCategoryId Integer NULL
end
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ritacco</ADDEDBY>
			<SQLVERSION>1.662</SQLVERSION>
			<RMTRACKLINK>3650</RMTRACKLINK>
			<REASON>[0] Add ScedulerId in Data.SchedulerLog</REASON>
			<TABLENAMES>DATA_SchedulerLog=SchedulerLogId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_SchedulerLog
add SchedulerId Integer NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AndreaDavanzo</ADDEDBY>
			<SQLVERSION>1.661</SQLVERSION>
			<RMTRACKLINK>3981</RMTRACKLINK>
			<REASON>[0] Add column SortOrder to CNF_Event
[1] Copy the value from MoneyCardCost field to SortOrder
[2] Set the value of field MoneyCardCost to zero</REASON>
			<TABLENAMES>CNF_Event=EventId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Event
add SortOrder Integer NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_Event
set SortOrder=MoneyCardCost
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_Event
set MoneyCardCost=0
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AndreaDavanzo</ADDEDBY>
			<SQLVERSION>1.660</SQLVERSION>
			<RMTRACKLINK>2863</RMTRACKLINK>
			<REASON>[0] Drop MediaId foreign key
[1] Drop DriverId foreign key
[2] Drop DATA_Biometric table
[3] Create DATA_Biometric table
[4] Create DriverId foreign key
[5] Create TicketId foreign key
[6] Create Unique Index on TicketId
[7] Alter store procedure for update on DATA_Biometric
[8] Alter store procedure for insert on DATA_Biometric</REASON>
			<TABLENAMES>DATA_Biometric=BiometricId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>declare @foreign_key_name nvarchar(max),
@dropstmt nvarchar(max);

select @foreign_key_name = f.name
from sys.foreign_keys AS f
inner join sys.foreign_key_columns AS fc 
on  f.object_id = fc.constraint_object_id    
where  f.parent_object_id = object_id(N'[dbo].[DATA_Biometric]')
and  f.referenced_object_id = object_id(N'[dbo].[DATA_Media]')   
and COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'MediaId';

if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [DATA_Biometric] DROP CONSTRAINT [' + @foreign_key_name + ']'; 
  execute sp_executesql @dropstmt
end;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>declare @foreign_key_name nvarchar(max),
@dropstmt nvarchar(max);

select @foreign_key_name = f.name
from sys.foreign_keys AS f
inner join sys.foreign_key_columns AS fc 
on  f.object_id = fc.constraint_object_id    
where  f.parent_object_id = object_id(N'[dbo].[DATA_Biometric]') 
and  f.referenced_object_id = object_id(N'[dbo].[CNF_Driver]')    
and COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'DriverId'; 

if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[DATA_Biometric] DROP CONSTRAINT [' + @foreign_key_name + ']'; 
  execute sp_executesql @dropstmt
end;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DROP TABLE [DATA_Biometric]
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE TABLE [DATA_Biometric](
	[BiometricId] [int] IDENTITY(1,1) NOT NULL,
	[TicketId] [int] NOT NULL,
	[DriverId] [int] NOT NULL,
	[TransactionId] [int] NOT NULL,
	[EnrollmentDate] [datetime] NOT NULL,
	[BiometricLen] [int] NOT NULL,
	[BiometricInfo] [varbinary](max) NOT NULL,
PRIMARY KEY CLUSTERED 
(
	[BiometricId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_Biometric] add constraint fkDATA_Biometric_CNF_Driver foreign key([DriverId]) 
REFERENCES [CNF_Driver] ([DriverId])
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_Biometric] add constraint fkDATA_Biometric_DATA_Ticket foreign key([TicketId]) 
REFERENCES [DATA_Ticket] ([TicketId])
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE UNIQUE NONCLUSTERED INDEX [IDX_BIOM_TICKETID] ON [dbo].[DATA_Biometric]
(
	[TicketId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER procedure sp_ui_DATA_Biometric_update
  @BiometricId int,
  @TicketId int,
  @DriverId int,
  @TransactionId int,
  @EnrollmentDate datetime,
  @BiometricLen int,
  @BiometricInfo varbinary(max)
as
begin
  update DATA_Biometric
  set
    TicketId=@TicketId,
    DriverId=@DriverId,
    TransactionId=@TransactionId,
    EnrollmentDate=@EnrollmentDate,
    BiometricLen=@BiometricLen,
    BiometricInfo=@BiometricInfo
  where
    BiometricId=@BiometricId
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER procedure sp_ui_DATA_Biometric_insert
  @BiometricId Integer output,
  @TicketId int,
  @DriverId int,
  @TransactionId int,
  @EnrollmentDate datetime,
  @BiometricLen int,
  @BiometricInfo varbinary(max)
as
begin
  insert into DATA_Biometric (
    TicketId,
    DriverId,
    TransactionId,
    EnrollmentDate,
    BiometricLen,
    BiometricInfo
  ) values (
    @TicketId,
    @DriverId,
    @TransactionId,
    @EnrollmentDate,
    @BiometricLen,
    @BiometricInfo
  )

  select @BiometricId=SCOPE_IDENTITY()

end
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.659</SQLVERSION>
			<RMTRACKLINK>Expo</RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>
Create table [DATA_Trigger_Errors]
(
	[TriggerId] Integer Identity(1,1) NOT NULL,
	[TriggerType] Smallint NOT NULL,
	[ListenerType] Smallint NOT NULL,
	[EntityTable] Smallint NULL,
	[EntityId] Integer NULL,
	[ErrorCode] Varchar(6) NULL,
	[ErrorMessage] Varchar(255) NULL,
Primary Key ([TriggerId])
) 
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.658</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE DATA_SaleItem_Combo ALTER COLUMN MatrixCellId integer NULL
ALTER TABLE DATA_TransactionItem_Combo ALTER COLUMN MatrixCellId integer NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.657</SQLVERSION>
			<RMTRACKLINK>3661</RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF EXISTS (SELECT name FROM sysindexes WHERE name = 'idxTransactionItemRule-itemid')	
drop index  [idxTransactionItemRule-itemid] on [DATA_TransactionItemRule] ;


IF EXISTS (SELECT name FROM sysindexes WHERE name = 'idxDATA_SAlecoupon_saleidcoupon')
 drop index [idxDATA_SAlecoupon_saleidcoupon] on [DATA_SaleCoupon] ;

IF EXISTS (SELECT name FROM sysindexes WHERE name = 'idxDATA_Transaction2TckTransactionid')
drop index	idxDATA_Transaction2TckTransactionid on [DATA_Transaction2Ticket];


IF EXISTS (SELECT name FROM sysindexes WHERE name = 'DATA_TicketUsageUSAGE')
drop index	DATA_TicketUsageUSAGE on [DATA_TicketUsage];



IF EXISTS (SELECT name FROM sysindexes WHERE name = 'idxDATA_transactioncompleted')
drop index	idxDATA_transactioncompleted on [DATA_Transaction];


IF EXISTS (SELECT name FROM sysindexes WHERE name = 'DATA_TransactionItem_Transactionid')
drop index	DATA_TransactionItem_Transactionid on [DATA_TransactionItem];


Create Index [idxDATA_TransactionItemRule_ItemId] ON [DATA_TransactionItemRule] ([ItemId] ) 

Create Index [idxDATA_SaleCoupon_PromotionId_SaleId] ON [DATA_SaleCoupon] ([PromotionId] ,[SaleId] ) 

Create Index [idxDATA_TicketUsage_TicketUsageTypeValidateResult] ON [DATA_TicketUsage] ([TicketId] ,[UsageType] ,[ValidateResult] ) 

Create Index [idxData_Transaction_Completed] ON [DATA_Transaction] ([Completed] ) 


				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.656</SQLVERSION>
			<RMTRACKLINK>3955</RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES>DATA_TransactionItem_Combo=TransactionItemComboId
DATA_SaleItem_Combo=SaleItemComboId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_SaleItem_Combo add Qty Integer;  

alter table DATA_TransactionItem_Combo add Qty Integer;
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.655</SQLVERSION>
			<RMTRACKLINK>3955</RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES>STOCK_CNF_ProductComboChoice=ComboChoiceId
STOCK_CNF_ProductCombo=ComboId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table STOCK_CNF_ProductCombo add MinQty float;
alter table STOCK_CNF_ProductComboChoice add MinQty float;

alter table STOCK_CNF_ProductCombo add MaxQty float;
alter table STOCK_CNF_ProductComboChoice add MaxQty float;
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.654</SQLVERSION>
			<RMTRACKLINK>3955</RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES>STOCK_CNF_ProductComboChoice=ComboChoiceId
STOCK_CNF_ProductCombo=ComboId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table STOCK_CNF_ProductCombo add FreeQuantity smallint not null default 0;
alter table STOCK_CNF_ProductComboChoice add FreeQuantity smallint not null default 0;
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.653</SQLVERSION>
			<RMTRACKLINK>3938</RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter PROCEDURE [dbo].[spui_GetCounter]
 -- Add the parameters for the stored procedure here
 @CounterType smallint,
 @IdentifierAK varchar(32),
 @ReferenceTime varchar(32),
 @Counter integer output  
AS
BEGIN


 SET NOCOUNT ON;


 insert into DATA_Counter (CounterType, IdentifierAK, ReferenceTime, Counter) 
 select @CounterType, @IdentifierAK, IsNull(@ReferenceTime,'Never'), 0
 where 
 0 = (select count(*) from DATA_Counter with (READCOMMITTEDLOCK) where CounterType = @CounterType and IdentifierAK = @IdentifierAK and
  IsNull(@ReferenceTime,'NEVER') = IsNull(ReferenceTime,'NEVER'))


   update DATA_Counter with (READCOMMITTEDLOCK)
   set    @Counter = Counter = Counter +1 
   where  CounterType = @CounterType and IdentifierAK = @IdentifierAK and
		IsNull(@ReferenceTime,'NEVER') = IsNull(ReferenceTime,'NEVER')


end
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Andrea Davanzo</ADDEDBY>
			<SQLVERSION>1.652</SQLVERSION>
			<RMTRACKLINK>3493</RMTRACKLINK>
			<REASON>Modified the table DATA_Biometric in order to save the length of the template and the template itself as array of bytes.
[0] Drop column BiometricInfo
[1] Add column BiometricLen as int
[2] Add column BiometricInfo as varbinary(MAX)
[3] Alter store procedure for update on DATA_Biometric
[4] Alter store procedure for insert on DATA_Biometric</REASON>
			<TABLENAMES>DATA_Biometric=BiometricId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Biometric
drop column BiometricInfo

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Biometric
add BiometricLen int not null

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Biometric
add BiometricInfo varbinary(MAX) not null

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER procedure sp_ui_DATA_Biometric_update
  @BiometricId int,
  @MediaId int,
  @DriverId int,
  @TransactionId int,
  @EnrollmentDate datetime,
  @BiometricLen int,
  @BiometricInfo varbinary(max)
as
begin
  update DATA_Biometric
  set
    MediaId=@MediaId,
    DriverId=@DriverId,
    TransactionId=@TransactionId,
    EnrollmentDate=@EnrollmentDate,
    BiometricLen=@BiometricLen,
    BiometricInfo=@BiometricInfo
  where
    BiometricId=@BiometricId
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER procedure sp_ui_DATA_Biometric_insert
  @BiometricId Integer output,
  @MediaId int,
  @DriverId int,
  @TransactionId int,
  @EnrollmentDate datetime,
  @BiometricLen int,
  @BiometricInfo varbinary(max)
as
begin
  insert into DATA_Biometric (
    MediaId,
    DriverId,
    TransactionId,
    EnrollmentDate,
    BiometricLen,
    BiometricInfo
  ) values (
    @MediaId,
    @DriverId,
    @TransactionId,
    @EnrollmentDate,
    @BiometricLen,
    @BiometricInfo
  )

  select @BiometricId=SCOPE_IDENTITY()

end
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Fabio</ADDEDBY>
			<SQLVERSION>1.651</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>[0] add field Active smallInt to CNF_ExternallTicketRange</REASON>
			<TABLENAMES>CNF_ExternalTicketRange=ExternalTicketRangeId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE [dbo].[CNF_ExternalTicketRange]
ADD [Active] smallint DEFAULT 1 NOT NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.650</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>[0] add field UseParentMoney
[1] update old value
[2] set field UseParentMoney as not null</REASON>
			<TABLENAMES>DATA_AccountRelationship=AccountRelationshipId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_AccountRelationship
 add UseParentMoney Smallint  NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_AccountRelationship set 
UseParentMoney = 0

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_AccountRelationship
 alter column UseParentMoney Smallint not NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.649</SQLVERSION>
			<RMTRACKLINK>3057</RMTRACKLINK>
			<REASON>Recaftoring of DATA_Ledger table
[0] add field PaymentId int null
[1] add field VoucherId int null
[2] add field AccountId int null
[3] add field TicketId int null

[4] update PaymentId
[5]Update VoucherId
[6] update AccountId
[7] Update Ticket Id

[8] add FK on PaymentId
[9]add FK on VoucherId
[10]add FK on AccountId
[11] add FK on TicketId

[12] add Index on PaymentId
[13] add Index on VoucherId
[14] add Index on AccountId
[15] add Index on TicketId</REASON>
			<TABLENAMES>DATA_Ledger=LedgerId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Ledger
  add PaymentId Integer NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Ledger
  add VoucherId Integer NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Ledger
  add AccountId Integer NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Ledger
  add TicketId Integer NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_Ledger
  set PaymentId = ReferenceId
  where Referencetable = 124   
  and ReferenceId = (select DATA_Payment.PaymentId from DATA_Payment where DATA_Payment.PaymentId=ReferenceId)
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_Ledger
  set VoucherId = ReferenceId
  where Referencetable = 186     
  and ReferenceId = (select DATA_Voucher.VoucherId from DATA_Voucher where DATA_Voucher.VoucherId=ReferenceId)
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_Ledger
  set AccountId = ReferenceId
  where Referencetable = 197    
  and ReferenceId = (select DATA_Account.AccountId from DATA_Account where DATA_Account.AccountId=ReferenceId)
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_Ledger
  set TicketId = ReferenceId
  where Referencetable = 159        
   and ReferenceId = (select DATA_Ticket.TicketId from DATA_Ticket where DATA_Ticket.TicketId=ReferenceId)
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_Ledger] 
  add  foreign key([PaymentId]) references [DATA_Payment] ([PaymentId]) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_Ledger] 
  add  foreign key([VoucherId]) references [DATA_Voucher] ([VoucherId])
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_Ledger] 
  add  foreign key([AccountId]) references [DATA_Account] ([AccountId])
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_Ledger] 
  add  foreign key([TicketId]) references [DATA_Ticket] ([TicketId]) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create Index [IDX_DATALedgerPaymentId] 
  ON [DATA_Ledger] ([PaymentId] ) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create Index [IDX_DATA_LedgerVoucherId] 
  ON [DATA_Ledger] ([VoucherId] )
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create Index [IDX_DATA_LedgerAccId] 
  ON [DATA_Ledger] ([AccountId] ) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create Index [IDX_DATALedgerTicketId] 
  ON [DATA_Ledger] ([TicketId] ) 
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Birtig</ADDEDBY>
			<SQLVERSION>1.648</SQLVERSION>
			<RMTRACKLINK>3671</RMTRACKLINK>
			<REASON> fixing multilanguage form which since the past few BOS version has been saving duplicated records or records with no value in componentname field</REASON>
			<TABLENAMES>CNF_Multilanguage=MultilanguageId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE cnf_multilanguage ALTER COLUMN ComponentName nvarchar(50) NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.647</SQLVERSION>
			<RMTRACKLINK>3681</RMTRACKLINK>
			<REASON>CNF_Geo
[0] drop table CNF_Geo
[1] re create table with primary Index</REASON>
			<TABLENAMES>CNF_Geo=GeoId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT> drop table [CNF_Geo]
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> Create table [CNF_Geo]
(
	[GeoId] Integer Identity(1,1) NOT NULL, UNIQUE ([GeoId]),
	[CountryISO] Nvarchar(5) NULL,
	[Country] Nvarchar(50) NULL,
	[PostalCode] Nvarchar(10) NULL,
	[City] Nvarchar(100) NULL,
	[State] Nvarchar(50) NULL,
Primary Key ([GeoId])
) 
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>federicocaramella</ADDEDBY>
			<SQLVERSION>1.646</SQLVERSION>
			<RMTRACKLINK>3305</RMTRACKLINK>
			<REASON>CNF_Workstation
[0] Add ThresholdDelta</REASON>
			<TABLENAMES>CNF_Workstation=WorkstationId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT> Alter table CNF_Workstation add ThresholdDelta integer
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>federicocaramella</ADDEDBY>
			<SQLVERSION>1.645</SQLVERSION>
			<RMTRACKLINK>3563</RMTRACKLINK>
			<REASON>DATA_ExceptionLog 
[0] CREATE TABLE
[1]ADD FK
[2]ADD FK</REASON>
			<TABLENAMES>DATA_ExceptionLog=ExceptionLogId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE TABLE DATA_ExceptionLog(
	[ExceptionLogId]  [int] Identity(1,1) NOT NULL UNIQUE,
	[LogDateTime] [datetime] NOT NULL,
	[UserId] [int] NOT NULL,
	[WorkstationId] [int] NOT NULL,
	[ExceptionStr] [varchar](500) NOT NULL, 
	[ExceptionType] [Smallint] NOT NULL, 
	[HandleType] [Smallint] NOT NULL, 
	[Status] [Smallint] NOT NULL, 
Primary Key  (ExceptionLogId)
	) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_ExceptionLog] add  foreign key([WorkstationId]) references [CNF_Workstation] ([WorkstationId])
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_ExceptionLog] add  foreign key([UserId]) references [CNF_User] ([UserId])
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>OTNALO</ADDEDBY>
			<SQLVERSION>1.644</SQLVERSION>
			<RMTRACKLINK>3305</RMTRACKLINK>
			<REASON>Cnf_Workstation
[0] Add field LoadTicket int (use TVM)</REASON>
			<TABLENAMES>CNF_Workstation=WorkstationId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE CNF_Workstation
ADD [LoadTicket] int NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.643</SQLVERSION>
			<RMTRACKLINK>3630</RMTRACKLINK>
			<REASON>DATA_TicketUsage
[0] add index on MediaIdentifierId</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[DATA_TicketUsage]') AND name = N'IDX_DATA_TicketUsage_MediaIdenfierId')
  Create Index [IDX_DATA_TicketUsage_MediaIdenfierId] ON [DATA_TicketUsage] ([MediaIdentifierId] )
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>federicocaramella</ADDEDBY>
			<SQLVERSION>1.642</SQLVERSION>
			<RMTRACKLINK>3519</RMTRACKLINK>
			<REASON>DATA_Reservation
[0] OperatingAreaId 
[1] FK</REASON>
			<TABLENAMES>DATA_Reservation=SaleId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table DATA_Reservation add OperatingAreaId integer
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_Reservation] add  foreign key([OperatingAreaId]) references [CNF_OperatingArea] ([OperatingAreaId])
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>federicocaramella</ADDEDBY>
			<SQLVERSION>1.641</SQLVERSION>
			<RMTRACKLINK>3409</RMTRACKLINK>
			<REASON>CNF_MatrixCellInfo
[0]Add  field QuickRenewIds NVarChar(1000)
[1]Add  field QuickRenewOnly SmallInt</REASON>
			<TABLENAMES>CNF_MatrixCellInfo=MatrixCellInfoId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE CNF_MatrixCellInfo ADD QuickRenewIds nvarchar(1000) NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE CNF_MatrixCellInfo ADD QuickRenewOnly SmallInt DEFAULT 0 NOT NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>OTNALO</ADDEDBY>
			<SQLVERSION>1.640</SQLVERSION>
			<RMTRACKLINK>2861</RMTRACKLINK>
			<REASON>CNF_MatrixSheet
[0]Add  field Code NVarChar(8)</REASON>
			<TABLENAMES>CNF_MatrixSheet=MatrixSheetId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>if not exists(select * from sys.columns 
            where Name = N'Code' and Object_ID = Object_ID(N'CNF_MatrixSheet'))             
BEGIN
  ALTER TABLE CNF_MatrixSheet ADD [Code] nvarchar(8) NULL
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if not Exists(SELECT 1
              FROM sys.indexes 
              WHERE name=N'IDX_CNF_MatrixSheet_Code' AND object_id = OBJECT_ID('CNF_MatrixSheet'))

BEGIN
   CREATE INDEX [IDX_CNF_MatrixSheet_Code] ON [CNF_MatrixSheet] ([Code])  
END

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.639</SQLVERSION>
			<RMTRACKLINK>3556</RMTRACKLINK>
			<REASON>CNF_Event
[0]Add  field TvmMaxTicketNum</REASON>
			<TABLENAMES>CNF_Event=EventId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Event
 add TvmMaxTicketNum Integer NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.638</SQLVERSION>
			<RMTRACKLINK>3548</RMTRACKLINK>
			<REASON>Fixed Account View</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER VIEW [dbo].[AccountHistory]
AS
SELECT 
        DateOrd,
	DatePayment, 
	DateCreation, 
	ReservationAK, 
	TransactionAK,
	AccountId, 
	paymentamount,
	Debit, 
	Credit, 
	AmountDisc, 
	UserName,
	Note,
	SettleCreditPayType
FROM  (SELECT P.PaymentDate AS DateOrd,
              P.FPaymentDate AS DatePayment, 
              dtcreation.trdate AS DateCreation, 
			  dr.ReservationAK, 
			  dt.TransactionAK,
			  PC.AccountId, 
			  P.PaymentAmount  AS paymentamount, 
              CASE WHEN p.paymentamount &gt; 0 THEN p.paymentamount ELSE 0 END AS Debit, 
              CASE WHEN p.paymentamount &lt; 0 THEN case when dt.TransactionType &lt;&gt; 5 then ABS(p.paymentamount) else ABS(p.paymentamount) end ELSE 0 END AS Credit, 
			  PC.AmountDisc, 
              cu.UserName,
			  dn.Note,
			  (case when pc.SettleTransactionId = dt.TransactionId then '' else cl.description end) SettleCreditPayType
       FROM   dbo.DATA_PaymentCredit AS PC WITH(NOLOCK) INNER JOIN
              dbo.DATA_Payment AS P WITH(NOLOCK) ON P.PaymentId = PC.PaymentId left JOIN
              dbo.DATA_Transaction AS dt WITH(NOLOCK) ON dt.TransactionId = P.TransactionId LEFT OUTER JOIN
              dbo.CNF_User AS cu WITH(NOLOCK) ON cu.UserId = dt.UserId left JOIN
              dbo.DATA_Sale AS ds WITH(NOLOCK) ON ds.SaleId = dt.SaleId left JOIN
			  dbo.DATA_Note AS dn WITH(NOLOCK) ON dn.NoteKey = ds.SaleId AND dn.NoteType = 161 left JOIN
              dbo.DATA_Reservation AS dr WITH(NOLOCK) ON dr.SaleId = ds.SaleId LEFT OUTER JOIN
      (SELECT MIN(FTransactionDate) AS trdate, SaleId
       FROM dbo.DATA_Transaction AS dt  WITH(NOLOCK) 
       GROUP BY SaleId) AS dtcreation ON dtcreation.SaleId = ds.SaleId LEFT OUTER JOIN
      (SELECT MIN(PaymentType) AS pttype, TransactionId
       FROM dbo.DATA_Payment AS dp  WITH(NOLOCK) 	   
       GROUP BY TransactionId) AS cs ON cs.TransactionId = PC.SettleTransactionId LEFT OUTER JOIN
       dbo.CNF_LookUp AS cl ON cl.ItemId = cs.pttype AND cl.LookUpTableId = 7  AND P.PaymentStatus = 1 
UNION ALL
SELECT dt.TransactionDate AS DateOrd, 
       dt.FTransactionDate AS DatePayment, 
       dt.FTransactionDate AS DateCreation, 
	   NULL AS Expr1, 
	   dt.TransactionAk AS Expr2, 
	   L.ReferenceId AS AccountId, 
       L.EntryAmount AS Expr3, 
	   case when L.EntryAmount &gt; 0 then L.EntryAmount else 0 end AS Debit, 
	   case when L.EntryAmount &lt; 0 then ABS(L.EntryAmount) else 0 end AS Credit, 
	   NULL AS Expr4,
       cu.UserName,
	   dn.Note AS Expr5, 
	   cl.description SettleCreditPayType
FROM   dbo.DATA_Transaction AS dt WITH(NOLOCK) left JOIN 
		DATA_Note as dn WITH(NOLOCK) on  dn.NoteKey = dt.SaleId AND dn.NoteType = 161  INNER JOIN
       dbo.DATA_Ledger AS L WITH(NOLOCK) ON L.TransactionId = dt.TransactionId INNER JOIN
       dbo.CNF_User AS cu WITH(NOLOCK) ON cu.UserId = dt.UserId inner JOIN
       dbo.CNF_LedgerAccount AS LA WITH(NOLOCK) ON L.LedgerAccountId = LA.LedgerAccountId INNER JOIN
      (SELECT MIN(PaymentType) AS pttype, TransactionId
       FROM dbo.DATA_Payment AS dp  WITH(NOLOCK) 
       GROUP BY TransactionId) AS cs_1 ON cs_1.TransactionId = dt.TransactionId LEFT OUTER JOIN
       dbo.CNF_LookUp AS cl ON cl.ItemId = cs_1.pttype AND cl.LookUpTableId = 7 
       WHERE (dt.TransactionType in (34,6)) 
	   AND LA.SystemAccountId= 7
	   AND (L.ReferenceTable = 197)) AS CreditDebit
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ritacco</ADDEDBY>
			<SQLVERSION>1.637</SQLVERSION>
			<RMTRACKLINK>3421</RMTRACKLINK>
			<REASON>Add table cnf_EventFilter </REASON>
			<TABLENAMES>CNF_EventFilter=EventFilterId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>
Create table [CNF_EventFilter]
(
	[EventFilterId] Integer Identity(1,1) NOT NULL, UNIQUE ([EventFilterId]),
	[AttributeId] Integer NOT NULL,
	[EventId] Integer NOT NULL,
Primary Key ([EventFilterId])
) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_EventFilter] add  foreign key([AttributeId]) references [CNF_Attribute] ([AttributeId])
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_EventFilter] add  foreign key([EventId]) references [CNF_Event] ([EventId])
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Birtig</ADDEDBY>
			<SQLVERSION>1.636</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>fixed  accountHistory view. Note column was empty most of the time. Second select in the query union was not correct</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.views
WHERE upper(name) = 'ACCOUNTHISTORY' AND type = 'V')
	drop view AccountHistory
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE VIEW AccountHistory
AS
SELECT 
        DateOrd,
	DatePayment, 
	DateCreation, 
	ReservationAK, 
	TransactionAK,
	AccountId, 
	paymentamount,
	Debit, 
	Credit, 
	AmountDisc, 
	UserName,
	Note,
	SettleCreditPayType
FROM  (SELECT P.PaymentDate AS DateOrd,
              P.FPaymentDate AS DatePayment, 
              dtcreation.trdate AS DateCreation, 
			  dr.ReservationAK, 
			  dt.TransactionAK,
			  PC.AccountId, 
			  P.PaymentAmount  AS paymentamount, 
              CASE WHEN p.paymentamount &gt; 0 THEN p.paymentamount ELSE 0 END AS Debit, 
              CASE WHEN p.paymentamount &lt; 0 THEN case when dt.TransactionType &lt;&gt; 5 then ABS(p.paymentamount) else ABS(p.paymentamount) end ELSE 0 END AS Credit, 
			  PC.AmountDisc, 
              cu.UserName,
			  dn.Note,
			  (case when pc.SettleTransactionId = dt.TransactionId then '' else cl.description end) SettleCreditPayType
       FROM   dbo.DATA_PaymentCredit AS PC WITH(NOLOCK) INNER JOIN
              dbo.DATA_Payment AS P WITH(NOLOCK) ON P.PaymentId = PC.PaymentId left JOIN
              dbo.DATA_Transaction AS dt WITH(NOLOCK) ON dt.TransactionId = P.TransactionId LEFT OUTER JOIN
              dbo.CNF_User AS cu WITH(NOLOCK) ON cu.UserId = dt.UserId left JOIN
              dbo.DATA_Sale AS ds WITH(NOLOCK) ON ds.SaleId = dt.SaleId left JOIN
			  dbo.DATA_Note AS dn WITH(NOLOCK) ON dn.NoteKey = ds.SaleId AND dn.NoteType = 161 left JOIN
              dbo.DATA_Reservation AS dr WITH(NOLOCK) ON dr.SaleId = ds.SaleId LEFT OUTER JOIN
      (SELECT MIN(FTransactionDate) AS trdate, SaleId
       FROM dbo.DATA_Transaction AS dt  WITH(NOLOCK) 
       GROUP BY SaleId) AS dtcreation ON dtcreation.SaleId = ds.SaleId LEFT OUTER JOIN
      (SELECT MIN(PaymentType) AS pttype, TransactionId
       FROM dbo.DATA_Payment AS dp  WITH(NOLOCK) 	   
       GROUP BY TransactionId) AS cs ON cs.TransactionId = PC.SettleTransactionId LEFT OUTER JOIN
       dbo.CNF_LookUp AS cl ON cl.ItemId = cs.pttype AND cl.LookUpTableId = 7  AND P.PaymentStatus = 1 
UNION ALL
SELECT dt.TransactionDate AS DateOrd, 
       dt.FTransactionDate AS DatePayment, 
       dt.FTransactionDate AS DateCreation, 
	   NULL AS Expr1, 
	   NULL AS Expr2, 
	   L.ReferenceId AS AccountId, 
       L.EntryAmount AS Expr3, 
	   case when L.EntryAmount &gt; 0 then L.EntryAmount else 0 end AS Debit, 
	   case when L.EntryAmount &lt; 0 then ABS(L.EntryAmount) else 0 end AS Credit, 
	   NULL AS Expr4,
       cu.UserName,
	   dn.Note AS Expr5, 
	   cl.description SettleCreditPayType
FROM   dbo.DATA_Transaction AS dt WITH(NOLOCK) left JOIN 
		DATA_Note as dn WITH(NOLOCK) on  dn.NoteKey = dt.SaleId AND dn.NoteType = 161  INNER JOIN
       dbo.DATA_Ledger AS L WITH(NOLOCK) ON L.TransactionId = dt.TransactionId INNER JOIN
       dbo.CNF_User AS cu WITH(NOLOCK) ON cu.UserId = dt.UserId inner JOIN
       dbo.CNF_LedgerAccount AS LA WITH(NOLOCK) ON L.LedgerAccountId = LA.LedgerAccountId INNER JOIN
      (SELECT MIN(PaymentType) AS pttype, TransactionId
       FROM dbo.DATA_Payment AS dp  WITH(NOLOCK) 
       GROUP BY TransactionId) AS cs_1 ON cs_1.TransactionId = dt.TransactionId LEFT OUTER JOIN
       dbo.CNF_LookUp AS cl ON cl.ItemId = cs_1.pttype AND cl.LookUpTableId = 7 
       WHERE (dt.TransactionType in (34,6)) 
	   AND LA.SystemAccountId= 7
	   AND (L.ReferenceTable = 197)) AS CreditDebit
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.635</SQLVERSION>
			<RMTRACKLINK>3099</RMTRACKLINK>
			<REASON>DATA_MediaIdentifier
[0] add column voidType to manage the blocking of a mediaCode</REASON>
			<TABLENAMES>DATA_MediaIdentifier=MediaIdentifierId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_MediaIdentifier
 add VoidType Smallint Default 0 NOT NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>federicocaramella</ADDEDBY>
			<SQLVERSION>1.634</SQLVERSION>
			<RMTRACKLINK>3053</RMTRACKLINK>
			<REASON>DATA_Sale
[0] OwnerAccountId 
[1] FK</REASON>
			<TABLENAMES>DATA_Sale=SaleId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_Sale] add OwnerAccountId integer
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_Sale] add  foreign key([OwnerAccountId]) references [DATA_Account] ([AccountId])
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Andrea Davanzo</ADDEDBY>
			<SQLVERSION>1.633</SQLVERSION>
			<RMTRACKLINK>3362</RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES>CNF_MatrixCellInfo=MatrixCellInfoId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_MatrixCellInfo add ExtInfoApplyAll smallint not null default 0;
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.632</SQLVERSION>
			<RMTRACKLINK>3407</RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES>DATA_Account=AccountId
CNF_MatrixCell=MatrixCellId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table cnf_matrixcell add Membership Smallint not null default 0;
alter table data_account add Membership Smallint not null default 0;
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.631</SQLVERSION>
			<RMTRACKLINK>3376</RMTRACKLINK>
			<REASON>CNF_AttributeTemplate=AttributeTemplateId</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE [CNF_AttributeTemplate] 
alter column weight int null

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_AttributeTemplate
set  weight = Null where Weight = 0
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.630</SQLVERSION>
			<RMTRACKLINK>3074</RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>     Create table [CNF_Geo]
(
	[CountryISO] Nvarchar(5) NULL,
	[Country] Nvarchar(50) NULL,
	[PostalCode] Nvarchar(10) NULL,
	[City] Nvarchar(100) NULL,
	[State] Nvarchar(50) NULL
) 
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.629</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>
Create table [SYNC_ExecLog]
(
	[ClientId] Integer NOT NULL,
	[UplLastExec] Datetime NULL,
	[UplSucc] Integer NULL,
	[UplError] Integer NULL,
	[DWNLastExec] Datetime NULL,
	[DWNSucc] Integer NULL,
	[DWNError] Integer NULL,
	[SHARELastExec] Datetime NULL,
	[SHARESucc] Integer NULL,
	[SHAREError] Integer NULL,
	[SYNCHLastExec] Datetime NULL,
	[SYNCHSucc] Integer NULL,
	[SYNCHError] Integer NULL,
	[UPLGENLastExec] Datetime NULL,
	[UPLGENSucc] Integer NULL,
	[UPLGENError] Integer NULL,
Primary Key ([ClientId])
) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Birtig</ADDEDBY>
			<SQLVERSION>1.628</SQLVERSION>
			<RMTRACKLINK>3376</RMTRACKLINK>
			<REASON>CNF_AttributeTemplate
[added column Weight]</REASON>
			<TABLENAMES>CNF_AttributeTemplate=AttributeTemplateId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE [CNF_AttributeTemplate] 
ADD [Weight] int NOT NULL 
CONSTRAINT DF_CNF_AttributeTemplate_Weight DEFAULT 0
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.627</SQLVERSION>
			<RMTRACKLINK>3421</RMTRACKLINK>
			<REASON>CNF_PerformanceFilter
[0] add Table
[1] add FK on AttributeId
[2] add FK on PerformanceId
[3] add index on AttributeId
[4] add index on PerformanceId
			</REASON>
			<TABLENAMES>CNF_PerformanceFilter=PerformaceFilterId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_PerformanceFilter]
(
	[PerformaceFilterId] Integer Identity(1,1) NOT NULL, UNIQUE ([PerformaceFilterId]),
	[AttributeId] Integer NOT NULL,
	[PerformanceId] Integer NOT NULL,
Primary Key ([PerformaceFilterId])
) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_PerformanceFilter] 
  add  foreign key([AttributeId]) references [CNF_Attribute] ([AttributeId])
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_PerformanceFilter] 
  add  foreign key([PerformanceId]) references [CNF_Performance] ([PerformanceId])
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create Index [PerfFilter_AttributeId] 
  ON [CNF_PerformanceFilter] ([AttributeId] )
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create Index [PerfFilertPerfId] 
  ON [CNF_PerformanceFilter] ([PerformanceId] ) 
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.626</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>CNF_MatrixSheet
[0] add field MatrixSheetType null
[1] update old data
[2] set field as not null</REASON>
			<TABLENAMES>CNF_MatrixSheet=MatrixSheetId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT> Alter table CNF_MatrixSheet 
   add MatrixSheetType smallint null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_MatrixSheet
set MatrixSheetType=1
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> Alter table CNF_MatrixSheet 
   alter column MatrixSheetType smallint not null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>federicocaramella</ADDEDBY>
			<SQLVERSION>1.625</SQLVERSION>
			<RMTRACKLINK>3403</RMTRACKLINK>
			<REASON>Table CNF_PaymentMethod
[0] Add Field ForceInputAmount
[1] UPDATE ForceInputAmount= 1
[2] UPDATE ForceInputAmount= 0</REASON>
			<TABLENAMES>CNF_PaymentMethod=PaymentMethodId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE CNF_PaymentMethod
ADD ForceInputAmount smallint NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>UPDATE CNF_PaymentMethod SET ForceInputAmount = 1 
WHERE PaymentMethodId in (
SELECT PaymentMethodId FROM CNF_PaymentMethod
INNER JOIN CNF_Driver ON
CNF_Driver.DriverId = CNF_PaymentMethod.DriverId
where
CNF_Driver.DriverSubType = 20 )
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>UPDATE CNF_PaymentMethod SET ForceInputAmount = 0
WHERE PaymentMethodId in (
SELECT PaymentMethodId FROM CNF_PaymentMethod
INNER JOIN CNF_Driver ON
CNF_Driver.DriverId = CNF_PaymentMethod.DriverId
where
CNF_Driver.DriverSubType &lt;&gt; 20 )
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>federicocaramella</ADDEDBY>
			<SQLVERSION>1.624</SQLVERSION>
			<RMTRACKLINK>2503</RMTRACKLINK>
			<REASON>Table CNF_PaymentMethod
[0] Add Field Cashback
[1] UPDATE Casback = 1
[2] UPDATE Casback = 0</REASON>
			<TABLENAMES>CNF_PaymentMethod=PaymentMethodId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE CNF_PaymentMethod
ADD Cashback smallint NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>UPDATE CNF_PaymentMethod SET Cashback = 1 
WHERE PaymentMethodId in (
SELECT PaymentMethodId FROM CNF_PaymentMethod
INNER JOIN CNF_Driver ON
CNF_Driver.DriverId = CNF_PaymentMethod.DriverId
where
CNF_Driver.DriverSubType not in ( 2, 18 ,20,3 ) )
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>UPDATE CNF_PaymentMethod SET Cashback = 0 
WHERE PaymentMethodId in (
SELECT PaymentMethodId FROM CNF_PaymentMethod
INNER JOIN CNF_Driver ON
CNF_Driver.DriverId = CNF_PaymentMethod.DriverId
where
CNF_Driver.DriverSubType in ( 2, 18 ,20,3 ) )
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>federicocaramella</ADDEDBY>
			<SQLVERSION>1.623</SQLVERSION>
			<RMTRACKLINK>3167</RMTRACKLINK>
			<REASON>Table CNF_DocTemplate
[0] Add Field AttachedReport</REASON>
			<TABLENAMES>CNF_DocTemplate=DocTemplateId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE CNF_DocTemplate
ADD AttachedTicket smallint NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.622</SQLVERSION>
			<RMTRACKLINK>3097</RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES>DATA_SaleItem=SaleItemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_SaleItem add AttachedMediaId Integer;

Alter table [DATA_SaleItem] add constraint fkData_SaleItem_Data_Media_AttachedMediaID foreign key([MediaId]) references [DATA_Media] ([MediaId]); 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>OTNALO</ADDEDBY>
			<SQLVERSION>1.621</SQLVERSION>
			<RMTRACKLINK>2895</RMTRACKLINK>
			<REASON>DATA_TicketUsage
[0] Rename constrints linked with field MediaIdentifierId</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @name nvarchar(64);

SET @name = (select f.name
from sys.foreign_keys AS f
inner join sys.foreign_key_columns AS fc 
on  f.object_id = fc.constraint_object_id    
where  
f.parent_object_id = object_id(N'[dbo].[DATA_TicketUsage]')
and  f.referenced_object_id = object_id(N'[dbo].[DATA_MediaIdentifier]')
and COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'MediaIdentifierId'
); 
BEGIN TRANSACTION T1;
EXEC sp_rename @name, 'FK_DATA_Tick_Media', 'OBJECT';

COMMIT TRANSACTION T1;
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>federicocaramella</ADDEDBY>
			<SQLVERSION>1.620</SQLVERSION>
			<RMTRACKLINK>3307</RMTRACKLINK>
			<REASON>AccountHistory
[0] DROP VIEW AccountHistory
[1] CREATE VIEW AccountHistory</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>DROP VIEW AccountHistory
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE VIEW AccountHistory
AS
SELECT 
        DateOrd,
	DatePayment, 
	DateCreation, 
	ReservationAK, 
	TransactionAK,
	AccountId, 
	paymentamount,
	Debit, 
	Credit, 
	AmountDisc, 
	UserName,
	Note,
	SettleCreditPayType
FROM  (SELECT P.PaymentDate AS DateOrd,
              P.FPaymentDate AS DatePayment, 
              dtcreation.trdate AS DateCreation, 
			  dr.ReservationAK, 
			  dt.TransactionAK,
			  PC.AccountId, 
			  P.PaymentAmount  AS paymentamount, 
              CASE WHEN p.paymentamount &gt; 0 THEN p.paymentamount ELSE 0 END AS Debit, 
              CASE WHEN p.paymentamount &lt; 0 THEN case when dt.TransactionType &lt;&gt; 5 then ABS(p.paymentamount) else ABS(p.paymentamount) end ELSE 0 END AS Credit, 
			  PC.AmountDisc, 
              cu.UserName,
			  dn.Note,
			  (case when pc.SettleTransactionId = dt.TransactionId then '' else cl.description end) SettleCreditPayType
       FROM   dbo.DATA_PaymentCredit AS PC WITH(NOLOCK) INNER JOIN
              dbo.DATA_Payment AS P WITH(NOLOCK) ON P.PaymentId = PC.PaymentId left JOIN
              dbo.DATA_Transaction AS dt WITH(NOLOCK) ON dt.TransactionId = P.TransactionId LEFT OUTER JOIN
              dbo.CNF_User AS cu WITH(NOLOCK) ON cu.UserId = dt.UserId left JOIN
              dbo.DATA_Sale AS ds WITH(NOLOCK) ON ds.SaleId = dt.SaleId left JOIN
			  dbo.DATA_Note AS dn WITH(NOLOCK) ON dn.NoteKey = ds.SaleId AND dn.NoteType = 161 left JOIN
              dbo.DATA_Reservation AS dr WITH(NOLOCK) ON dr.SaleId = ds.SaleId LEFT OUTER JOIN
      (SELECT MIN(FTransactionDate) AS trdate, SaleId
       FROM dbo.DATA_Transaction AS dt  WITH(NOLOCK) 
       GROUP BY SaleId) AS dtcreation ON dtcreation.SaleId = ds.SaleId LEFT OUTER JOIN
      (SELECT MIN(PaymentType) AS pttype, TransactionId
       FROM dbo.DATA_Payment AS dp  WITH(NOLOCK) 	   
       GROUP BY TransactionId) AS cs ON cs.TransactionId = PC.SettleTransactionId LEFT OUTER JOIN
       dbo.CNF_LookUp AS cl ON cl.ItemId = cs.pttype AND cl.LookUpTableId = 7  AND P.PaymentStatus = 1 
UNION ALL
SELECT dt.TransactionDate AS DateOrd, 
       dt.FTransactionDate AS DatePayment, 
       dt.FTransactionDate AS DateCreation, 
	   NULL AS Expr1, 
	   NULL AS Expr2, 
	   L.ReferenceId AS AccountId, 
       L.EntryAmount AS Expr3, 
	   case when L.EntryAmount &gt; 0 then L.EntryAmount else 0 end AS Debit, 
	   case when L.EntryAmount &lt; 0 then ABS(L.EntryAmount) else 0 end AS Credit, 
	   NULL AS Expr4,
       cu.UserName,
	   NULL AS Expr5, 
	   cl.description SettleCreditPayType
FROM   dbo.DATA_Transaction AS dt WITH(NOLOCK) INNER JOIN
       dbo.DATA_Ledger AS L WITH(NOLOCK) ON L.TransactionId = dt.TransactionId INNER JOIN
       dbo.CNF_User AS cu WITH(NOLOCK) ON cu.UserId = dt.UserId inner JOIN
       dbo.CNF_LedgerAccount AS LA WITH(NOLOCK) ON L.LedgerAccountId = LA.LedgerAccountId INNER JOIN
      (SELECT MIN(PaymentType) AS pttype, TransactionId
       FROM dbo.DATA_Payment AS dp  WITH(NOLOCK) 
       GROUP BY TransactionId) AS cs_1 ON cs_1.TransactionId = dt.TransactionId LEFT OUTER JOIN
       dbo.CNF_LookUp AS cl ON cl.ItemId = cs_1.pttype AND cl.LookUpTableId = 7 
       WHERE (dt.TransactionType in (34,6)) 
	   AND LA.SystemAccountId= 7
	   AND (L.ReferenceTable = 197)) AS CreditDebit

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.619</SQLVERSION>
			<RMTRACKLINK>3333</RMTRACKLINK>
			<REASON>Stored Procedure

[0] removed store procedure on CNF_MatrixCellOption (insert)
[1] removed store procedure on CNF_MatrixCellOption (update)
[2]removed store procedure on CNF_MatrixCellOption (delete)</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>DROP PROCEDURE [dbo].[sp_ui_CNF_MatrixCellOption_insert]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DROP PROCEDURE [dbo].[sp_ui_CNF_MatrixCellOption_update]
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DROP PROCEDURE [dbo].[sp_ui_CNF_MatrixCellOption_delete]
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>davideapicella</ADDEDBY>
			<SQLVERSION>1.618</SQLVERSION>
			<RMTRACKLINK>905</RMTRACKLINK>
			<REASON>Table CNF_Seat
[0] Drop Column ReferenceTable
[1] Drop Column ReferenceId
[2] Drop Column BookingReference</REASON>
			<TABLENAMES>CNF_Seat=SeatId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Seat drop column ReferenceTable
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Seat drop column ReferenceId
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Seat drop column BookingReference
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>davideapicella</ADDEDBY>
			<SQLVERSION>1.617</SQLVERSION>
			<RMTRACKLINK>905</RMTRACKLINK>
			<REASON>Table CNF_Seat
[0] Add Field ShopCartItemGuid
[1] Add Field ShopCartItemId
[2] Add Field SaleItemGuid
[3] Move RefernceTable 159 (Data_Ticket)
[4] Move RefernceTable 164 (Data_SaleItem)
[5] Move RefernceTable 221 (Data_ShopCartItem)
[6] Move BookingReference
[7] add index on EnvelopeId
[8] add index on SeatMapId 
[9] add index on PerformanceId
[10] add index on SpaceStructureId 
[11] add index on SeatCategoryId 
[12] add index on DocumentId 
[13] add index on SaleItemId 
[14] add index on TicketId 
[15] add index on ShopCartItemGuid 
[16] add index on ShopCartItemId 
[17] add index on SaleItemGuid 
			</REASON>
			<TABLENAMES>CNF_Seat=SeatId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE [dbo].[CNF_SEAT]
ADD [ShopCartItemGuid] Varchar(38) NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE [dbo].[CNF_SEAT]
ADD [ShopCartItemId] Integer NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE [dbo].[CNF_SEAT]
ADD [SaleItemGuid] Varchar(38) NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>UPDATE CNF_SEAT
SET TicketId = ReferenceId
WHERE
ReferenceTable = 159
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>UPDATE CNF_SEAT
SET SaleItemId = ReferenceId
WHERE
ReferenceTable = 164
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>UPDATE CNF_SEAT
SET ShopCartItemId = ReferenceId
WHERE
ReferenceTable = 221
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>UPDATE CNF_SEAT
SET ShopCartItemGuid = BookingReference
WHERE
ReferenceTable = 221
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if not Exists(SELECT 1
              FROM sys.indexes 
              WHERE name=N'IDX_CNF_Seat_EnvelopeId' AND object_id = OBJECT_ID('CNF_Seat'))
BEGIN              
  CREATE NONCLUSTERED INDEX [IDX_CNF_Seat_EnvelopeId] ON [dbo].[CNF_Seat]
    ([EnvelopeId])    
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if not Exists(SELECT 1
              FROM sys.indexes 
              WHERE name=N'IDX_CNF_Seat_SeatMapId' AND object_id = OBJECT_ID('CNF_Seat'))
BEGIN              
  CREATE NONCLUSTERED INDEX [IDX_CNF_Seat_SeatMapId] ON [dbo].[CNF_Seat]
    ([SeatMapId])
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if not Exists(SELECT 1
              FROM sys.indexes 
              WHERE name=N'IDX_CNF_Seat_PerformanceId' AND object_id = OBJECT_ID('CNF_Seat'))
BEGIN              
  CREATE NONCLUSTERED INDEX [IDX_CNF_Seat_PerformanceId] ON [dbo].[CNF_Seat]
    ([PerformanceId])
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if not Exists(SELECT 1
              FROM sys.indexes 
              WHERE name=N'IDX_CNF_Seat_SpaceStructureId' AND object_id = OBJECT_ID('CNF_Seat'))
BEGIN              
  CREATE NONCLUSTERED INDEX [IDX_CNF_Seat_SpaceStructureId] ON [dbo].[CNF_Seat]
    ([SpaceStructureId])
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if not Exists(SELECT 1
              FROM sys.indexes 
              WHERE name=N'IDX_CNF_Seat_SeatCategoryId' AND object_id = OBJECT_ID('CNF_Seat'))
BEGIN              
  CREATE NONCLUSTERED INDEX [IDX_CNF_Seat_SeatCategoryId] ON [dbo].[CNF_Seat]
    ([SeatCategoryId])
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if not Exists(SELECT 1
              FROM sys.indexes 
              WHERE name=N'IDX_CNF_Seat_DocumentId' AND object_id = OBJECT_ID('CNF_Seat'))
BEGIN              
  CREATE NONCLUSTERED INDEX [IDX_CNF_Seat_DocumentId] ON [dbo].[CNF_Seat]
    ([DocumentId])
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if not Exists(SELECT 1
              FROM sys.indexes 
              WHERE name=N'IDX_CNF_Seat_SaleItemId' AND object_id = OBJECT_ID('CNF_Seat'))
BEGIN              
  CREATE NONCLUSTERED INDEX [IDX_CNF_Seat_SaleItemId] ON [dbo].[CNF_Seat]
    ([SaleItemId])
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if not Exists(SELECT 1
              FROM sys.indexes 
              WHERE name=N'IDX_CNF_Seat_TicketId' AND object_id = OBJECT_ID('CNF_Seat'))
BEGIN              
  CREATE NONCLUSTERED INDEX [IDX_CNF_Seat_TicketId] ON [dbo].[CNF_Seat]
    ([TicketId])
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if not Exists(SELECT 1
              FROM sys.indexes 
              WHERE name=N'IDX_CNF_Seat_ShopCartItemGuid' AND object_id = OBJECT_ID('CNF_Seat'))
BEGIN              
  CREATE NONCLUSTERED INDEX [IDX_CNF_Seat_ShopCartItemGuid] ON [dbo].[CNF_Seat]
    ([ShopCartItemGuid])
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if not Exists(SELECT 1
              FROM sys.indexes 
              WHERE name=N'IDX_CNF_Seat_ShopCartItemId' AND object_id = OBJECT_ID('CNF_Seat'))
BEGIN              
  CREATE NONCLUSTERED INDEX [IDX_CNF_Seat_ShopCartItemId] ON [dbo].[CNF_Seat]
    ([ShopCartItemId])
END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if not Exists(SELECT 1
              FROM sys.indexes 
              WHERE name=N'IDX_CNF_Seat_SaleItemGuid' AND object_id = OBJECT_ID('CNF_Seat'))
BEGIN              
  CREATE NONCLUSTERED INDEX [IDX_CNF_Seat_SaleItemGuid] ON [dbo].[CNF_Seat]
    ([SaleItemGuid])
END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>federicocaramella</ADDEDBY>
			<SQLVERSION>1.616</SQLVERSION>
			<RMTRACKLINK>3307</RMTRACKLINK>
			<REASON>AccountHistory
[0] CREATE VIEW AccountHistory</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE VIEW AccountHistory
AS
SELECT 
	DatePayment, 
	DateCreation, 
	ReservationAK, 
	TransactionAK,
	AccountId, 
	paymentamount, 
	Debit, 
	Credit, 
	AmountDisc, 
	UserName,
	Note,
	SettleCreditPayType
FROM  (SELECT P.FPaymentDate AS DatePayment, 
              dtcreation.trdate AS DateCreation, 
			  dr.ReservationAK, 
			  dt.TransactionAK,
			  PC.AccountId, 
			  - P.PaymentAmount AS paymentamount, 
              CASE WHEN p.paymentamount &gt; 0 THEN p.paymentamount ELSE 0 END AS Debit, 
              CASE WHEN p.paymentamount &lt; 0 THEN - p.paymentamount + PC.AmountDisc ELSE 0 END AS Credit, 
			  PC.AmountDisc, 
              cu.UserName,
			  dn.Note,
			  (case when pc.SettleTransactionId = dt.TransactionId then '' else cl.description end) SettleCreditPayType
       FROM   dbo.DATA_PaymentCredit AS PC WITH(NOLOCK) INNER JOIN
              dbo.DATA_Payment AS P WITH(NOLOCK) ON P.PaymentId = PC.PaymentId LEFT OUTER JOIN
              dbo.DATA_Transaction AS dt WITH(NOLOCK) ON dt.TransactionId = P.TransactionId LEFT OUTER JOIN
              dbo.CNF_User AS cu WITH(NOLOCK) ON cu.UserId = dt.UserId LEFT OUTER JOIN
              dbo.DATA_Sale AS ds WITH(NOLOCK) ON ds.SaleId = dt.SaleId LEFT OUTER JOIN
			  dbo.DATA_Note AS dn WITH(NOLOCK) ON dn.NoteKey = ds.SaleId AND dn.NoteType = 161 LEFT OUTER JOIN
              dbo.DATA_Reservation AS dr WITH(NOLOCK) ON dr.SaleId = ds.SaleId LEFT OUTER JOIN
      (SELECT MIN(FTransactionDate) AS trdate, SaleId
       FROM dbo.DATA_Transaction AS dt  WITH(NOLOCK) 
       GROUP BY SaleId) AS dtcreation ON dtcreation.SaleId = ds.SaleId LEFT OUTER JOIN
      (SELECT MIN(PaymentType) AS pttype, TransactionId
       FROM dbo.DATA_Payment AS dp  WITH(NOLOCK) 
       GROUP BY TransactionId) AS cs ON cs.TransactionId = PC.SettleTransactionId LEFT OUTER JOIN
       dbo.CNF_LookUp AS cl ON cl.ItemId = cs.pttype AND cl.LookUpTableId = 7 
UNION ALL
SELECT dt.FTransactionDate AS DatePayment, 
       dt.FTransactionDate AS DateCreation, 
	   NULL AS Expr1, 
	   NULL AS Expr2, 
	   L.ReferenceId AS AccountId, 
       - L.EntryAmount AS Expr3, 
	   NULL AS Debit, 
	   - L.EntryAmount AS Credit, 
	   NULL AS Expr4,
       cu.UserName,
	   NULL AS Expr5, 
	   cl.description SettleCreditPayType
FROM   dbo.DATA_Transaction AS dt WITH(NOLOCK) INNER JOIN
       dbo.DATA_Ledger AS L WITH(NOLOCK) ON L.TransactionId = dt.TransactionId INNER JOIN
       dbo.CNF_User AS cu WITH(NOLOCK) ON cu.UserId = dt.UserId LEFT OUTER JOIN
       dbo.CNF_LedgerAccount AS LA WITH(NOLOCK) ON L.LedgerAccountId = LA.LedgerAccountId INNER JOIN
      (SELECT MIN(PaymentType) AS pttype, TransactionId
       FROM dbo.DATA_Payment AS dp  WITH(NOLOCK) 
       GROUP BY TransactionId) AS cs_1 ON cs_1.TransactionId = dt.TransactionId LEFT OUTER JOIN
       dbo.CNF_LookUp AS cl ON cl.ItemId = cs_1.pttype AND cl.LookUpTableId = 7 
       WHERE (dt.TransactionType in (34,6)) AND (LA.AccountType = 6) AND (LA.ParentAccountId = 17) AND (L.ReferenceTable = 197)) AS CreditDebit

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>OTNALO</ADDEDBY>
			<SQLVERSION>1.615</SQLVERSION>
			<RMTRACKLINK>3265</RMTRACKLINK>
			<REASON>Table DATA_Deposit
[0] Add Field InitialDepositType</REASON>
			<TABLENAMES>DATA_Deposit=DepositId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE [dbo].[DATA_Deposit]
ADD [InitialDepositType] smallint NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>federicocaramella</ADDEDBY>
			<SQLVERSION>1.614</SQLVERSION>
			<RMTRACKLINK>2945</RMTRACKLINK>
			<REASON>[0] Add Field LocationId
[6] Add foreign key for CNF_Subscription on CNF_Location</REASON>
			<TABLENAMES>CNF_Subscription=SubscriptionId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE CNF_Subscription
ADD LocationId Integer NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Subscription] add  foreign key([LocationId]) references [CNF_Location] ([LocationId])
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.613</SQLVERSION>
			<RMTRACKLINK>3043</RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES>CNF_System=SystemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>  alter table cnf_system add WorkstationId integer null;  

  Alter table [CNF_System] add constraint fkCNF_System_Workstation foreign key([WorkstationId]) references [CNF_Workstation] ([WorkstationId]);
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>federicocaramella</ADDEDBY>
			<SQLVERSION>1.612</SQLVERSION>
			<RMTRACKLINK>2945</RMTRACKLINK>
			<REASON>CNF_Subscription
CNF_Subscription2Performance
[0] Drop Table CNF_Subscription2Performance
[1] DropTable CNF_Subscription
[2] Create Table CNF_Subscription
[3] Create Table CNF_Subscription2Performance
[4] Add foreign key for CNF_Subscription on CNF_System
[5] Add foreign key for CNF_Subscription on DATA_Account
[6] Add foreign key for CNF_Subscription on CNF_DmgCategory
[7] Add foreign key for CNF_Subscription on CNF_AttributeTemplate
[8] Add foreign key for CNF_Subscription2Performance on CNF_Subscription
[9] Add foreign key for CNF_Subscription2Performance on CNF_Event
[10] Add foreign key for CNF_Subscription2Performance on CNF_Performance</REASON>
			<TABLENAMES>CNF_Subscription=SubscriptionId
CNF_Subscription2Performance=Subscription2PerformanceId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Drop table [CNF_Subscription2Performance]
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Drop table [CNF_Subscription]
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> Create table [CNF_Subscription]
(
	[SubscriptionId] Integer Identity(1,1) NOT NULL, UNIQUE ([SubscriptionId]),
	[SystemId] Integer NOT NULL,
	[AccountId] Integer NULL,
	[DmgCategoryId] Integer NULL,
	[AttributeTemplateId] Integer NULL,
	[SubscriptionAK] Varchar(32) NOT NULL,
	[SubscriptionType] Smallint NOT NULL,
	[SubscriptionCode] Nvarchar(10) NOT NULL,
	[SubscriptionName] Nvarchar(50) NOT NULL,
	[SubscriptionTitle] Nvarchar(50) NULL,
	[Status] Smallint NOT NULL,
	[StartDate] Datetime NOT NULL,
	[EndDate] Datetime NOT NULL,
	[Note] Ntext NULL,
	[MinPerformance] Integer NULL,
	[MaxPerformance] Integer NULL,
Primary Key ([SubscriptionId])
) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_Subscription2Performance]
(
	[Subscription2PerformanceId] Integer Identity(1,1) NOT NULL, UNIQUE ([Subscription2PerformanceId]),
	[SubscriptionId] Integer NOT NULL,
	[EventId] Integer NOT NULL,
	[PerformanceId] Integer NOT NULL,
Primary Key ([Subscription2PerformanceId])
) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Subscription] add  foreign key([SystemId]) references [CNF_System] ([SystemId])
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Subscription] add  foreign key([AccountId]) references [DATA_Account] ([AccountId])
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Subscription] add  foreign key([DmgCategoryId]) references [CNF_DmgCategory] ([DmgCategoryId])
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Subscription] add  foreign key([AttributeTemplateId]) references [CNF_AttributeTemplate] ([AttributeTemplateId])
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Subscription2Performance] add  foreign key([SubscriptionId]) references [CNF_Subscription] ([SubscriptionId])
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Subscription2Performance] add  foreign key([EventId]) references [CNF_Event] ([EventId])
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Subscription2Performance] add  foreign key([PerformanceId]) references [CNF_Performance] ([PerformanceId])
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>OTNALO</ADDEDBY>
			<SQLVERSION>1.611</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>Some index colud be present but I verify before creation

DATA_Ticket2Media
  add index on TicketId
  add index on MediaId

DATA_Transaction2Ticket
  add index on TicketId
  add index on TransactionId

DATA_Transaction2Media
  add index on MediaId
  add index on TransactionId

DATA_SaleItem2Account
  add index on AccountId

DATA_SaleItem2Performance
  add index on PerformanceId</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>if not Exists(SELECT 1
                FROM sys.indexes 
               WHERE name=N'idxTicket2Media_TicketId' AND object_id = OBJECT_ID('DATA_Ticket2Media'))
 BEGIN              
CREATE NONCLUSTERED INDEX [idxTicket2Media_TicketId] ON [dbo].[DATA_Ticket2Media]
  ([TicketId])
 END

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if not Exists(SELECT 1
                FROM sys.indexes 
               WHERE name=N'IDX_Ticket2Media_MediaId' AND object_id = OBJECT_ID('DATA_Ticket2Media'))
 BEGIN              
CREATE NONCLUSTERED INDEX [IDX_Ticket2Media_MediaId] ON [dbo].[DATA_Ticket2Media]
  ([MediaId])
 END

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if not Exists(SELECT 1
                FROM sys.indexes 
               WHERE name=N'idxTransaction2Ticket_TicketId' AND object_id = OBJECT_ID('DATA_Transaction2Ticket'))
 BEGIN              
CREATE NONCLUSTERED INDEX [idxTransaction2Ticket_TicketId] ON [dbo].[DATA_Transaction2Ticket]
  ([TicketId])
 END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if not Exists(SELECT 1
                FROM sys.indexes 
               WHERE name=N'idxTransaction2Ticket_TransactionId' AND object_id = OBJECT_ID('DATA_Transaction2Ticket'))
 BEGIN              
CREATE NONCLUSTERED INDEX [idxTransaction2Ticket_TransactionId] ON [dbo].[DATA_Transaction2Ticket]
  ([TransactionId])
 END

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if not Exists(SELECT 1
                FROM sys.indexes 
               WHERE name=N'idxTransaction2Media_MediaId' AND object_id = OBJECT_ID('DATA_Transaction2Media'))
 BEGIN              
CREATE NONCLUSTERED INDEX [idxTransaction2Media_MediaId] ON [dbo].[DATA_Transaction2Media]
  ([MediaId])
 END

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if not Exists(SELECT 1
                FROM sys.indexes 
               WHERE name=N'idxTransaction2Media_TransactionId' AND object_id = OBJECT_ID('DATA_Transaction2Media'))
 BEGIN              
CREATE NONCLUSTERED INDEX [idxTransaction2Media_TransactionId] ON [dbo].[DATA_Transaction2Media]
  ([TransactionId])
 END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if not Exists(SELECT 1
                FROM sys.indexes 
               WHERE name=N'idxSaleItem2Account_AccountId' AND object_id = OBJECT_ID('DATA_SaleItem2Account'))
 BEGIN              
CREATE NONCLUSTERED INDEX [idxSaleItem2Account_AccountId] ON [dbo].[DATA_SaleItem2Account]
  ([AccountId])
 END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if not Exists(SELECT 1
                FROM sys.indexes 
               WHERE name=N'idxSaleItem2Performance_PerformanceId' AND object_id = OBJECT_ID('DATA_SaleItem2Performance'))
 BEGIN              
CREATE NONCLUSTERED INDEX [idxSaleItem2Performance_PerformanceId] ON [dbo].[DATA_SaleItem2Performance]
  ([PerformanceId])
 END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.610</SQLVERSION>
			<RMTRACKLINK>3054</RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>insert into  DATA_AccountRelationship (FatherAccountId,ChildAccountId,RelationType)
select
ParentAccountId,
AccountId,
0
from
data_account da left join
DATA_AccountRelationship dar on dar.FatherAccountId = da.ParentAccountId and dar.ChildAccountId = da.AccountId
where
dar.AccountRelationshipId is null and
not da.ParentAccountId is null

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>federicocaramella</ADDEDBY>
			<SQLVERSION>1.609</SQLVERSION>
			<RMTRACKLINK>2945</RMTRACKLINK>
			<REASON>CNF_Subscription
CNF_Subscription2Performance
[0] Create Table CNF_Subscription
[1] Create Table CNF_Subscription2Performance
[2] Add foreign key for CNF_Subscription on CNF_System
[3] Add foreign key for CNF_Subscription on DATA_Account
[4] Add foreign key for CNF_Subscription on CNF_DmgCategory
[5] Add foreign key for CNF_Subscription on CNF_AttributeTemplate
[6] Add foreign key for CNF_Subscription2Performance on CNF_Subscription
[7] Add foreign key for CNF_Subscription2Performance on CNF_Event
[8] Add foreign key for CNF_Subscription2Performance on CNF_Performance</REASON>
			<TABLENAMES>CNF_Subscription=SubscriptionId
CNF_Subscription2Performance=Subscription2PerformanceId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>
Create table [CNF_Subscription]
(
	[SubscriptionId] Integer Identity(1,1) NOT NULL, UNIQUE ([SubscriptionId]),
	[SystemId] Integer NOT NULL,
	[AccountId] Integer NOT NULL,
	[DmgCategoryId] Integer NOT NULL,
	[AttributeTemplateId] Integer NOT NULL,
	[SubscriptionAK] Varchar(32) NOT NULL,
	[SubscriptionType] Smallint NOT NULL,
	[SubscriptionCode] Nvarchar(10) NOT NULL,
	[SubscriptionName] Nvarchar(50) NOT NULL,
	[SubscriptionTitle] Nvarchar(50) NULL,
	[Status] Smallint NOT NULL,
	[StartDate] Datetime NOT NULL,
	[EndDate] Datetime NOT NULL,
	[Note] Ntext NULL,
	[MinPerformance] Integer NULL,
	[MaxPerformance] Integer NULL,
Primary Key ([SubscriptionId])
) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>
Create table [CNF_Subscription2Performance]
(
	[Subscription2PerformanceId] Integer Identity(1,1) NOT NULL, UNIQUE ([Subscription2PerformanceId]),
	[SubscriptionId] Integer NOT NULL,
	[EventId] Integer NOT NULL,
	[PerformanceId] Integer NOT NULL,
Primary Key ([Subscription2PerformanceId])
) 


				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Subscription] add  foreign key([SystemId]) references [CNF_System] ([SystemId])
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Subscription] add  foreign key([AccountId]) references [DATA_Account] ([AccountId])
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Subscription] add  foreign key([DmgCategoryId]) references [CNF_DmgCategory] ([DmgCategoryId])
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Subscription] add  foreign key([AttributeTemplateId]) references [CNF_AttributeTemplate] ([AttributeTemplateId])
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Subscription2Performance] add  foreign key([SubscriptionId]) references [CNF_Subscription] ([SubscriptionId])
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Subscription2Performance] add  foreign key([EventId]) references [CNF_Event] ([EventId])
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Subscription2Performance] add  foreign key([PerformanceId]) references [CNF_Performance] ([PerformanceId])
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>1.608</SQLVERSION>
			<RMTRACKLINK>1035</RMTRACKLINK>
			<REASON>Add field RecursiveDesc nVarChar(200) CNF_PerformanceCategory </REASON>
			<TABLENAMES>CNF_PerformanceCategory=PerformanceCategoryId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE CNF_PerformanceCategory
ADD RecursiveDesc NVarChar(200) 
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>1.607</SQLVERSION>
			<RMTRACKLINK>1035</RMTRACKLINK>
			<REASON>Add field Recursive name nVarChar(200) CNF_PerformanceCategory </REASON>
			<TABLENAMES>CNF_PerformanceCategory=PerformanceCategoryId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE CNF_PerformanceCategory
ADD RecursiveName NVarChar(200) 
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.606</SQLVERSION>
			<RMTRACKLINK>2927</RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES>DATA_TransactionItem=ItemId
DATA_SaleItem=SaleItemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_SaleItem add PersonOnEachMediaIdentifier smallint null;
alter table DATA_TransactionItem add PersonOnEachMediaIdentifier smallint null;

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.605</SQLVERSION>
			<RMTRACKLINK>2927</RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES>DATA_SaleItem2Account=SaleItem2AccountId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_SaleItem2Account add Used smallint null;
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.604</SQLVERSION>
			<RMTRACKLINK>2927</RMTRACKLINK>
			<REASON></REASON>
			<TABLENAMES>DATA_Media=MediaID
DATA_MediaIdentifier=MediaIdentifierId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table data_media add [LastSerial] Integer NULL;
alter table data_media add [LastAccountId] Integer NULL;


alter table DATA_MediaIdentifier add [Serial] Integer NULL;
alter table DATA_MediaIdentifier add [AccountId] Integer NULL;


Alter table [DATA_MediaIdentifier] add constraint fkDATA_MediaIdentifier_DATA_Account foreign key([AccountId]) references [DATA_Account] ([AccountId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>1.603</SQLVERSION>
			<RMTRACKLINK>936</RMTRACKLINK>
			<REASON>Capacity and Seat  - Improve table SEAT_CNF_SpaceStructureSeat, CNF_Seat and CNF_SpaceStructure

SEAT_CNF_SpaceStructureSeat
[0] - Add New fields: 
          - DocumentId Integer
          - Version Integer
          - SettingDocumentId Integer
          - SettingVersion Integer 

CNF_Seat
[1] - Add new fields: 
          - PositionType smallint not null
          - DocumentId Integer
          - SaleItemId Integer
          - TicketId Integer
[2] - Copy values from old field (FalgInfo) to new one  (PositionType)
[3] - Set field PositionType as not null
[4] - Remove Fields:
           - FlagInfo 
           - CapacityId
[5] - Add foreign key for CNF_Seat  on DATA_SaleItem (nullable)
[6] - Add foreign key for CNF_Seat  on DATA_Ticket (nullable)

CNF_SpaceStructure - Change Field ExternalReference from Char(10) to Varchar(10)

[7] - DROP INDEX [idxCNF_SpaceStructure_AccessConfId_ExternalReference] ON [dbo].[CNF_SpaceStructure]
[8] - ALTER TABLE CNF_SpaceStructure ALTER COLUMN ExternalReference varchar(10)
[9] - Copy data (trimmed) itself
[10] - Add index [idxCNF_SpaceStructure_AccessConfId_ExternalReference] ON [dbo].[CNF_SpaceStructure]


			</REASON>
			<TABLENAMES>SEAT_CNF_SpaceStructureSeat=SpaceStructureSeatId
CNF_Seat=SeatId
CNF_SpaceStructure=SpaceStructureId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>   alter table SEAT_CNF_SpaceStructureSeat add DocumentId Int NULL;    
   alter table SEAT_CNF_SpaceStructureSeat add Version Int NULL;    
   alter table SEAT_CNF_SpaceStructureSeat add SettingDocumentId Int NULL;    
   alter table SEAT_CNF_SpaceStructureSeat add SettingVersion Int NULL;    

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>   alter table CNF_Seat add PositionType SmallInt NULL;
   alter table CNF_Seat add DocumentId Int NULL;
   alter table CNF_Seat add SaleItemId Int NULL;
   alter table CNF_Seat add TicketId Int NULL;

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_Seat
set PositionType = FlagInfo
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Seat
  alter column PositionType smallint not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Seat drop column FlagInfo;
alter table CNF_Seat drop column CapacityId;



				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> Alter table [CNF_Seat] 
   add  foreign key([SaleItemId]) references [DATA_SaleItem] ([SaleItemId])
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> Alter table [CNF_Seat] 
   add  foreign key([TicketId]) references [DATA_Ticket] ([TicketId])
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DROP INDEX [idxCNF_SpaceStructure_AccessConfId_ExternalReference] ON [CNF_SpaceStructure]


				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE CNF_SpaceStructure ALTER COLUMN ExternalReference varchar(10)

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Update CNF_SpaceStructure set ExternalReference = ltrim(rtrim(ExternalReference))
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE NONCLUSTERED INDEX [idxCNF_SpaceStructure_AccessConfId_ExternalReference] ON [dbo].[CNF_SpaceStructure]
(
	[AccessConfigurationId] ASC,
	[ExternalReference] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>OTNALO</ADDEDBY>
			<SQLVERSION>1.602</SQLVERSION>
			<RMTRACKLINK>3166</RMTRACKLINK>
			<REASON>CNF_Promotion
[0] add field MaxCouponsOnTransaction int null</REASON>
			<TABLENAMES>CNF_Promotion=PromotionId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE CNF_Promotion
ADD MaxCouponsOnTransaction int NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>1.601</SQLVERSION>
			<RMTRACKLINK>3241</RMTRACKLINK>
			<REASON>Update View
vwStock_Inventory
Add "with"  statement before "nolock" when missed</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER view [dbo].[vwStock_Inventory]
as
select
SCP.MinStock,
SCP.MatrixCellId as MatrixcellId,
SCP.SKU as Product,
STOCK_CNF_Warehouse.WarehouseId as  WarehouseId,
STOCK_CNF_Um.Description Um,
STOCK_CNF_Warehouse.Description as WareHouse,
sum(qtyleft) qtyleft,
sum(qtyout) qtyout,
sum(qtytomove) qtytomove
from
(select
matrixcellid,
warehouseid,
sum(qtyleft) qtyleft,
0 qtyout,
0 qtytomove
from
stock_movement with (nolock)
where
InOut = 1
group by
matrixcellid,
warehouseid
union
select
matrixcellid,
warehouseid,
0,
sum(qty) qtyout,
sum(qty-qtymoved) qtytomove
from
stock_movement with (nolock)
where
stock_movement.InOut = -1 and 
stock_movement.MovementDate = dateadd(day,datediff(day,0,getdate()),0)
group by
matrixcellid,
warehouseid) as inventory  inner join
STOCK_CNF_Product SCP with (nolock) on inventory.MatrixCellId = SCP.MatrixCellId inner join 
STOCK_CNF_Warehouse with (nolock) on inventory.warehouseid = STOCK_CNF_Warehouse.warehouseid inner join
STOCK_CNF_Um with (nolock) on STOCK_CNF_Um.UmId=SCP.UmId
group by
SCP.MinStock,
SCP.MatrixCellId ,
SCP.SKU,
STOCK_CNF_Warehouse.WarehouseId ,
STOCK_CNF_Um.Description ,
STOCK_CNF_Warehouse.Description



				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>1.600</SQLVERSION>
			<RMTRACKLINK>3248</RMTRACKLINK>
			<REASON>Update Store Procedure 
spui_GetCounter
due smallint instead integer problem

			</REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER PROCEDURE [dbo].[spui_GetCounter]
 -- Add the parameters for the stored procedure here
 @CounterType smallint,
 @IdentifierAK varchar(32),
 @ReferenceTime varchar(32),
 @Counter integer output  
AS
BEGIN
declare @CounterId  integer

 SET NOCOUNT ON;

 select @Counter = Counter ,
     @CounterId = CounterId
 from DATA_Counter (nolock)
 where CounterType = @CounterType and IdentifierAK = @IdentifierAK and
  IsNull(@ReferenceTime,'NEVER') = IsNull(ReferenceTime,'NEVER')


 if @Counter is null 
 begin
   select @Counter = 1

   insert into DATA_Counter (CounterType, IdentifierAK, ReferenceTime, Counter)
    values            (@CounterType, @IdentifierAK, IsNull(@ReferenceTime,'Never'), @Counter) 

 end
 else
 begin

   select @Counter = @Counter+1

   update DATA_Counter
   set    Counter = @Counter
   where  CounterId =  @CounterId

 end

end
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>federicocaramella</ADDEDBY>
			<SQLVERSION>1.599</SQLVERSION>
			<RMTRACKLINK>3124</RMTRACKLINK>
			<REASON>DATA_Account
[0] add field AccountGUID nVarChar(200) null</REASON>
			<TABLENAMES>DATA_Account=AccountId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Account
  add AccountGUID nVarChar(200) null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>federicocaramella</ADDEDBY>
			<SQLVERSION>1.598</SQLVERSION>
			<RMTRACKLINK>3214</RMTRACKLINK>
			<REASON>CNF_SeatCategory
[0] add field Weight Integer null</REASON>
			<TABLENAMES>CNF_SeatCategory=SeatCategoryId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_SeatCategory
  add Weight int null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.597</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>Add default permission for seat Category

WARNING!!!!
Due a problem about MERGE SQL Statement happened sometimes during session test
(missing semicolon at the end of command), this patch will be applied trhought a Stored Procedure </REASON>
			<TABLENAMES></TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>create procedure [sp_UPD_SEATCATEGORY_PERMISSION]	
as
begin
MERGE INTO CNF_SeatCategory_Permission AS Target
USING 
(Select
  SC.SeatCategoryId,
  (select top 1 SystemId from CNF_System) as SitePer,  
  1 as Allow
  from CNF_SeatCategory as SC
  where SC.PerformanceId is null
   ) AS Source ON (Target.seatCategoryId = Source.seatCategoryId)  
WHEN NOT MATCHED THEN
    INSERT (seatCategoryId,
            SiteId,
            Allow) VALUES (
            Source.seatCategoryId,
            Source.SitePer,
            1);
 end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>
  EXECUTE sp_UPD_SEATCATEGORY_PERMISSION
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>

 DROP PROCEDURE sp_UPD_SEATCATEGORY_PERMISSION
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>skhan</ADDEDBY>
			<SQLVERSION>1.596</SQLVERSION>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>SAK Added extra fields to hold credit card return values.</REASON>
			<TABLENAMES>DATA_PaymentCard=PaymentId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>   alter table DATA_PaymentCard add SignLineC Varchar(30) NULL;    
   alter table DATA_PaymentCard add TransactionStatus Varchar(4) NULL;    
   alter table DATA_PaymentCard add PinIndicator Varchar(30) NULL;
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.595</SQLVERSION>
			<RMTRACKLINK>3207</RMTRACKLINK>
			<REASON>[0] add Primary Key on DATA_MediaIdentifierBlackList</REASON>
			<TABLENAMES>DATA_MediaIdentifierBlackList=MediaBlackListId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_MediaIdentifierBlackList
  add Primary Key ([MediaBlackListId])
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AndreaL (OTNALO)</ADDEDBY>
			<SQLVERSION>1.594</SQLVERSION>
			<RMTRACKLINK>2923</RMTRACKLINK>
			<REASON>CNF_ExternalTicketRange 
[1] add new field ExternalTicketRangeIdParent int</REASON>
			<TABLENAMES>CNF_ExternalTicketRange=ExternalTicketRangeId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE [dbo].[CNF_ExternalTicketRange]
ADD [ExternalTicketRangeIdParent] int NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.593</SQLVERSION>
			<RMTRACKLINK>3162 </RMTRACKLINK>
			<REASON>CNF_SeatCategoryPermission
[0] create table
[1] add FK on SeatCategory
[2] add FK on Sited
[3] add FK on WorkstationId
[4] add FK on DmgCateogryId
[5] add FK on UserId
[6]Add FK on UserGroypId
[7]Add FK on AccountId
[8]add FK on OperatingAreaId</REASON>
			<TABLENAMES>CNF_SeatCategory_Permission=SeatCategoryPermissionId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_SeatCategory_Permission]
(
	[SeatCategoryPermissionId] Integer Identity(1,1) NOT NULL, UNIQUE ([SeatCategoryPermissionId]),
	[SeatCategoryId] Integer NOT NULL,
	[SiteId] Integer NULL,
	[WorkstationId] Integer NULL,
	[DmgCategoryId] Integer NULL,
	[UserId] Integer NULL,
	[UserGroupId] Integer NULL,
	[AccountId] Integer NULL,
	[OperatingAreaId] Integer NULL,
	[Allow] Smallint NULL

Primary Key ([SeatCategoryPermissionId])
) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> Alter table [CNF_SeatCategory_Permission] 
   add  foreign key([SeatCategoryId]) references [CNF_SeatCategory] ([SeatCategoryId])
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> Alter table [CNF_SeatCategory_Permission] 
   add  foreign key([SiteId]) references [CNF_Site] ([SiteId])
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_SeatCategory_Permission] 
  add  foreign key([WorkstationId]) references [CNF_Workstation] ([WorkstationId])
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_SeatCategory_Permission] 
  add  foreign key([DmgCategoryId]) references [CNF_DmgCategory] ([DmgCategoryId])
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_SeatCategory_Permission] 
  add  foreign key([UserId]) references [CNF_User] ([UserId])
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_SeatCategory_Permission] 
  add  foreign key([UserGroupId]) references [CNF_UserGroup] ([UserGroupId])
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> Alter table [CNF_SeatCategory_Permission] 
   add  foreign key([AccountId]) references [DATA_Account] ([AccountId])
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> Alter table [CNF_SeatCategory_Permission] 
   add  foreign key([OperatingAreaId]) references [CNF_OperatingArea] ([OperatingAreaId])
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>skhan</ADDEDBY>
			<SQLVERSION>1.592</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>SAK Added extra fields to hold credit card return values.</REASON>
			<TABLENAMES>DATA_PaymentCard=PaymentId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_PaymentCard add TerminalId Varchar(10) NULL;
alter table DATA_PaymentCard add AppId Varchar(32) NULL;
alter table DATA_PaymentCard add VerificationResult Varchar(10) NULL;
alter table DATA_PaymentCard add AppLabel Varchar(16) NULL;
alter table DATA_PaymentCard add TransactionType Varchar(10) NULL;
alter table DATA_PaymentCard add B24Code Varchar(5) NULL;
alter table DATA_PaymentCard add ISOCode Varchar(5) NULL;
alter table DATA_PaymentCard add CardName Varchar(30) NULL;
alter table DATA_PaymentCard add SignLine Varchar(30) NULL;
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>1.591</SQLVERSION>
			<RMTRACKLINK>1035</RMTRACKLINK>
			<REASON>CNF_PerformanceCategory
CNF_PerformanceCategoryValidity
[0] Create Table CNF_PerformanceCategory
[1] Create Table CNF_PerformanceCategoryValidity
[2] Add self foreign key on CNF_PerformanceCategory (ParentId) 
[3] Add foreign key for CNF_PerformanceCategoryValidity on CNF_Performance (nullable)
[4] Add foreign key for CNF_PerformanceCategoryValidity on CNF_Event  (nullable)
[5] Add foreign key for CNF_PerformanceCategoryValidity on CNF_PerformanceCategory 

			</REASON>
			<TABLENAMES>CNF_PerformanceCategory=PerformanceCategoryId
CNF_PerformanceCategoryValidity=PerfCatValidityId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_PerformanceCategory]
(
	[PerformanceCategoryId] Integer Identity(1,1) NOT NULL, UNIQUE ([PerformanceCategoryId]),
	[PerformanceCategoryCode] Varchar(10) NOT NULL,
	[PerformanceCategoryDescription] Nvarchar(100) NULL,
	[ParentId] Integer NULL,
	[Position] Integer NOT NULL,
	[Level] Integer NOT NULL,
        [ActivationType] Integer NULL,
Primary Key ([PerformanceCategoryId])
) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_PerformanceCategoryValidity]
(
	[PerfCatValidityId] Integer Identity(1,1) NOT NULL, UNIQUE ([PerfCatValidityId]),
	[PerformanceCategoryId] Integer NOT NULL,
	[EventId] Integer NULL,
	[PerformanceId] Integer NULL,
Primary Key ([PerfCatValidityId])
)
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_PerformanceCategory] add  foreign key([ParentId]) references [CNF_PerformanceCategory] ([PerformanceCategoryId])

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>
Alter table [CNF_PerformanceCategoryValidity] add  foreign key([PerformanceId]) references [CNF_Performance] ([PerformanceId])


				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_PerformanceCategoryValidity] add  foreign key([EventId]) references [CNF_Event] ([EventId])
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_PerformanceCategoryValidity] add  foreign key([PerformanceCategoryId]) references [CNF_PerformanceCategory] ([PerformanceCategoryId])
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.590</SQLVERSION>
			<RMTRACKLINK>2928</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>CNF_PromotionProduct=PromotionProductId
CNF_PromotionItemRule=PromotionItemRuleId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>

Alter table [CNF_PromotionProduct] drop constraint fkCNF_PromotionProduct_MatrixCell;
Alter table [CNF_PromotionProduct] drop constraint fkCNF_PromotionProduct_AttributeTemplate;
Alter table [CNF_PromotionProduct] drop constraint fkCNF_PromotionProduct_MatrixSheet;


alter table  CNF_PromotionItemRule add  [ReplaceWith] Smallint NULL;
alter table  CNF_PromotionItemRule add	[MatrixCellId] Integer NULL;
alter table  CNF_PromotionItemRule add	[AttributeTemplateId] Integer NULL;
alter table  CNF_PromotionItemRule add	[AttributeId] Integer NULL;
alter table  CNF_PromotionItemRule add	[PriceFromMatrixSheet] Smallint NULL;


Alter table [CNF_PromotionItemRule] add constraint fkPromotionItemRule_AttributeTemplate foreign key([AttributeTemplateId]) references [CNF_AttributeTemplate] ([AttributeTemplateId]);
Alter table [CNF_PromotionItemRule] add constraint fkPromotionItemRule_Attribute foreign key([AttributeId]) references [CNF_Attribute] ([AttributeId]);
Alter table [CNF_PromotionItemRule] add constraint fkPromotionItemRule_MatrixCell foreign key([MatrixCellId]) references [CNF_MatrixCell] ([MatrixCellId]);

alter table CNF_PromotionProduct drop column AttributeTemplateId;
alter table CNF_PromotionProduct drop column MatrixSheetId;
alter table CNF_PromotionProduct drop column ValidAttributes;

alter table CNF_PromotionProduct add [AttributeId] Integer NULL;

alter table [CNF_PromotionProduct] add constraint fkPromotionProduct_Attribute foreign key([AttributeId]) references [CNF_Attribute] ([AttributeId]); 


				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.589</SQLVERSION>
			<RMTRACKLINK>2928</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>CNF_PromotionProduct=PromotionProductId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_PromotionProduct add MatrixcellIdtemp integer;

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>    

update  CNF_PromotionProduct  set MatrixcellIdtemp = MatrixCellId;

alter table CNF_PromotionProduct drop column MatrixcellId;

alter table CNF_PromotionProduct add MatrixcellId integer;

update  CNF_PromotionProduct  set MatrixCellId = MatrixcellIdtemp;


alter table CNF_PromotionProduct drop column MatrixcellIdtemp;


alter table CNF_PromotionProduct add AttributeTemplateId Integer NULL;
alter table CNF_PromotionProduct add MatrixSheetId Integer NULL;
alter table CNF_PromotionProduct add ValidAttributes Varchar(100) NULL;

Alter table [CNF_PromotionProduct] add constraint fkCNF_PromotionProduct_MatrixCell foreign key([MatrixCellId]) references [CNF_MatrixCell] ([MatrixCellId]);
Alter table [CNF_PromotionProduct] add constraint fkCNF_PromotionProduct_AttributeTemplate foreign key([AttributeTemplateId]) references [CNF_AttributeTemplate] ([AttributeTemplateId]);
Alter table [CNF_PromotionProduct] add constraint fkCNF_PromotionProduct_MatrixSheet foreign key([MatrixSheetId]) references [CNF_MatrixSheet] ([MatrixSheetId]);
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>francescosalvi</ADDEDBY>
			<SQLVERSION>1.588</SQLVERSION>
			<RMTRACKLINK>3169</RMTRACKLINK>
			<REASON>Ability to correct the final close declaration by ticket type</REASON>
			<TABLENAMES>DATA_Deposit=DepositId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE [DATA_Deposit]
ADD [AuditId] Integer NULL

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AndreaL</ADDEDBY>
			<SQLVERSION>1.587</SQLVERSION>
			<RMTRACKLINK>2923</RMTRACKLINK>
			<REASON>CNF_ExternalTicketRange
to correct ValidFrom, ValidTo DataType</REASON>
			<TABLENAMES>CNF_ExternalTicketRange=ExternalTicketRangeId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE [CNF_ExternalTicketRange]
ALTER COLUMN [ValidFrom] datetime
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE [CNF_ExternalTicketRange]
ALTER COLUMN [ValidTo] datetime
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AndreaL</ADDEDBY>
			<SQLVERSION>1.586</SQLVERSION>
			<RMTRACKLINK>2923</RMTRACKLINK>
			<REASON>CNF_ExternalTicketRange
[0] Add Constrains on field MatrrixCellId
[1] Add field UserId nullable
[2] Add Constraints on field UserId
[3] Add Field ExtRangeType default 1
[4] Add Field ValidFrom
[5] Add Field ValidTo</REASON>
			<TABLENAMES>CNF_ExternalTicketRange=ExternalTicketRangeId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE [CNF_ExternalTicketRange]
ADD CONSTRAINT [CNF_ExtTckRange_MatrixCellId] FOREIGN KEY ([MatrixCellId]) 
  REFERENCES [CNF_MatrixCell] ([MatrixCellId]) 
  ON UPDATE NO ACTION
  ON DELETE NO ACTION
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE [CNF_ExternalTicketRange]
ADD [UserId] int NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE [CNF_ExternalTicketRange]
ADD CONSTRAINT [CNF_ExtTckRange_UserId] FOREIGN KEY ([UserId]) 
  REFERENCES [CNF_User] ([UserId]) 
  ON UPDATE NO ACTION
  ON DELETE NO ACTION
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE [CNF_ExternalTicketRange]
ADD [ExtRangeType] smallint DEFAULT 1 NOT NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE [CNF_ExternalTicketRange]
ADD [ValidFrom] date NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE [CNF_ExternalTicketRange]
ADD [ValidTo] date NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AndreaL</ADDEDBY>
			<SQLVERSION>1.585</SQLVERSION>
			<RMTRACKLINK>2720</RMTRACKLINK>
			<REASON>Add Field PerformanceCreatio to table CNF_Calendar</REASON>
			<TABLENAMES>CNF_Calendar=CalendarId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE [CNF_Calendar]
ADD [PerformanceCreation] smallint NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>1.584</SQLVERSION>
			<RMTRACKLINK>3159</RMTRACKLINK>
			<REASON>Empty patch
DBModel realigned to real DB (foreign key DATA_Note
to DATA_Sale)</REASON>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>1.583</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>CNF_Envelope
update Code for Default envelope</REASON>
			<TABLENAMES>CNF_Envelope=EnvelopeId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT> update CNF_Envelope
 set Code = 'DEF'
 where EnvelopeType = 2
 and (Code is null or Code = '')
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.582</SQLVERSION>
			<RMTRACKLINK>3054</RMTRACKLINK>
			<REASON>DATA_AccountRelationship
[0] create table
[1] create index on Father
[2] create index on Child
[3] add FK on Father
[4] add FK on Child</REASON>
			<TABLENAMES>DATA_AccountRelationship=AccountRelationshipId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [DATA_AccountRelationship]
(
	[AccountRelationshipId] Integer Identity(1,1) NOT NULL,
	[FatherAccountId] Integer NOT NULL,
	[ChildAccountId] Integer NOT NULL,
	[RelationType] Smallint NOT NULL,
Primary Key ([AccountRelationshipId])
) 



				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create Index [IDX_DATA_AccountRelationshipFather] 
  ON [DATA_AccountRelationship] ([FatherAccountId] ) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create Index [DATA_AccountRelationshipChild] 
  ON [DATA_AccountRelationship] ([ChildAccountId] ) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>  Alter table [DATA_AccountRelationship] 
    add  foreign key([FatherAccountId]) references [DATA_Account] ([AccountId])
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_AccountRelationship] 
  add  foreign key([ChildAccountId]) references [DATA_Account] ([AccountId])
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>1.581</SQLVERSION>
			<RMTRACKLINK>2124</RMTRACKLINK>
			<REASON>DATA_Sale
[0] add field Operation Integer not null</REASON>
			<TABLENAMES>DATA_Sale=SaleId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Sale
  add Operation smallint not null default 1
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.580</SQLVERSION>
			<RMTRACKLINK>3098</RMTRACKLINK>
			<REASON>DATA_Account
[0] add field Password</REASON>
			<TABLENAMES>DATA_Account=AccountId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Account
  add Password nvarchar(100) null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>federicocaramella</ADDEDBY>
			<SQLVERSION>1.579</SQLVERSION>
			<RMTRACKLINK>3039</RMTRACKLINK>
			<REASON>DROP CONSTRAINT
[0]CNF_Language
ADD CONSTRAINT
[1]CNF_Language</REASON>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @sql NVARCHAR(255)

IF EXISTS 
( SELECT OBJECT_NAME(object_id) AS ConstraintName
  FROM sys.objects
  WHERE  OBJECT_NAME(parent_object_id)='CNF_Language' AND  
         type = 'UQ')
  BEGIN
    SELECT @sql = 'ALTER TABLE CNF_Language DROP CONSTRAINT ' + (SELECT OBJECT_NAME(object_id) AS ConstraintName
    FROM sys.objects
    WHERE  OBJECT_NAME(parent_object_id)='CNF_Language' AND  type = 'UQ')
    EXEC sp_executesql @sql    
  END
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS 
(SELECT * FROM sys.indexes 
 WHERE object_id = OBJECT_ID(N'[dbo].[CNF_Language]') AND 
 name = N'UQ_CNF_Language_LangCode_LangI18nCode') 

ALTER TABLE CNF_Language
ADD CONSTRAINT UQ_CNF_Language_LangCode_LangI18nCode UNIQUE NONCLUSTERED (LangCode ASC ,LangI18nCode ASC )
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.578</SQLVERSION>
			<RMTRACKLINK>3127</RMTRACKLINK>
			<REASON>DATA_TicketUsageOption

add index on UsageId
add index on UsageId and UsageType</REASON>
			<TABLENAMES>DATA_TicketUsageOption=ticketUsageOptionId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[DATA_ticketUsageOption]') AND name = N'IDX_DATA_TicketUsageOption_UsageId')
CREATE NONCLUSTERED INDEX [IDX_DATA_TicketUsageOption_UsageId] ON [dbo].[DATA_TicketUsageOption]
(
	[UsageId] ASC
)
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[DATA_ticketUsageOption]') AND name = N'IDX_DATA_TicketUsageOption_OptionType')
CREATE NONCLUSTERED INDEX [IDX_DATA_TicketUsageOption_OptionType] ON [dbo].[DATA_TicketUsageOption]
(
	[UsageId] ASC,
	[OptionType] ASC
)
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.577</SQLVERSION>
			<RMTRACKLINK>3043</RMTRACKLINK>
			<REASON/>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>drop table SYNC_ExtTicket


Create table [SYNC_NEWENTRY]
(
	[Id] Integer Identity(1,1) NOT NULL,
	[Context] Nvarchar(10) NOT NULL,
	[Content] Varchar(1000) NULL,
Primary Key ([Id])
) 


Create table [SYNC_TOUPLOAD]
(
	[ClientId] Smallint NOT NULL,
	[Id] Integer NOT NULL,
	[Context] Nvarchar(10) NOT NULL,
	[Content] Varchar(1000) NULL,
Primary Key ([ClientId],[Id])
) 

Create table [SYNC_DOWNLOADED]
(
	[ClientId] Smallint NOT NULL,
	[Id] Integer NOT NULL,
	[Context] Nvarchar(10) NOT NULL,
	[Content] Varchar(1000) NULL,
Primary Key ([ClientId],[Id])
) 


Create table [SYNC_DOWNLOADED_ERRORS]
(
	[ClientId] Smallint NOT NULL,
	[Id] Integer NOT NULL,
	[Context] Nvarchar(10) NOT NULL,
	[Content] Varchar(1000) NULL,
	[Error] Varchar(200) NULL,
Primary Key ([ClientId],[Id])
) 


Create table [SYNC_DOWNLOADED_LOGS]
(
	[ClientId] Smallint NOT NULL,
	[Id] Integer NOT NULL,
	[Context] Nvarchar(10) NOT NULL,
	[Content] Varchar(1000) NULL,
	[SyncDateTime] Datetime NULL,
Primary Key ([ClientId],[Id])
) 
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.576</SQLVERSION>
			<RMTRACKLINK>3043</RMTRACKLINK>
			<REASON/>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>
Create table [SYNC_ExtTicket]
(
	[Identifier] Varchar(100) NULL,
	[Activate] Smallint NULL,
	[WorkstationAK] Varchar(30) NULL,
	[MatrixCellCode] Varchar(30) NULL,
	[ActiveFrom] Datetime NULL,
	[ActiveTo] Datetime NULL,
	[Serial] Integer NULL,
	[EncodeDate] Smalldatetime NULL
) 
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.575</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>CNF_MatrixCell

[0] add field Code null
[1] add filed Name null
[2] add field Description null
[3] add field Description2 null
[4] add field PrintedPrice null
[5] add field DownPayment null 
[6] add field DocTemplateId null



[7] move Matrix Cell Code from CNF_MatrixCellOption
[8] move Matrix Cell Name from CNF_MatrixCellOption
[9] move MatrixCel Description from CNF_MatrixCellOption
[10] move Matrix Cell Description2 from CNF_MatrixCellOption
[11] move Matrix Cell PrintedPrice from CNF_MatrixCellOption
[12] move Matrix Cell DownPayment from CNF_MatrixCellOption
[13] move Matrix Cell DocTemplateId from CNF_MatrixCellOption

[14] alter field Code not null
[15] alter field Name not null

CNF_MatrixCellInfo
[16] add field AccountMandatory null
[17] add field AccountDmgCatId null
[18] add field ExtendedInfoMandatory null
[19] add field ExtInfoDmgCatId null
[20] add field NotRefundable null
[21] add field SurveyId null

[22] move Matrix Cell AccountMandatory from CNF_MatrixCellOption
[23] move Matrix Cell AccountDmgCatIdf rom CNF_MatrixCellOption
[24] move Matrix Cell ExtendedInfoMandatory from CNF_MatrixCellOption
[25] move Matrix Cell ExtInfoDmgCatId from CNF_MatrixCellOption
[26] move Matrix Cell NotRefundable from CNF_MatrixCellOption
[27] move Matrix Cell Code SurveyId CNF_MatrixCellOption

[28]  alter field AccountMandatory not null
[29] alter field ExtendedInfoMandatory not null
[30] alter field NotRefundable not null

[31] drop table CNF_MatrixCellOption

[32] create view to back compatibily

[33] add FK CNF_MatrixCell.DocTemplateId
[34] add FK CNF_MatrixCellInfo.AccountDmgCatId
[35] add FK CNF_MatrixCellInfo.ExtInfoDmgCatId
[36] add FK CNF_MatrixCellInfo.SurveyId
			</REASON>
			<TABLENAMES>CNF_MatrixCell=MatrixCellId
CNF_MatrixCellInfo=MatrixCellInfoId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT> alter table CNF_MatrixCell    
   add Code nVarChar(32) Default 'None' null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> alter table CNF_MatrixCell    
   add Name nVarChar(60) Default 'None' null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>  alter table CNF_MatrixCell    
   add Description nVarChar(100) null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>  alter table CNF_MatrixCell    
   add Description2 nVarChar(100) null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_MatrixCell    
   add PrintedPrice float null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_MatrixCell    
  add DownPayment float null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_MatrixCell    
  add DocTemplateId integer null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_MatrixCell 
set Code = 
(
  select case when MCO.OptionValue = '' then 'NONE' else substring(MCO.OptionValue, 1, 32) end					
  from CNF_MatrixCellOption as MCO 
  where MCO.OptionType=5 and MCO.MatrixCellId=CNF_MatrixCell.MatrixCellId
)
where Exists
( select CNF_MatrixCellOption.OptionValue  
  from CNF_MatrixCellOption 
  where CNF_MatrixCellOption.OptionType=5 and CNF_MatrixCellOption.MatrixCellId=CNF_MatrixCell.MatrixCellId
)

update CNF_MatrixCell 
set Code = 'None' where Code is null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> update CNF_MatrixCell 
set Name = 
(
 select case when MCO.OptionValue = '' then 'NONE' else substring(MCO.OptionValue, 1, 60) end					
  from CNF_MatrixCellOption as MCO 
  where MCO.OptionType=6 and MCO.MatrixCellId=CNF_MatrixCell.MatrixCellId
)
where Exists
( select CNF_MatrixCellOption.OptionValue  
  from CNF_MatrixCellOption 
  where CNF_MatrixCellOption.OptionType=6 and CNF_MatrixCellOption.MatrixCellId=CNF_MatrixCell.MatrixCellId
)


update CNF_MatrixCell 
set Name = 'None' where Name is null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_MatrixCell 
set Description = 
(
  select case when MCO.OptionValue = '' then '' else  substring(MCO.OptionValue, 1, 100)  end					
  from CNF_MatrixCellOption as MCO 
  where MCO.OptionType=7 and MCO.MatrixCellId=CNF_MatrixCell.MatrixCellId
)
where Exists
( select CNF_MatrixCellOption.OptionValue  
  from CNF_MatrixCellOption 
  where CNF_MatrixCellOption.OptionType=7 and CNF_MatrixCellOption.MatrixCellId=CNF_MatrixCell.MatrixCellId
)
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_MatrixCell 
set Description2 = 
(
  select case when MCO.OptionValue = '' then '' else   substring(MCO.OptionValue, 1, 100) end					
  from CNF_MatrixCellOption as MCO 
  where MCO.OptionType=22 and MCO.MatrixCellId=CNF_MatrixCell.MatrixCellId
)
where Exists
( select CNF_MatrixCellOption.OptionValue  
  from CNF_MatrixCellOption 
  where CNF_MatrixCellOption.OptionType=22 and CNF_MatrixCellOption.MatrixCellId=CNF_MatrixCell.MatrixCellId
)
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_MatrixCell 
set PrintedPrice = 
(
  select case when MCO.OptionValue = '' then 0 else  convert(Float, replace(MCO.OptionValue, ',', '.') ) end					
  from CNF_MatrixCellOption as MCO 
  where MCO.OptionType=3 and MCO.MatrixCellId=CNF_MatrixCell.MatrixCellId
)
where Exists
( select CNF_MatrixCellOption.OptionValue  
  from CNF_MatrixCellOption 
  where CNF_MatrixCellOption.OptionType=3 and CNF_MatrixCellOption.MatrixCellId=CNF_MatrixCell.MatrixCellId
)
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_MatrixCell 
set DownPayment = 
(
  select case when MCO.OptionValue = '' then 0 else  MCO.OptionValue end					
  from CNF_MatrixCellOption as MCO 
  where MCO.OptionType=4 and MCO.MatrixCellId=CNF_MatrixCell.MatrixCellId
)
where Exists
( select CNF_MatrixCellOption.OptionValue  
  from CNF_MatrixCellOption 
  where CNF_MatrixCellOption.OptionType=4 and CNF_MatrixCellOption.MatrixCellId=CNF_MatrixCell.MatrixCellId
)
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_MatrixCell 
set DocTemplateId = 
(
  select case when MCO.OptionValue = '' then Null else  MCO.OptionValue end					
  from CNF_MatrixCellOption as MCO 
  where MCO.OptionType=2 and MCO.MatrixCellId=CNF_MatrixCell.MatrixCellId
)
where Exists
( select CNF_MatrixCellOption.OptionValue  
  from CNF_MatrixCellOption 
  where CNF_MatrixCellOption.OptionType=2 and CNF_MatrixCellOption.MatrixCellId=CNF_MatrixCell.MatrixCellId
)
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_MatrixCell
  alter column Code nVarChar(32) not null 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_MatrixCell
  alter column Name nVarChar(60) not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> alter table CNF_MatrixCellInfo    
   add AccountMandatory smallInt null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> alter table CNF_MatrixCellInfo    
   add AccountDmgCatId Int null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>  alter table CNF_MatrixCellInfo    
   add ExtendedInfoMandatory smallInt null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>  alter table CNF_MatrixCellInfo    
   add ExtInfoDmgCatId Integer null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>   alter table CNF_MatrixCellInfo    
   add NotRefundable smallInt null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_MatrixCellInfo    
   add SurveyId Int null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_MatrixCellInfo 
set AccountMandatory = 
(
  select case when MCO.OptionValue = 'True' then 1 else  0 end					
  from CNF_MatrixCellOption as MCO 
  where MCO.OptionType=17 and MCO.MatrixCellId=CNF_MatrixCellInfo.MatrixCellId
)
where Exists
( select CNF_MatrixCellOption.OptionValue  
  from CNF_MatrixCellOption 
  where CNF_MatrixCellOption.OptionType=17 and CNF_MatrixCellOption.MatrixCellId=CNF_MatrixCellInfo.MatrixCellId
);


update CNF_MatrixCellInfo 
set AccountMandatory = 0
where AccountMandatory is null 



				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_MatrixCellInfo 
set AccountDmgCatId = 
(
  select DC.DmgCategoryId					
  from CNF_MatrixCellOption as MCO   
  left join CNF_DmgCategory DC ON MCO.OptionValue = DC.DmgCategoryId and DC.DmgType =1
  where MCO.OptionType=16 and MCO.MatrixCellId=CNF_MatrixCellInfo.MatrixCellId
)
where Exists
( select CNF_MatrixCellOption.OptionValue  
  from CNF_MatrixCellOption 
  where CNF_MatrixCellOption.OptionType=16 and CNF_MatrixCellOption.MatrixCellId=CNF_MatrixCellInfo.MatrixCellId
)



				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_MatrixCellInfo 
set ExtendedInfoMandatory = 
(
  select case when MCO.OptionValue = 'True' then 1 else  0 end						
  from CNF_MatrixCellOption as MCO 
  where MCO.OptionType=15 and MCO.MatrixCellId=CNF_MatrixCellInfo.MatrixCellId
)
where Exists
( select CNF_MatrixCellOption.OptionValue  
  from CNF_MatrixCellOption 
  where CNF_MatrixCellOption.OptionType=15 and CNF_MatrixCellOption.MatrixCellId=CNF_MatrixCellInfo.MatrixCellId
)

update CNF_MatrixCellInfo 
set ExtendedInfoMandatory = 0
where ExtendedInfoMandatory is null  
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_MatrixCellInfo 
set ExtInfoDmgCatId = 
(
  select case when MCO.OptionValue = '' then Null else  MCO.OptionValue end					
  from CNF_MatrixCellOption as MCO 
  where MCO.OptionType=14 and MCO.MatrixCellId=CNF_MatrixCellInfo.MatrixCellId
)
where Exists
( select CNF_MatrixCellOption.OptionValue  
  from CNF_MatrixCellOption 
  where CNF_MatrixCellOption.OptionType=14 and CNF_MatrixCellOption.MatrixCellId=CNF_MatrixCellInfo.MatrixCellId
)
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_MatrixCellInfo 
set NotRefundable = 
(
  select case when MCO.OptionValue = 'True' then 1 else  0 end						
  from CNF_MatrixCellOption as MCO 
  where MCO.OptionType=23 and MCO.MatrixCellId=CNF_MatrixCellInfo.MatrixCellId
)
where Exists
( select CNF_MatrixCellOption.OptionValue  
  from CNF_MatrixCellOption 
  where CNF_MatrixCellOption.OptionType=23 and CNF_MatrixCellOption.MatrixCellId=CNF_MatrixCellInfo.MatrixCellId
)

update CNF_MatrixCellInfo 
set NotRefundable = 0 where NotRefundable is null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_MatrixCellInfo 
set SurveyId = 
(
  select case when MCO.OptionValue = '' then Null else  MCO.OptionValue end					
  from CNF_MatrixCellOption as MCO 
  where MCO.OptionType=21 and MCO.MatrixCellId=CNF_MatrixCellInfo.MatrixCellId
)
where Exists
( select CNF_MatrixCellOption.OptionValue  
  from CNF_MatrixCellOption 
  where CNF_MatrixCellOption.OptionType=21 and CNF_MatrixCellOption.MatrixCellId=CNF_MatrixCellInfo.MatrixCellId
) AND
 Exists
( select SurveyId 
  from CNF_Survey
  inner join CNF_MatrixCellOption as MCO on  
  MCO.OptionType=21 and
  MCO.OptionValue = CNF_Survey.SurveyId
)
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_MatrixCellInfo
  alter column AccountMandatory smallint not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_MatrixCellInfo
  alter column ExtendedInfoMandatory smallint not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_MatrixCellInfo
  alter column NotRefundable smallint  not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> drop table  CNF_MatrixCellOption
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>create view CNF_MatrixCellOption
as(
select 
  MC.MatrixCellId, 
  5 as OptionType,
  MC.Code as OptionValue
from CNF_MatrixCell as MC

union

select 
  MC.MatrixCellId, 
  6 as OptionType,
  MC.Name as OptionValue
from CNF_MatrixCell as MC
union
select 
  MC.MatrixCellId, 
  7 as OptionType,
  MC.Description as OptionValue
from CNF_MatrixCell as MC
)
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_MatrixCell] 
  add  foreign key([DocTemplateId]) references [CNF_DocTemplate] ([DocTemplateId])  
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_MatrixCellInfo] 
  add  foreign key([AccountDmgCatId]) references [CNF_DmgCategory] ([DmgCategoryId])
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_MatrixCellInfo] 
  add  foreign key([ExtInfoDmgCatId]) references [CNF_DmgCategory] ([DmgCategoryId])
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_MatrixCellInfo] 
  add  foreign key([SurveyId]) references [CNF_Survey] ([SurveyId])
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.574</SQLVERSION>
			<RMTRACKLINK>2928</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>CNF_PromotionItemRule=PromotionItemRuleId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_PromotionItemRule add MinDaysRenew integer;
alter table CNF_PromotionItemRule add MaxDaysRenew integer;
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>federicocaramella</ADDEDBY>
			<SQLVERSION>1.573</SQLVERSION>
			<RMTRACKLINK>3039</RMTRACKLINK>
			<REASON>CNF_Language
[0] Add Field LangI18nCode</REASON>
			<TABLENAMES>CNF_Language=LanguageId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE [CNF_Language]
ADD [LangI18nCode] nvarchar(10) NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.572</SQLVERSION>
			<RMTRACKLINK>2320</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>cnf_attribute=attributeid</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table cnf_attribute add PerfNumDays int
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.571</SQLVERSION>
			<RMTRACKLINK>1948</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>CNF_PromotionItemRule=PromotionItemRuleId
CNF_PromotionEvent=PromotionEventId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_PromotionEvent]
(
	[PromotionEventId] Integer Identity(1,1) NOT NULL,
	[PromotionItemRuleId] Integer NOT NULL,
	[EventId] Integer NOT NULL,
Primary Key ([PromotionEventId])
) 


Alter Table CNF_PromotionItemRule add ChangePerformance smallint;


Alter table [CNF_PromotionEvent] add constraint FK_PromotionEvent_PromotionItemRule foreign key([PromotionItemRuleId]) references [CNF_PromotionItemRule] ([PromotionItemRuleId])

Alter table [CNF_PromotionEvent] add constraint FK_PromotionEvent_Event foreign key([EventId]) references [CNF_Event] ([EventId])   





				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>OTNALO</ADDEDBY>
			<SQLVERSION>1.570</SQLVERSION>
			<RMTRACKLINK>2682</RMTRACKLINK>
			<REASON>CNF_MaskTableItem
[0] Add Field ItemCodeAdditional </REASON>
			<TABLENAMES>CNF_MaskTableItem=MaskTableItemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE [CNF_MaskTableItem]
ADD [ItemCodeAdditional] nvarchar(30) NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>federicocaramella</ADDEDBY>
			<SQLVERSION>1.569</SQLVERSION>
			<RMTRACKLINK>2832</RMTRACKLINK>
			<REASON>CNF_User
[0] add field ExtAuthCode</REASON>
			<TABLENAMES>CNF_User=UserId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_User
  add [ExtAuthCode] Nvarchar(50) NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.568</SQLVERSION>
			<RMTRACKLINK>Stock</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>STOCK_CNF_Product=MatrixCellId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table STOCK_CNF_Product add MoveQty smallint not null default 1;
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.567</SQLVERSION>
			<RMTRACKLINK>2108</RMTRACKLINK>
			<REASON>DATA_Account</REASON>
			<TABLENAMES>DATA_Account=AccountId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Account
  add [DisplayField2] Nvarchar(200) NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Account
  add [DisplayField1] Nvarchar(200) NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AlessandroBadii</ADDEDBY>
			<SQLVERSION>1.566</SQLVERSION>
			<RMTRACKLINK>2948</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>CNF_Promotion=PromotionId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Promotion
  add SupervisorOverride smallint not null default 0
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.565</SQLVERSION>
			<RMTRACKLINK>2738</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>DATA_SaleItem=SaleItemId
DATA_TransactionItem=ItemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>

alter table [DATA_SaleItem] add [ComboRef] Nvarchar(10) NULL;
alter table [DATA_TransactionItem] add [ComboRef] Nvarchar(10) NULL;


Create Index [idxDATA_TransactionItem_ComboRef] ON [DATA_TransactionItem] ([ComboRef] );
Create Index [idxDATA_SaleItem_ComboRef] ON [DATA_SaleItem] ([ComboRef] )  
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AlessandroBadii</ADDEDBY>
			<SQLVERSION>1.564</SQLVERSION>
			<RMTRACKLINK>2813</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>CNF_PaymentMethod=PaymentMethodId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_PaymentMethod
  add SupervisorOverride smallint not null default 0
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.563</SQLVERSION>
			<RMTRACKLINK>2738</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>STOCK_CNF_ProductComboChoice=ComboChoiceId
STOCK_CNF_ProductCombo=ComboId
			</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table STOCK_CNF_ProductComboChoice add quantity Float;
alter table STOCK_CNF_ProductCombo add quantity Float;

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.562</SQLVERSION>
			<RMTRACKLINK>2738</RMTRACKLINK>
			<REASON/>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_SaleItem_Combo alter column  ComboChoiceId integer null;
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.561</SQLVERSION>
			<RMTRACKLINK>2738</RMTRACKLINK>
			<REASON/>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_TransactionItem_Combo alter column  ComboChoiceId integer null;
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>1.560</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add new indexes for tables:

[0] CNF_MaskTableItem
[1] CNF_MatrixCell
[2] CNF_MatrixCellOption
[3] CNF_MatrixSheet
[4] DATA_Account
[5] DATA_Ticket
[6] DATA_TicketUsage
[7] DATA_Ledger


			</REASON>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>
-- [0] CNF_MaskTableItem

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CNF_MaskTableItem]') AND name = N'IDX_CNF_MaskTableItem_ItemDescription')
CREATE NONCLUSTERED INDEX [IDX_CNF_MaskTableItem_ItemDescription] ON [dbo].[CNF_MaskTableItem]
(
	[ItemDescription] ASC
)




				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>
-- [1] CNF_MatrixCell

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CNF_MatrixCell]') AND name = N'IDX_CNF_MatrixCell_MatrixSheetId')
CREATE NONCLUSTERED INDEX [IDX_CNF_MatrixCell_MatrixSheetId] ON [dbo].[CNF_MatrixCell]
(
	[MatrixSheetId] ASC
)

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CNF_MatrixCell]') AND name = N'IDX_CNF_MatrixCell_AttributeSetId')
CREATE NONCLUSTERED INDEX [IDX_CNF_MatrixCell_AttributeSetId] ON [dbo].[CNF_MatrixCell]
(
	[AttributeSetId] ASC
)



				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>
-- [2] CNF_MatrixCellOption

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CNF_MatrixCellOption]') AND name = N'IDX_CNF_MatrixCellOption_OptionType')
CREATE NONCLUSTERED INDEX [IDX_CNF_MatrixCellOption_OptionType] ON [dbo].[CNF_MatrixCellOption]
(
	[OptionType] ASC
)

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CNF_MatrixCellOption]') AND name = N'IDX_CNF_MatrixCellOption_MatrixCellId')
CREATE NONCLUSTERED INDEX [IDX_CNF_MatrixCellOption_MatrixCellId] ON [dbo].[CNF_MatrixCellOption]
(
	[MatrixCellId] ASC
)

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>
-- [3] CNF_MatrixSheet


IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CNF_MatrixSheet]') AND name = N'IDX_CNF_MatrixSheet_EventId')
CREATE NONCLUSTERED INDEX [IDX_CNF_MatrixSheet_EventId] ON [dbo].[CNF_MatrixSheet]
(
	[EventId] ASC
)

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>
-- [4] DATA_Account


IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[DATA_Account]') AND name = N'IDX_DATA_Account_DmgCategoryId')
CREATE NONCLUSTERED INDEX [IDX_DATA_Account_DmgCategoryId] ON [dbo].[DATA_Account]
(
	[DmgCategoryId] ASC
)

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[DATA_Account]') AND name = N'IDX_DATA_Account_AccountType')
CREATE NONCLUSTERED INDEX [IDX_DATA_Account_AccountType] ON [dbo].[DATA_Account]
(
	[AccountType] ASC
)

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[DATA_Account]') AND name = N'IDX_DATA_Account_Enabled')
CREATE NONCLUSTERED INDEX [IDX_DATA_Account_Enabled] ON [dbo].[DATA_Account]
(
	[Enabled] ASC
)

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>
-- [5] DATA_Ticket


IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[DATA_Ticket]') AND name = N'IDX_DATA_Ticket_WorkstationId')
CREATE NONCLUSTERED INDEX [IDX_DATA_Ticket_WorkstationId] ON [dbo].[DATA_Ticket]
(
	[WorkstationId] ASC
)

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[DATA_Ticket]') AND name = N'IDX_DATA_Ticket_MatrixCellId')
CREATE NONCLUSTERED INDEX [IDX_DATA_Ticket_MatrixCellId] ON [dbo].[DATA_Ticket]
(
	[MatrixCellId] ASC
)

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[DATA_Ticket]') AND name = N'IDX_DATA_Ticket_CreationType')
CREATE NONCLUSTERED INDEX [IDX_DATA_Ticket_CreationType] ON [dbo].[DATA_Ticket]
(
	[CreationType] ASC
)

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[DATA_Ticket]') AND name = N'IDX_DATA_Ticket_AccountId')
CREATE NONCLUSTERED INDEX [IDX_DATA_Ticket_AccountId] ON [dbo].[DATA_Ticket]
(
	[AccountId] ASC
)

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[DATA_Ticket]') AND name = N'IDX_DATA_Ticket_VoidType')
CREATE NONCLUSTERED INDEX [IDX_DATA_Ticket_VoidType] ON [dbo].[DATA_Ticket]
(
	[VoidType] ASC
)

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>
-- [6] DATA_TicketUsage


IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[DATA_TicketUsage]') AND name = N'IDX_DATA_TicketUsage_FUsageDate')
CREATE NONCLUSTERED INDEX [IDX_DATA_TicketUsage_FUsageDate] ON [dbo].[DATA_TicketUsage]
(
	[FUsageDate] ASC
)

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[DATA_TicketUsage]') AND name = N'IDX_DATA_TicketUsage_UsageType')
CREATE NONCLUSTERED INDEX [IDX_DATA_TicketUsage_UsageType] ON [dbo].[DATA_TicketUsage]
(
	[UsageType] ASC
)

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[DATA_TicketUsage]') AND name = N'IDX_DATA_TicketUsage_ValidateResult')
CREATE NONCLUSTERED INDEX [IDX_DATA_TicketUsage_ValidateResult] ON [dbo].[DATA_TicketUsage]
(
	[ValidateResult] ASC
)



				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>
-- [7] DATA_Ledger

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[DATA_Ledger]') AND name = N'IDX_DATA_Ledger_Transaction_AccountId')
CREATE NONCLUSTERED INDEX [IDX_DATA_Ledger_Transaction_AccountId] ON [dbo].[DATA_Ledger]
(
	[TransactionId] ASC,
	[LedgerAccountId] ASC,
	[DueDate] ASC,
	[ReferenceTable] ASC,
	[ReferenceId] ASC
)



				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.559</SQLVERSION>
			<RMTRACKLINK>2738</RMTRACKLINK>
			<REASON/>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [STOCK_CNF_ProductCombo] drop constraint  FK_StockProductCombo_ProductChild;

Alter table [STOCK_CNF_ProductCombo] add constraint FK_StockProductCombo_Child foreign key([ChildMatrixCellId]) references [CNF_MatrixCell] ([MatrixCellId]) ; 







				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.558</SQLVERSION>
			<RMTRACKLINK>2738</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>STOCK_CNF_ProductCombo=ComboId
STOCK_CNF_Product=MatrixCellId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT> alter table STOCK_CNF_ProductCombo add Description Varchar(20);
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.557</SQLVERSION>
			<RMTRACKLINK>2738</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>DATA_SaleItem_Combo=SaleItemComboId
DATA_TransactionItem_Combo=TransactionItemComboId
STOCK_CNF_ProductComboChoice=ComboChoiceId
STOCK_CNF_ProductCombo=ComboId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter Table STOCK_CNF_Product Add IsCombo smallint not null default (0)



Create table [STOCK_CNF_ProductCombo]
(
	[ComboId] Integer Identity(1,1) NOT NULL,
	[ComboMatrixCellId] Integer NOT NULL,
	[ParentComboId] Integer NULL,
	[Level] Integer NULL,
	[Position] Integer NULL,
	[Optional] Smallint Default 0 NOT NULL,
	[ChildMatrixCellId] Integer NULL,
	[Choice] Smallint Default 0 NOT NULL,
	[ChildProductCategoryId] Integer NULL,
	[DeltaPrice] Money NULL,
	[Enabled] Smallint Default 1 NOT NULL,
Primary Key ([ComboId])
)  

Alter table [STOCK_CNF_ProductCombo] add constraint FK_StockProductCombo_ProductCategory foreign key([ChildProductCategoryId]) references [STOCK_CNF_ProductCategory] ([CategoryId]) 
Alter table [STOCK_CNF_ProductCombo] add constraint FK_StockProductCombo_Parent foreign key([ParentComboId]) references [STOCK_CNF_ProductCombo] ([ComboId]) 
Alter table [STOCK_CNF_ProductCombo] add constraint FK_StockProductCombo_Product foreign key([ComboMatrixCellId]) references [STOCK_CNF_Product] ([MatrixCellId]) 
Alter table [STOCK_CNF_ProductCombo] add constraint FK_StockProductCombo_ProductChild foreign key([ChildProductCategoryId]) references [STOCK_CNF_Product] ([MatrixCellId]) 




Create table [STOCK_CNF_ProductComboChoice]
(
	[ComboChoiceId] Integer Identity(1,1) NOT NULL,
	[ComboId] Integer NOT NULL,
	[MatrixCellId] Integer NOT NULL,
	[DeltaPrice] Money NULL,
	[Enabled] Smallint Default 1 NOT NULL,
Primary Key ([ComboChoiceId])
) 


Alter table [STOCK_CNF_ProductComboChoice] add constraint FK_StockProductComboChoice_ProductCombo foreign key([ComboId]) references [STOCK_CNF_ProductCombo] ([ComboId])  
Alter table [STOCK_CNF_ProductComboChoice] add constraint FK_StockProductComboChoice_MatrixCell foreign key([MatrixCellId]) references [CNF_MatrixCell] ([MatrixCellId])  


Create table [DATA_TransactionItem_Combo]
(
	[TransactionItemComboId] Integer Identity(1,1) NOT NULL,
	[ComboId] Integer NOT NULL,
	[ComboChoiceId] Integer NOT NULL,
	[MatrixCellId] Integer NOT NULL,
	[ItemId] Integer NOT NULL,
	[Price] Money NULL,
Primary Key ([TransactionItemComboId])
) 

Alter table [DATA_TransactionItem_Combo] add constraint DATA_TransactionItemCombo_ProductCombo foreign key([ComboId]) references [STOCK_CNF_ProductCombo] ([ComboId]) 
Alter table [DATA_TransactionItem_Combo] add constraint DATA_TransactionItemCombo_ProductComboChoice foreign key([ComboChoiceId]) references [STOCK_CNF_ProductComboChoice] ([ComboChoiceId]) 
Alter table [DATA_TransactionItem_Combo] add constraint DATA_TransactionItemCombo_MatrixCell foreign key([MatrixCellId]) references [CNF_MatrixCell] ([MatrixCellId])  
Alter table [DATA_TransactionItem_Combo] add constraint DATA_TransactionItemCombo_TransactionItem foreign key([ItemId]) references [DATA_TransactionItem] ([ItemId]) 


Create table [DATA_SaleItem_Combo]
(
	[SaleItemComboId] Integer Identity(1,1) NOT NULL,
	[ComboId] Integer NOT NULL,
	[ComboChoiceId] Integer NOT NULL,
	[SaleItemId] Integer NOT NULL,
	[MatrixCellId] Integer NOT NULL,
	[Price] Money NULL,
Primary Key ([SaleItemComboId])
) 


Alter table [DATA_SaleItem_Combo] add constraint DATA_SaleItemCombo_ProductCombo foreign key([ComboId]) references [STOCK_CNF_ProductCombo] ([ComboId]) 
Alter table [DATA_SaleItem_Combo] add constraint DATA_SaleItemCombo_ProductComboChoice foreign key([ComboChoiceId]) references [STOCK_CNF_ProductComboChoice] ([ComboChoiceId]) 
Alter table [DATA_SaleItem_Combo] add constraint DATA_SaleItemCombo_MatrixCell foreign key([MatrixCellId]) references [CNF_MatrixCell] ([MatrixCellId])  
Alter table [DATA_SaleItem_Combo] add constraint DATA_SaleItemCombo_SaleItem foreign key([SaleItemId]) references [DATA_SaleItem] ([SaleItemId])

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.556</SQLVERSION>
			<RMTRACKLINK>2834</RMTRACKLINK>
			<REASON>CNF_MatrixCell
[0] add field ReceiptTemplateId
[1] update the field
[2] drop EnvelopeTemplateId
			</REASON>
			<TABLENAMES>CNF_MatrixCell=MatrixCellId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>  alter table CNF_MatrixCell  
    add ReceiptTemplateId int null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_MatrixCell
  set ReceiptTemplateId = EnvelopeTemplateId
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>  Alter Table CNF_MAtrixCell  
    drop column  EnvelopeTemplateId
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.555</SQLVERSION>
			<RMTRACKLINK>2090</RMTRACKLINK>
			<REASON/>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table FM_RepositoryFiles drop column Content;  

alter table FM_RepositoryFiles add Content varbinary(MAX);

ALTER TABLE [dbo].[FM_RepositoryItems] DROP CONSTRAINT [FK_RespositoryItem_Files_Guid];
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.554</SQLVERSION>
			<RMTRACKLINK>2834</RMTRACKLINK>
			<REASON>CNF_MatrixCell
[0] add field EnvelopeTemplateId int</REASON>
			<TABLENAMES>CNF_matrixCell=MatrixCellId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_MatrixCell
  add EnvelopeTemplateId Integer NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.553</SQLVERSION>
			<RMTRACKLINK>2090</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>FM_RepositoryItems=ItemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>   alter table FM_RepositoryItems drop column Repository;
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.552</SQLVERSION>
			<RMTRACKLINK>2090</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>FM_RepositoryItems=ItemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table FM_RepositoryItems add ParentItemId Integer;

Alter table [FM_RepositoryItems] add constraint FK_RepositoryItem_Parent foreign key([ParentItemId]) references [FM_RepositoryItems] ([ItemId]) ;




				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.551</SQLVERSION>
			<RMTRACKLINK>2090</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>FM_RepositoryItems=ItemId
FM_RepositoryFiles=Guid</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>        
Create table [FM_RepositoryItems]
(
	[ItemId] Integer Identity(1,1) NOT NULL,
	[Guid] Nvarchar(38) NULL,
	[Repository] Nvarchar(10) NOT NULL,
	[Ext] Nvarchar(6) NULL,
	[Description] Varchar(50) NULL,
	[Name] Varchar(25) NULL,
Primary Key ([ItemId])
) 

Create table [FM_RepositoryFiles]
(
	[Guid] Nvarchar(38) NOT NULL,
	[Content] Text NULL,
Primary Key ([Guid])
) 

Alter table [FM_RepositoryItems] add constraint [FK_RespositoryItem_Files_Guid] foreign key([Guid]) references [FM_RepositoryFiles] ([Guid])  




				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.550</SQLVERSION>
			<RMTRACKLINK>905</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>CNF_Envelope_Permission=EnvelopePermissionId
CNF_Envelope=EnvelopeId</TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.549</SQLVERSION>
			<RMTRACKLINK>905</RMTRACKLINK>
			<REASON>CNF_Envelope_Permission
[0] create table
[1] add FK on UserId
[2] add FK on WorkstationId
[3] Add FK on OperatingAreaId
[4] Add FK on AccountId
[5] Add FK on DmgCategoryId
[6] Add FK on SiteId
[7] Add FK on UserGroupId
CNF_Envelope
[8] add field DMGCategoryId
[9] Add FP on DmgCategoryId
[10] add FP on EnvelopeId
[11] drop FK parentId
[12]Remove Field ParentId </REASON>
			<TABLENAMES>CNF_Envelope_Permission=EnvelopePermissionId
CNF_Envelope=EnvelopeId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_Envelope_Permission]
(
	[EnvelopePermissionId] Integer Identity(1,1) NOT NULL, UNIQUE ([EnvelopePermissionId]),
	[EnvelopeId] Integer NOT NULL,
	[SiteId] Integer NULL,
	[WorkstationId] Integer NULL,
	[DmgCategoryId] Integer NULL,
	[UserId] Integer NULL,
	[UserGroupId] Integer NULL,
	[AccountId] Integer NULL,
	[OperatingAreaId] Integer NULL,
	[Allow] Smallint NULL,
Primary Key ([EnvelopePermissionId])
)
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Envelope_Permission] 
  add  foreign key([UserId]) references [CNF_User] ([UserId])  

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Envelope_Permission] 
  add  foreign key([WorkstationId]) references [CNF_Workstation] ([WorkstationId])  


				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Envelope_Permission] 
  add  foreign key([OperatingAreaId]) references [CNF_OperatingArea] ([OperatingAreaId])  

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Envelope_Permission] 
  add  foreign key([AccountId]) references [DATA_Account] ([AccountId])   
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Envelope_Permission] 
add  foreign key([DmgCategoryId]) references [CNF_DmgCategory] ([DmgCategoryId])  
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> Alter table [CNF_Envelope_Permission] 
   add  foreign key([SiteId]) references [CNF_Site] ([SiteId])
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Envelope_Permission] 
  add  foreign key([UserGroupId]) references [CNF_UserGroup] ([UserGroupId])
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Envelope
  add DmgCategoryId integer null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Envelope] add  foreign key([DmgCategoryId]) references [CNF_DmgCategory] ([DmgCategoryId])
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> Alter table [CNF_Envelope_Permission] 
   add  foreign key([EnvelopeId]) references [CNF_Envelope] ([EnvelopeId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>declare @foreign_key_name nvarchar(max),
@dropstmt nvarchar(max);

select @foreign_key_name = f.name
from sys.foreign_keys AS f
inner join sys.foreign_key_columns AS fc 
on  f.object_id = fc.constraint_object_id 
where  f.parent_object_id = object_id(N'dbo.CNF_Envelope')
and  f.referenced_object_id = object_id(N'dbo.CNF_Envelope')
and COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'EnvelopeId';

--Se lo Trovo lo cancello
if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE dbo.CNF_Envelope DROP CONSTRAINT [' + @foreign_key_name + ']';
  execute sp_executesql @dropstmt
end;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Envelope
  drop column ParentId
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Envelope
  add Code nvarchar(12) not null default ' '
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.548</SQLVERSION>
			<RMTRACKLINK>2831</RMTRACKLINK>
			<REASON>CNF_MatrixCell
[0] add field PriorityOrder int</REASON>
			<TABLENAMES>CNF_MatrixCell=MatrixCellId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_MatrixCell
  add PriorityOrder int null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>alessandrobadii</ADDEDBY>
			<SQLVERSION>1.547</SQLVERSION>
			<RMTRACKLINK>2500</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>CNF_SaleRestriction=SaleRestrictionId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_SaleRestriction
  add Updated Integer not null default 0
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>alessandrobadii</ADDEDBY>
			<SQLVERSION>1.546</SQLVERSION>
			<RMTRACKLINK>2500</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>CNF_SaleRestriction=SaleRestrictionId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>declare @foreign_key_name nvarchar(max),
@dropstmt nvarchar(max);

--Search for the name of Foreign Key
    select @foreign_key_name = f.name
      from sys.foreign_keys AS f
inner join sys.foreign_key_columns AS fc 
        on f.object_id = fc.constraint_object_id 
     where f.parent_object_id = object_id(N'[dbo].[CNF_SaleLimit]')
       and f.referenced_object_id = object_id(N'[dbo].[CNF_SaleRestriction]')
       and COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'SaleRestrictionId';

--If found delete it
if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[CNF_SaleLimit] DROP CONSTRAINT [' + @foreign_key_name + ']';
  execute sp_executesql @dropstmt
end;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DROP TABLE CNF_SaleRestriction
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_SaleRestriction]
(
        [SaleRestrictionId] Integer 

Identity(1,1) NOT NULL,
	[StartDateTime] DateTime NULL,
	[EndDateTime] DateTime NULL,
	[MaxAllowed] Integer NULL,
	[Enabled] Smallint NULL,
        [MatrixCellIds] Nvarchar(100) 

NULL,        
        [Description] Nvarchar(100) NULL 
Primary Key ([SaleRestrictionId])
) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>insert into CNF_SaleRestriction 

(CNF_SaleRestriction.StartDateTime
      ,CNF_SaleRestriction.EndDateTime
      ,CNF_SaleRestriction.MaxAllowed
      ,CNF_SaleRestriction.Enabled
      ,CNF_SaleRestriction.MatrixCellIds
      ,CNF_SaleRestriction.Description)

SELECT CNF_SaleLimit.StartDateTime
      ,CNF_SaleLimit.EndDateTime
      ,CNF_SaleLimit.MaxAllowed
      ,CNF_SaleLimit.Enabled
      ,CNF_SaleLimit.MatrixCellIds
      ,CNF_SaleLimit.description
  FROM CNF_SaleLimit
  Group by CNF_SaleLimit.StartDateTime
      ,CNF_SaleLimit.EndDateTime
      ,CNF_SaleLimit.MaxAllowed
      ,CNF_SaleLimit.Enabled
      ,CNF_SaleLimit.MatrixCellIds
      ,CNF_SaleLimit.Description
  ORDER by CNF_SaleLimit.StartDateTime, 

CNF_SaleLimit.MaxAllowed
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_SaleLimit
set CNF_SaleLimit.SaleRestrictionId = CNF_SaleRestriction.SaleRestrictionId
from CNF_SaleRestriction
Where (CNF_SaleLimit.StartDateTime = CNF_SaleRestriction.StartDateTime) and
      (CNF_SaleLimit.EndDateTime = CNF_SaleRestriction.EndDateTime) and
      (CNF_SaleLimit.MaxAllowed = CNF_SaleRestriction.MaxAllowed) and
      (CNF_SaleLimit.Enabled = CNF_SaleRestriction.Enabled) and
      (CNF_SaleLimit.MatrixCellIds = CNF_SaleRestriction.MatrixCellIds) and
      (CNF_SaleLimit.Description = CNF_SaleRestriction.Description)
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>alessandrobadii</ADDEDBY>
			<SQLVERSION>1.545</SQLVERSION>
			<RMTRACKLINK>2500</RMTRACKLINK>
			<REASON>CNF_SaleRestriction
[0] create tBLE</REASON>
			<TABLENAMES>CNF_SaleRestriction=SaleRestrictionId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_SaleRestriction]
(
        [SaleRestrictionId] Integer Identity(1,1) NOT NULL,
	[StartDateTime] DateTime NULL,
	[EndDateTime] DateTime NULL,
	[MaxAllowed] Integer NULL,
	[Used] Integer NULL,
	[Enabled] Smallint NULL,
        [MatrixCellIds] Nvarchar(100) NULL,        
        [Description] Nvarchar(100) NULL 
Primary Key ([SaleRestrictionId])
) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_SaleLimit
alter column SaleRestrictionId Integer NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_SaleLimit
add  foreign key([SaleRestrictionId]) references CNF_SaleRestriction (SaleRestrictionId)  on update no action on delete no action
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>insert into CNF_SaleRestriction (CNF_SaleRestriction.StartDateTime
      ,CNF_SaleRestriction.EndDateTime
      ,CNF_SaleRestriction.MaxAllowed
      ,CNF_SaleRestriction.Used
      ,CNF_SaleRestriction.Enabled
      ,CNF_SaleRestriction.MatrixCellIds
      ,CNF_SaleRestriction.Description)

SELECT CNF_SaleLimit.StartDateTime
      ,CNF_SaleLimit.EndDateTime
      ,CNF_SaleLimit.MaxAllowed
      ,CNF_SaleLimit.Used
      ,CNF_SaleLimit.Enabled
      ,CNF_SaleLimit.MatrixCellIds
      ,CNF_SaleLimit.description
  FROM CNF_SaleLimit
  Group by CNF_SaleLimit.StartDateTime
      ,CNF_SaleLimit.EndDateTime
      ,CNF_SaleLimit.MaxAllowed
      ,CNF_SaleLimit.Used
      ,CNF_SaleLimit.Enabled
      ,CNF_SaleLimit.MatrixCellIds
      ,CNF_SaleLimit.Description
  ORDER by CNF_SaleLimit.StartDateTime, CNF_SaleLimit.MaxAllowed
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_SaleLimit
set CNF_SaleLimit.SaleRestrictionId = CNF_SaleRestriction.SaleRestrictionId
from CNF_SaleRestriction
Where (CNF_SaleLimit.StartDateTime = CNF_SaleRestriction.StartDateTime) and
      (CNF_SaleLimit.EndDateTime = CNF_SaleRestriction.EndDateTime) and
      (CNF_SaleLimit.MaxAllowed = CNF_SaleRestriction.MaxAllowed) and
      (CNF_SaleLimit.Used = CNF_SaleRestriction.Used) and
      (CNF_SaleLimit.Enabled = CNF_SaleRestriction.Enabled) and
      (CNF_SaleLimit.MatrixCellIds = CNF_SaleRestriction.MatrixCellIds) and
      (CNF_SaleLimit.Description = CNF_SaleRestriction.Description)
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>alessandrobadii</ADDEDBY>
			<SQLVERSION>1.544</SQLVERSION>
			<RMTRACKLINK>2500</RMTRACKLINK>
			<REASON>CNF_SaleLimit
[0] add field SaleRestrictionId</REASON>
			<TABLENAMES>CNF_SaleLimit=SaleLimitId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_SaleLimit
  add SaleRestrictionId Integer null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.543</SQLVERSION>
			<RMTRACKLINK>2679</RMTRACKLINK>
			<REASON>CNF_MatrixCell
[0] update field </REASON>
			<TABLENAMES>CNF_MatrixCell=MatrixCellId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT> update CNF_MatrixCell 
   set UpgradeType=1 where UpgradeType= 0
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.542</SQLVERSION>
			<RMTRACKLINK>2742</RMTRACKLINK>
			<REASON/>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[SEAT_CNF_SpaceStructureSeat]') AND name = N'idxSEAT_CNF_SpaceStructureSeat_SpaceStructureId')
CREATE NONCLUSTERED INDEX [idxSEAT_CNF_SpaceStructureSeat_SpaceStructureId] ON [dbo].[SEAT_CNF_SpaceStructureSeat]
(
	[SpaceStructureId] ASC
)

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CNF_SpaceStructure]') AND name = N'idxCNF_SpaceStructure_AccessConfId_ExternalReference')
CREATE NONCLUSTERED INDEX [idxCNF_SpaceStructure_AccessConfId_ExternalReference] ON [dbo].[CNF_SpaceStructure]
(
	[AccessConfigurationId] ASC,
	[ExternalReference] ASC
)

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CNF_Performance]') AND name = N'idxCNF_Performance_EventDateStatus')
CREATE NONCLUSTERED INDEX [idxCNF_Performance_EventDateStatus] ON [dbo].[CNF_Performance]
(
	[EventId] ASC,
	[PerfDateTime] ASC,
	[Status] ASC
)
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[DATA_Transaction]') AND name = N'idxDATA_Transaction_Reconciliation')
CREATE NONCLUSTERED INDEX [idxDATA_Transaction_Reconciliation] ON [dbo].[DATA_Transaction]
(
	[WorkstationId] ASC,
	[Completed] ASC
)
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[DATA_SaleItem]') AND name = N'IDX_SaleItem_SaleId_Position')
CREATE NONCLUSTERED INDEX [IDX_SaleItem_SaleId_Position] ON [dbo].[DATA_SaleItem]
(
	[SaleId] ASC,
	[Position] ASC
)
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CNF_AttributeSetDetail]') AND name = N'idxCNF_AttributeSetDetail_AttributeSetId')
CREATE NONCLUSTERED INDEX [idxCNF_AttributeSetDetail_AttributeSetId] ON [dbo].[CNF_AttributeSetDetail]
(
	[AttributeSetId] ASC
)
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CNF_Performance]') AND name = N'idx_CNF_Performance_OnSale')
CREATE NONCLUSTERED INDEX [idx_CNF_Performance_OnSale] ON [dbo].[CNF_Performance]
(
	[EventId] ASC,
	[Status] ASC,
	[BlockPerformance] ASC,
	[OnSaleFrom] ASC,
	[OnSaleUntil] ASC,
	[PerformanceId] ASC,
	[PerfDateTime] ASC
)

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CNF_SeatCategory]') AND name = N'idx_CNF_SeatCategory_SaleAttribute')
CREATE NONCLUSTERED INDEX [idx_CNF_SeatCategory_SaleAttribute] ON [dbo].[CNF_SeatCategory]
(
	[PerformanceId] ASC,
	[AttributeId] ASC,
	[SeatCategoryId] ASC
)

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CNF_AttributeSetDetail]') AND name = N'dta_index_CNF_AttributeSetDetail_AttributeSet')
CREATE NONCLUSTERED INDEX [dta_index_CNF_AttributeSetDetail_AttributeSet] ON [dbo].[CNF_AttributeSetDetail]
(
	[AttributeSetId] ASC,
	[AttributeId] ASC
)

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CNF_Performance]') AND name = N'idx_CNF_Performance_OnSale')
CREATE NONCLUSTERED INDEX [idx_CNF_Performance_OnSale] ON [dbo].[CNF_Performance]
(
	[EventId] ASC,
	[Status] ASC,
	[BlockPerformance] ASC,
	[OnSaleFrom] ASC,
	[OnSaleUntil] ASC,
	[PerformanceId] ASC,
	[PerfDateTime] ASC
)

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CNF_SeatCategory]') AND name = N'idx_CNF_SeatCategory_SaleAttribute')
CREATE NONCLUSTERED INDEX [idx_CNF_SeatCategory_SaleAttribute] ON [dbo].[CNF_SeatCategory]
(
	[PerformanceId] ASC,
	[AttributeId] ASC
)

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CNF_AttributeSetDetail]') AND name = N'dta_index_CNF_AttributeSetDetail_AttributeSet')
CREATE NONCLUSTERED INDEX [dta_index_CNF_AttributeSetDetail_AttributeSet] ON [dbo].[CNF_AttributeSetDetail]
(
	[AttributeSetId] ASC,
	[AttributeId] ASC
)
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CNF_EnvelopeCapacity]') AND name = N'idx_CNF_EnvelopeCapacity_Qty')
CREATE NONCLUSTERED INDEX [idx_CNF_EnvelopeCapacity_Qty] ON [dbo].[CNF_EnvelopeCapacity]
(
	[SpaceStructureId] ASC,
	[Quantity] ASC
)
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CNF_EnvelopeCapacity]') AND name = N'idx_CNF_EnvelopeCapacity_CategoryQty')
CREATE NONCLUSTERED INDEX [idx_CNF_EnvelopeCapacity_CategoryQty] ON [dbo].[CNF_EnvelopeCapacity]
(
	[SeatCategoryId] ASC,
	[Quantity] ASC,
	[SpaceStructureId] ASC
)
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[DATA_SaleItem2Ticket]') AND name = N'idxSaleItem2Ticket_TicketId')

CREATE NONCLUSTERED INDEX [idxSaleItem2Ticket_TicketId] ON [dbo].[DATA_SaleItem2Ticket]
(
	[TicketId] ASC
)
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[DATA_Transaction]') AND name = N'idxDATA_Transaction_DataWkSerial')
CREATE NONCLUSTERED INDEX [idxDATA_Transaction_DataWkSerial] ON [dbo].[DATA_Transaction]
(
	[FTransactionDate] ASC,
	[WorkstationId] ASC,
	[Serial] ASC
)
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[DATA_Ledger]') AND name = N'idxDATA_LedgerAccountId')
CREATE NONCLUSTERED INDEX [idxDATA_LedgerAccountId] ON [dbo].[DATA_Ledger]
(
	[LedgerAccountId] ASC,
	[DueDate] ASC,
	[ReferenceTable] ASC,
	[ReferenceId] ASC
)

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Andrea L</ADDEDBY>
			<SQLVERSION>1.541</SQLVERSION>
			<RMTRACKLINK>2754</RMTRACKLINK>
			<REASON>Add CreatableOnPos field on CNF_Promotion</REASON>
			<TABLENAMES>CNF_Promotion=PromotionId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Promotion 
  add CreatableOnPos smallint not null default 0
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.540</SQLVERSION>
			<RMTRACKLINK>1042</RMTRACKLINK>
			<REASON>CNF_Performance
[0] add field OpeningTime null
[1] add field ClosingTime null
[2]
[3]
[4]
[5]</REASON>
			<TABLENAMES>CNF_Performance=PerformanceId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_Performance
  add OpeningTime DateTime null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_Performance
  add ClosingTime DateTime null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_Performance
  set  OpeningTime=PerfDateTime
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_Performance
  set ClosingTime=PerformanceEnd
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Performance
  alter column OpeningTime DateTime not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Performance
  alter column ClosingTime DateTime not null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>francescosalvi</ADDEDBY>
			<SQLVERSION>1.539</SQLVERSION>
			<RMTRACKLINK>2469</RMTRACKLINK>
			<REASON>Added field CNF_MatrixCellInfo.ForceReservation</REASON>
			<TABLENAMES>CNF_MatrixCellInfo=MatrixCellInfoId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_MatrixCellInfo add ForceReservation smallint not null default 0;

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.538</SQLVERSION>
			<RMTRACKLINK>2679</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>CNF_MatrixCellInfo=MatrixCellInfoId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>update cnf_matrixcell
set    UpgradeType = 3
where
matrixcellid in (select matrixcellid from cnf_matrixcellinfo where NotUpgradable=1)
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>declare @foreign_key_name nvarchar(max),
@dropstmt nvarchar(max);


select @foreign_key_name = c.name from 
sys.all_columns a 
inner join
sys.tables b 
on 
a.object_id = b.object_id
inner join
sys.default_constraints c
on a.default_object_id = c.object_id
where b.name='CNF_MatrixCellInfo'
and a.name = 'NotUpgradable'


if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[CNF_MatrixCellInfo] DROP CONSTRAINT [' + @foreign_key_name + ']';
  execute sp_executesql @dropstmt
end;


				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>    alter table cnf_matrixcellinfo drop column NotUpgradable;
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.537</SQLVERSION>
			<RMTRACKLINK>2679</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>CNF_MatrixCell=MatrixCellId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table cnf_matrixcell add UpgradeType smallint not null default 0;

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.536</SQLVERSION>
			<RMTRACKLINK>2561</RMTRACKLINK>
			<REASON>DATA_Account
[0] add field BilligAccountId int null
[1] add Fk on itself</REASON>
			<TABLENAMES>DATA_Account=AccountId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table DATA_Account
  add BillingAccountId integer null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table DATA_Account 
  add foreign key(BillingAccountId) references DATA_Account (AccountId)  on update no action on delete no action 
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.535</SQLVERSION>
			<RMTRACKLINK>2561</RMTRACKLINK>
			<REASON>DATA_Reservation
[0] add field BillingAccountId
[1] add Fk on AccountId</REASON>
			<TABLENAMES>DATA_Reservation=SaleId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table DATA_Reservation
 add BillingAccountId integer null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table DATA_Reservation 
add  foreign key(BillingAccountId) references DATA_Account (AccountId)  on update no action on delete no action 
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.534</SQLVERSION>
			<RMTRACKLINK>2336</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>CNF_Commission2Account=Commission2AccountId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table [CNF_Commission2Account] add [CustomPayId] Integer NULL;

Alter table [CNF_Commission2Account] add constraint FKCommision2Account_CustomPay foreign key([CustomPayId]) references [CNF_PAY] ([PayId]);
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>davideapicella</ADDEDBY>
			<SQLVERSION>1.533</SQLVERSION>
			<RMTRACKLINK>2584</RMTRACKLINK>
			<REASON>delete wrong/old translation value from CNF_MatrixCellTranslation
add contraint</REASON>
			<TABLENAMES>CNF_MatrixCellTranslation=MatrixCellTranslationId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Delete FROM CNF_MatrixCellTranslation 
WHERE not Exists
(SELECT MYCNF_MatrixCellTranslation.MatrixCellTranslationId FROM
	(SELECT     
	MAX(MatrixCellTranslationId) AS MatrixCellTranslationId, 
	LanguageId, 
	MatrixCellId
	FROM CNF_MatrixCellTranslation
        GROUP BY LanguageId, MatrixCellId) AS MYCNF_MatrixCellTranslation
WHERE MYCNF_MatrixCellTranslation.MatrixCellTranslationId = CNF_MatrixCellTranslation.MatrixCellTranslationId)
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE CNF_MatrixCellTranslation
ADD CONSTRAINT uc_CNF_MatrixCellTranslation_MatrixCellId_LanguageId UNIQUE (MatrixCellId, LanguageId)
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.532</SQLVERSION>
			<RMTRACKLINK>2542</RMTRACKLINK>
			<REASON>CNF_MatrixCell
			</REASON>
			<TABLENAMES>CNF_MatrixCell=MatrixCellid</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_MatrixCell
  add CreationDate Datetime 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table  CNF_MatrixCell
  add LastUpdDate Datetime 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> update CNF_MatrixCell 
   set CreationDate = GetDate()
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> update CNF_MatrixCell 
   set LastUpdDate = GetDate()
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_MatrixCell 
  alter column  CreationDate Datetime NOT NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_MatrixCell 
  alter column  LastUpdDate Datetime NOT NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.531</SQLVERSION>
			<RMTRACKLINK>2572</RMTRACKLINK>
			<REASON>DATA_Account 
[0] drop index on DisplayName
[1] alter fields

DATA_DmgData
[2] alter field

DATA_DmgData_Translate
[3] alter field

[4] re-create index on DisplayName</REASON>
			<TABLENAMES>DATA_Account=AccountId
DATA_DmgData=DmgDataId
DATA_DmgData_Translate=DmgDataTranslateId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>DROP INDEX IDX_Account_DisplayName 
  ON DATA_Account

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Account
  alter column  ExternalCode1 Nvarchar(200) NULL

alter table DATA_Account
  alter column  DisplayName Nvarchar(200) NULL

alter table DATA_Account
  alter column  [FirstName] Nvarchar(200) NULL

alter table DATA_Account
  alter column  [SurName] Nvarchar(200) NULL

alter table DATA_Account
  alter column   [CompanyName] Nvarchar(200) NULL

alter table DATA_Account
  alter column  [Address1] Nvarchar(200) NULL

alter table DATA_Account
  alter column [ZipCode] Nvarchar(200) NULL

alter table DATA_Account
  alter column [City] Nvarchar(200) NULL

alter table DATA_Account
  alter column  [State] Nvarchar(200) NULL

alter table DATA_Account
  alter column  [Country] Nvarchar(200) NULL

alter table DATA_Account
  alter column  [HomePhone] Nvarchar(200) NULL

alter table DATA_Account
  alter column  [BusinessPhone] Nvarchar(200) NULL

alter table DATA_Account
  alter column [Fax] Nvarchar(200) NULL

alter table DATA_Account
  alter column  [MobilePhone] Nvarchar(200) NULL

alter table DATA_Account
  alter column  [EmailAddress1] Nvarchar(200) NULL     
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> Alter table DATA_DmgData 
   alter column MaskData Nvarchar(200) NOT NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_DmgData_Translate
  alter column MaskData Nvarchar(200) NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE NONCLUSTERED INDEX IDX_Account_DisplayName ON DATA_Account
(
	[DisplayName] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ettore Bottega</ADDEDBY>
			<SQLVERSION>1.530</SQLVERSION>
			<RMTRACKLINK>2549</RMTRACKLINK>
			<REASON/>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE NONCLUSTERED INDEX [idxDATA_MediaIdentifier_MediaId] ON [dbo].[DATA_MediaIdentifier]
(
	[MediaId] ASC
)

CREATE NONCLUSTERED INDEX [idxDATA_SaleItem2Ticket_SaleItemId] ON [dbo].[DATA_SaleItem2Ticket]
(
	[SaleItemId] ASC
)
CREATE NONCLUSTERED INDEX [idxDATA_SaleItem2Performance_SaleItemId] ON [dbo].[DATA_SaleItem2Performance]
(
	[SaleItemId] ASC
)
CREATE NONCLUSTERED INDEX [idxDATA_Ticket_SaleItemID] ON [dbo].[DATA_Ticket]
(
	[SaleItemId] ASC
)
CREATE NONCLUSTERED INDEX [idxDATA_TransactionItem_SaleItemID] ON [dbo].[DATA_TransactionItem]
(
	[SaleItemId] ASC
)

CREATE NONCLUSTERED INDEX [idxDATA_SaleItem2Account_SaleItemId] ON [dbo].[DATA_SaleItem2Account]
(
	[SaleItemId] ASC
)

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.529</SQLVERSION>
			<RMTRACKLINK>2585</RMTRACKLINK>
			<REASON>DATA_Ticket
[0] add flag renewed not null
[1] update old data</REASON>
			<TABLENAMES>DATA_Ticket=TicketId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Ticket
 add Renewed Smallint Default 0 NOT NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_Ticket 
  set Renewed = 1
  where TicketId in 
  (select  SI.TicketId
   from DATA_Transaction as TR 
        inner join DATA_Transactionitem as TI on(TR.TransactionId=TI.TransactionId)
        inner join DATA_SaleItem as SI on (TI.SaleItemId=SI.SaleItemid)
   where 
    TR.TransactionType = 9 
    and SI.TicketId is not null)
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.528</SQLVERSION>
			<RMTRACKLINK>1579</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>CNF_Pay=PayId
CNF_Pay_MatrixCell=PayMatrixCellId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Pay_MatrixCell add 	[UseInRangeFilter] Smallint default 1 NOT NULL;
alter table CNF_Pay_MatrixCell add 	[UseInOutputQty] Smallint default 1 NOT NULL;
alter table CNF_Pay_MatrixCell add 	[Value]   [float]   NULL;

alter table CNF_Pay add [MatrixCellId] Integer NULL;

Alter table [CNF_PAY] add constraint FKCnf_pay_MatrixCellId foreign key([MatrixCellId]) references [CNF_MatrixCell] ([MatrixCellId]); 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>alessandrobadii</ADDEDBY>
			<SQLVERSION>1.527</SQLVERSION>
			<RMTRACKLINK>2560</RMTRACKLINK>
			<REASON>CNF_IncentiveTicket
[0] ALTER COLUMN [MatrixCellId]</REASON>
			<TABLENAMES>CNF_IncentiveTicket=IncentiveTicketId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_IncentiveTicket
alter column MatrixCellId Int not Null;

Alter table CNF_IncentiveTicket 
add foreign key(MatrixCellId) references CNF_MatrixCell (MatrixCellId) on update no action on delete no action;
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>1.526</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>FIX PROBLEM ON SMALLINT FIELDS INSTEAD INTEGER
--&gt; PATCH 1.487
--&gt; PATCH 1.501

[0] - PATCH 1.487 - CNF_Survey - Field DmgCategoryId - Add foreign key on CNF_DmgCategory
[1] - PATCH 1.501 - CNF_MatrixSheet - SortOrder




			</REASON>
			<TABLENAMES>CNF_MatrixSheet=MatrixSheetId
CNF_Survey=SurveyId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_Survey
alter column DmgCategoryId Int Null;

Alter table CNF_Survey 
add foreign key(DmgCategoryId) references CNF_DmgCategory (DmgCategoryId) on update no action on delete no action;



				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_MatrixSheet
alter column SortOrder int NULL;


				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>davideapicella</ADDEDBY>
			<SQLVERSION>1.525</SQLVERSION>
			<RMTRACKLINK>2557</RMTRACKLINK>
			<REASON>Add Column QuickUpgradeOnly</REASON>
			<TABLENAMES>CNF_MatrixCellInfo=MatrixCellInfoId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter Table CNF_MatrixCellInfo 
Add QuickUpgradeOnly SmallInt NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Update CNF_MatrixCellInfo 
Set QuickUpgradeOnly = 0
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_MatrixCellInfo
  alter column QuickUpgradeOnly Smallint not null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>alessandrobadii</ADDEDBY>
			<SQLVERSION>1.524</SQLVERSION>
			<RMTRACKLINK>2560</RMTRACKLINK>
			<REASON>CNF_IncentiveTicket
[0] ALTER COLUMN [MatrixCellId]</REASON>
			<TABLENAMES>CNF_IncentiveTicket=IncentiveTicketId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>declare @foreign_key_name nvarchar(max),
@dropstmt nvarchar(max);

--Search for the name of Foreign Key
    select @foreign_key_name = f.name
      from sys.foreign_keys AS f
inner join sys.foreign_key_columns AS fc 
        on f.object_id = fc.constraint_object_id 
     where f.parent_object_id = object_id(N'[dbo].[CNF_IncentiveTicket]')
       and f.referenced_object_id = object_id(N'[dbo].[CNF_MatrixCell]')
       and COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'MatrixCellId';

--If found delete it
if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[CNF_IncentiveTicket] DROP CONSTRAINT [' + @foreign_key_name + ']';
  execute sp_executesql @dropstmt
end;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_IncentiveTicket
alter column MatrixCellId SmallInt Null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.523</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>DATA_Account
 [0] add field UserId
[1] add FK on CNF_User</REASON>
			<TABLENAMES>DATA_Account=AccountId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Account
  add UserId int null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table DATA_Account 
  add  foreign key(UserId) references CNF_User (UserId)

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.522</SQLVERSION>
			<RMTRACKLINK>2558</RMTRACKLINK>
			<REASON>CNF_MatrixCell
[0] add field AdditionalDescription</REASON>
			<TABLENAMES>CNF_matrixCell=MatrixCellId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_matrixCell
  add AdditionalDescription Nvarchar(100) NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.521</SQLVERSION>
			<RMTRACKLINK>2531</RMTRACKLINK>
			<REASON>DATA_MediaStoredValue
[0] add column matrixCellid nullable
[1] remove FK from TicketId
[2] fill field TicketId
[3]fill matrixCellid
[4] set MatrixcellId as not null
[5] add FK on TicketId
[6] add FK on MatrixCellId
			</REASON>
			<TABLENAMES>DATA_MediaStoredValue=MediaStoredValueId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table DATA_MediaStoredValue
  add MatrixCellId int default 1
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>declare @foreign_key_name nvarchar(max),
@dropstmt nvarchar(max);

select @foreign_key_name = f.name
from sys.foreign_keys AS f
inner join sys.foreign_key_columns AS fc 
on  f.object_id = fc.constraint_object_id 
where  f.parent_object_id = object_id(N'dbo.DATA_MediaStoredValue')
and  f.referenced_object_id = object_id(N'dbo.DATA_Ticket')
and COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'TicketId';

--Se lo Trovo lo cancello
if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE dbo.DATA_MediaStoredValue DROP CONSTRAINT [' + @foreign_key_name + ']';
  execute sp_executesql @dropstmt
end;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_MediaStoredValue 
set TicketId = 
(
select top 1 T2M.TicketId
from DATA_MediaStoredValue as MSV 
  inner join DATA_Ticket2Media as T2m on (T2m.MediaId=MSV.MediaId)
 where DATA_MediaStoredValue.MediaStoredValueId = MSV.MediaStoredValueId 
 )
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_MediaStoredValue 
set MatrixCellId = 
(
select top 1 TI.MatrixCellId
from DATA_MediaStoredValue as MSV 
  inner join DATA_Ticket2Media as T2m on (T2m.MediaId=MSV.MediaId)
  inner join DATA_Ticket as TI on (TI.TicketId=T2M.TicketId)
 where DATA_MediaStoredValue.MediaStoredValueId = MSV.MediaStoredValueId 
 )
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_MediaStoredValue
  alter column MatrixCellId int not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> Alter table [DATA_MediaStoredValue] 
 add  foreign key(TicketId) references DATA_Ticket (TicketId)
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> Alter table [DATA_MediaStoredValue] 
 add  foreign key(MatrixCellId) references CNF_MatrixCell (MatrixCellId)
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>davideapicella</ADDEDBY>
			<SQLVERSION>1.520</SQLVERSION>
			<RMTRACKLINK>2026</RMTRACKLINK>
			<REASON>CNF_SaleLimit
Add Column Description
move data from MatrixCellIds to Description
Alter Column Description Not Null
			</REASON>
			<TABLENAMES>CNF_SaleLimit=SaleLimitId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter Table CNF_SaleLimit 
Add Description Nvarchar(100) NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_SaleLimit
set Description = (Case when (MatrixCellIds Is Null) then '' else CONVERT(nvarchar,MatrixCellIds) end)
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_SaleLimit
alter column Description Nvarchar(100) not null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>OTNALO</ADDEDBY>
			<SQLVERSION>1.519</SQLVERSION>
			<RMTRACKLINK>2338,2146</RMTRACKLINK>
			<REASON>Added new stored about DmgCategory hierarchy</REASON>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>create view vwDmgCategoryHiercachy
as
WITH DmgHiercachy AS
 (SELECT DmgCategoryId, DmgCategoryId DMGParentId, 0 as level, description as parentdescr, description
    FROM CNF_DmgCategory
   WHERE DmgType = 1 
  UNION ALL
  SELECT DmgParent.DmgCategoryId, 
         DmgHiercachy.DmgParentId,DmgHiercachy.level +1 as level,
         DmgHiercachy.parentdescr as parentdescr, DmgParent.description
    FROM CNF_DmgCategory DmgParent, DmgHiercachy
   WHERE DmgParent.DMGParentId = DmgHiercachy.DmgCategoryId)
SELECT DmgCategoryId, DmgParentId, level, parentdescr, Description 
  FROM DmgHiercachy

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>davideapicella</ADDEDBY>
			<SQLVERSION>1.518</SQLVERSION>
			<RMTRACKLINK>2026</RMTRACKLINK>
			<REASON>CNF_SaleLimit
Add Column MatrixCellIds
move data from MatrixCellId to MatrixCellIds
drop field MatrixCellId</REASON>
			<TABLENAMES>CNF_SaleLimit=SaleLimitId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter Table CNF_SaleLimit 
Add MatrixCellIds Nvarchar(1000) NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_SaleLimit
set MatrixCellIds = MatrixCellId 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_SaleLimit
DROP COLUMN MatrixCellId
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>davideapicella</ADDEDBY>
			<SQLVERSION>1.517</SQLVERSION>
			<RMTRACKLINK>2517</RMTRACKLINK>
			<REASON>Add Column OffLineImport
Update column OffLineImport
alter column OffLineImport not null</REASON>
			<TABLENAMES>DATA_Box=BoxId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table DATA_Box
  Add OffLineImport Smallint 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Update DATA_Box
set OffLineImport = 0 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table DATA_Box
  alter column OffLineImport Smallint not null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.516</SQLVERSION>
			<RMTRACKLINK>2527</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>CNF_MatrixCellTranslation=MatrixCellTranslationId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_MatrixCellTranslation
  alter column ShortName nvarchar(50)
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_MatrixCellTranslation
  alter column LongName nvarchar(250)
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_MatrixCellTranslation
  alter column ShortDescription nvarchar(50)
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_MatrixCellTranslation
  alter column LongDescription nvarchar(250)
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>davideapicella</ADDEDBY>
			<SQLVERSION>1.515</SQLVERSION>
			<RMTRACKLINK>785</RMTRACKLINK>
			<REASON>Add Column QuickUpgradeIds</REASON>
			<TABLENAMES>CNF_MatrixCellInfo=MatrixCellInfoId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter Table CNF_MatrixCellInfo 
Add QuickUpgradeIds Nvarchar(1000) NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.514</SQLVERSION>
			<RMTRACKLINK>1578</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>CNF_PAY=PayID
CNF_Pay_MatrixCell=PayMatrixCellId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>


declare @foreign_key_name nvarchar(max),
@dropstmt nvarchar(max);

select @foreign_key_name=f.name
from sys.foreign_keys AS f
inner join sys.foreign_key_columns AS fc 
on  f.object_id = fc.constraint_object_id 
where
object_name(f.parent_object_id) = 'CNF_Pay' and
object_name(f.referenced_object_id) = 'CNF_MatrixCell'

select @foreign_key_name

--Se lo Trovo lo cancello
if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[CNF_Pay] DROP CONSTRAINT [' + @foreign_key_name + ']';
  execute sp_executesql @dropstmt
end;

Alter Table CNF_Pay drop column MatrixCellid

Create table [CNF_Pay_MatrixCell]
(
	[PayMatrixCellId] Integer Identity(1,1) NOT NULL,
	[PayId] Integer NOT NULL,
	[MatrixCellId] Integer NOT NULL,
Primary Key ([PayMatrixCellId])
) 


Alter table [CNF_Pay_MatrixCell] add constraint FK_CNF_PayMatrixCell_CNF_MatrixCell foreign key([MatrixCellId]) references [CNF_MatrixCell] ([MatrixCellId])
Alter table [CNF_Pay_MatrixCell] add constraint FK_CNF_PayMatrixCell_CNF_Pay  foreign key([PayId]) references [CNF_PAY] ([PayId])  on update no action on delete no action   


				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.513</SQLVERSION>
			<RMTRACKLINK>1578</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>DATA_Ledger=LedgerId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter Table DATA_Ledger Add DueDate smalldatetime
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>davideapicella</ADDEDBY>
			<SQLVERSION>1.512</SQLVERSION>
			<RMTRACKLINK>2352</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>DATA_DepositDetail=DepositDetailId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table DATA_DepositDetail
  add CurrencyAmount Float NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.511</SQLVERSION>
			<RMTRACKLINK>2211</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>RES_CNF_ResourcePriority=ResourcePriorityId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>
Create table [RES_CNF_ResourcePriority]
(
	[ResourcePriorityId] Integer Identity(1,1) NOT NULL,
	[RequirementTemplateId] Integer NOT NULL,
	[ResourceId] Integer NOT NULL,
	[Priority] Integer NOT NULL,
Primary Key ([ResourcePriorityId])
)


Alter table [RES_CNF_ResourcePriority] add constraint FKResourcePriority_Template foreign key([RequirementTemplateId]) references [RES_CNF_RequirementTemplate] ([RequirementTemplateId])

Alter table [RES_CNF_ResourcePriority] add constraint FKResourcePriority_Resource foreign key([ResourceId]) references [RES_CNF_Resource] ([ResourceId])   
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>davideapicella</ADDEDBY>
			<SQLVERSION>1.510</SQLVERSION>
			<RMTRACKLINK>2370</RMTRACKLINK>
			<REASON>DATA_PaymentB2B
[0] create table
[1] add FPK on DATA_Payment</REASON>
			<TABLENAMES>DATA_PaymentB2B=PaymentId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [DATA_PaymentB2B]
(
	[PaymentId] Integer NOT NULL,
	[AccountId] Integer NOT NULL,
Primary Key ([PaymentId])
)
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table DATA_PaymentB2B add  foreign key(PaymentId) references DATA_Payment (PaymentId) on update no action on delete no action
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.509</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>CNF_CostCenterValidity
[0] add field SiteId
[1] add FK on SiteId</REASON>
			<TABLENAMES>CNF_CostCenter_Validity=CostCenterValidityId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_CostCenter_Validity
  add SiteId Integer NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_CostCenter_Validity 
  add  foreign key(SiteId) references CNF_Site (SiteId)  on update no action on delete no action 
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.508</SQLVERSION>
			<RMTRACKLINK>2331</RMTRACKLINK>
			<REASON/>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[DATA_UserLog]') AND name = N'IdxData_UserLog_Workstationid')
CREATE NONCLUSTERED INDEX [IdxData_UserLog_Workstationid] ON [dbo].[DATA_UserLog]
(
	[WorkstationId] ASC
)

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[DATA_Ticket2Media]') AND name = N'idxTicket2Media_TicketId')
CREATE NONCLUSTERED INDEX [idxTicket2Media_TicketId] ON [dbo].[DATA_Ticket2Media]
(
	[TicketId] ASC
)

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.507</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>CNF_ExternalStoredInfo
[0] create tBLE
[1] ADD FK on AttributeId
[2] ADD FK on AttributeId
[3] ADD FK on AttributeId</REASON>
			<TABLENAMES>CNF_ExternalStoredInfo=ExternalMediaTypeId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_ExternalStoredInfo]
(
        [ExternalMediaTypeId] Integer NOT NULL,
	[TicketType1] Integer NULL,
	[TicketType2] Integer NULL,
	[TicketType3] Integer NULL,
	[AttributeTemplateId] Integer NULL,
	[StoredInfoType] Smallint NULL,
Primary Key ([ExternalMediaTypeId])
) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_ExternalStoredInfo 
add  foreign key([TicketType1]) references CNF_Attribute (AttributeId)  on update no action on delete no action 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_ExternalStoredInfo 
add  foreign key([TicketType2]) references CNF_Attribute (AttributeId)  on update no action on delete no action 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_ExternalStoredInfo 
add  foreign key([TicketType3]) references CNF_Attribute (AttributeId)  on update no action on delete no action 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.506</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>DATA_Media
[0] add field WriteInfoOnChip</REASON>
			<TABLENAMES>DATA_Media=MediaId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table DATA_Media
  add WriteInfoOnChip Smallint Default 0 NOT NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Andrea L</ADDEDBY>
			<SQLVERSION>1.505</SQLVERSION>
			<RMTRACKLINK>2338</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>CNF_PromotionPermission=PromotionPermissionId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_PromotionPermission]
(
	[PromotionPermissionId] Integer Identity(1,1) NOT NULL,
	[PromotionId] Integer NOT NULL,
	[SiteId] Integer NULL,
	[OperatingAreaId] Integer NULL,
	[WorkstationId] Integer NULL,
	[UserGroupId] Integer NULL,
	[UserId] Integer NULL,
	[DmgCategoryId] Integer NULL,
	[AccountId] Integer NULL,
	[Allow] Smallint NULL,
Primary Key ([PromotionPermissionId])
)
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_PromotionPermission add foreign key(PromotionId) references CNF_Promotion (PromotionId) on update no action on delete no action
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_PromotionPermission add foreign key(SiteId) references CNF_Site (SiteId) on update no action on delete no action
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_PromotionPermission add foreign key(OperatingAreaId) references CNF_OperatingArea (OperatingAreaId) on update no action on delete no action
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_PromotionPermission add foreign key(WorkstationId) references CNF_Workstation (WorkstationId) on update no action on delete no action
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_PromotionPermission add foreign key(UserGroupId) references CNF_UserGroup (UserGroupId) on update no action on delete no action
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_PromotionPermission add foreign key(UserId) references CNF_User (UserId) on update no action on delete no action
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_PromotionPermission add foreign key(DmgCategoryId) references CNF_DmgCategory (DmgCategoryId) on update no action on delete no action
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_PromotionPermission add foreign key(AccountId) references DATA_Account (AccountId) on update no action on delete no action
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>davideapicella</ADDEDBY>
			<SQLVERSION>1.504</SQLVERSION>
			<RMTRACKLINK>2308,2396</RMTRACKLINK>
			<REASON>DATA_Coupon
DATA_SaleCoupon
DATA_SaleItemRule
[0] create table
[1] add FPK on DATA_Coupon
[2] add Index on DATA_Coupon
[3] add Index on DATA_Coupon
[4] add row on DATA_SaleCoupon
[5] add Index on DATA_SaleCoupon
[6] add FPK On DATA_SaleCoupon
[7] add row on DATA_SaleItemRule</REASON>
			<TABLENAMES>DATA_Coupon=CouponId
DATA_SaleCoupon=SaleCouponId
DATA_SaleItemRule=SaleItemRuleId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [DATA_Coupon]
(
	[CouponId] Integer Identity(1,1) NOT NULL,
	[PromotionId] Integer NOT NULL,
	[CouponSerial] Nvarchar(40) NOT NULL,
	[UserId] Integer NOT NULL,
	[InsertDateTime] Datetime NOT NULL,
	Primary Key ([CouponId])

)
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table DATA_Coupon add  foreign key(PromotionId) references CNF_Promotion (PromotionId) on update no action on delete no action 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create Unique Index DATA_Coupon_PromotionId_CouponSerial ON DATA_Coupon (PromotionId ,CouponSerial) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create Index DATA_Coupon_CouponSerial ON DATA_Coupon (CouponSerial) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table DATA_SaleCoupon 
Add CouponId Integer Default Null NULL

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create Index DATA_SaleCoupon_PromotionId_CouponId ON DATA_SaleCoupon (PromotionId,CouponId)
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table DATA_SaleCoupon add  foreign key(CouponId) references DATA_Coupon (CouponId) on update no action on delete no action

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table DATA_SaleItemRule 
Add DiscountAmount Float NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.503</SQLVERSION>
			<RMTRACKLINK>2123</RMTRACKLINK>
			<REASON>CNF_MatrixCellInfo
[0] create table
[1] add FK on MatrixCellInfo
[2] create row for matrixCell
[3] move backGroundColor information
[4] move IgnoreAttributeValidity information
[5] move IgnoreEncodedValidity information
[6] move TransReceiptNotRequired information
[7] move NotUpgradable information</REASON>
			<TABLENAMES>CNF_MatrixCellInfo=MatrixCellInfoId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_MatrixCellInfo]
(
	[MatrixCellInfoId] Integer Identity(1,1) NOT NULL, UNIQUE ([MatrixCellInfoId]),
	[MatrixCellId] Integer NOT NULL, UNIQUE ([MatrixCellId]),
	[NeedApproval] Smallint Default 0 NOT NULL,
	[TransReceiptNotRequired] Smallint Default 0 NOT NULL,
	[IgnoreEncodedValidity] Smallint Default 0 NOT NULL,
	[IgnoreAttributeValidity] Smallint Default 0 NOT NULL,
	[BackGroundColor] Nvarchar(10) Default 'DEFAULT' NOT NULL,
	[NotUpgradable] Smallint Default 0 NOT NULL,
Primary Key ([MatrixCellInfoId])
) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> Alter table CNF_MatrixCellInfo add  foreign key(MatrixCellId) references CNF_MatrixCell (MatrixCellId)  
 on update no action on delete no action 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>insert into CNF_MatrixCellInfo ( MatrixCellId) 
(select CNF_MatrixCell.MatrixCellId from CNF_MatrixCell) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_MatrixCellInfo 
set BackGroundColor = 
(
  select case when MCO.OptionValue = '' then 'DEFAULT' else  MCO.OptionValue end					
  from CNF_MatrixCellOption as MCO 
  where MCO.OptionType=1 and MCO.MatrixCellId=CNF_MatrixCellInfo.MatrixCellId
)
where Exists
( select CNF_MatrixCellOption.OptionValue  
  from CNF_MatrixCellOption 
  where CNF_MatrixCellOption.OptionType=1 and CNF_MatrixCellOption.MatrixCellId=CNF_MatrixCellInfo.MatrixCellId
)
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_MatrixCellInfo 
  set IgnoreAttributeValidity = 
  (
    select case when MCO.OptionValue = 'True' then 1 else  0 end
    from CNF_MatrixCellOption as MCO 
    where MCO.OptionType=8 and MCO.MatrixCellId=CNF_MatrixCellInfo.MatrixCellId
)
where Exists
( select CNF_MatrixCellOption.OptionValue  
  from CNF_MatrixCellOption 
  where CNF_MatrixCellOption.OptionType=8 and CNF_MatrixCellOption.MatrixCellId=CNF_MatrixCellInfo.MatrixCellId
)
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_MatrixCellInfo 
set IgnoreEncodedValidity = 
(
  select case when MCO.OptionValue = 'True' then 1 else  0 end
  from CNF_MatrixCellOption as MCO 
  where MCO.OptionType=18 and MCO.MatrixCellId=CNF_MatrixCellInfo.MatrixCellId
) 
where Exists
( select CNF_MatrixCellOption.OptionValue  
  from CNF_MatrixCellOption 
  where CNF_MatrixCellOption.OptionType=18 and CNF_MatrixCellOption.MatrixCellId=CNF_MatrixCellInfo.MatrixCellId
)
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_MatrixCellInfo 
set TransReceiptNotRequired = 
(
  select case when MCO.OptionValue = 'True' then 1 else  0 end
  from CNF_MatrixCellOption as MCO 
  where MCO.OptionType=19 and MCO.MatrixCellId=CNF_MatrixCellInfo.MatrixCellId
)
where Exists
( select CNF_MatrixCellOption.OptionValue  
  from CNF_MatrixCellOption 
  where CNF_MatrixCellOption.OptionType=19 and CNF_MatrixCellOption.MatrixCellId=CNF_MatrixCellInfo.MatrixCellId
)

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_MatrixCellInfo 
set NotUpgradable = 
(
  select case when MCO.OptionValue = 'True' then 1 else  0 end
  from CNF_MatrixCellOption as MCO 
  where MCO.OptionType=20 and MCO.MatrixCellId=CNF_MatrixCellInfo.MatrixCellId
)
where exists 
(
  select MCO.OptionValue  
  from CNF_MatrixCellOption as MCO
  where MCO.OptionType=20 and MCO.MatrixCellId=CNF_MatrixCellInfo.MatrixCellId
)
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AlessandroBadii</ADDEDBY>
			<SQLVERSION>1.502</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>DATA_MediaIdentifierBlackList

[0] Add UserId Integer
[1] Update old data for UserId
[2] Add InsertDateTime dateTime
[3] Update old data for InsertDateTime
[4] Apply not null to UserId field
[5] Apply not null to InsertDateTime
[6] Apply foreign key to field UserId on CNF_User


			</REASON>
			<TABLENAMES>DATA_MediaIdentifierBlackList=MediaBlackListId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table DATA_MediaIdentifierBlackList
add UserId Integer
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>

update DATA_MediaIdentifierBlackList
set UserId = 1


				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table DATA_MediaIdentifierBlackList
add InsertDateTime Datetime 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>
update DATA_MediaIdentifierBlackList
set InsertDateTime = GetDate()


				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>
Alter table DATA_MediaIdentifierBlackList
Alter Column UserId Integer not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>

Alter table DATA_MediaIdentifierBlackList
Alter Column InsertDateTime Datetime not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>

 Alter table DATA_MediaIdentifierBlackList 
 add  foreign key(UserId) references CNF_User (UserId)
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AlessandroBadii</ADDEDBY>
			<SQLVERSION>1.501</SQLVERSION>
			<RMTRACKLINK>2035</RMTRACKLINK>
			<REASON>CNF_MatrixSheet
[0] Add SortOrder</REASON>
			<TABLENAMES>CNF_MatrixSheet=MatrixSheetId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_MatrixSheet
add SortOrder Smallint NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.500</SQLVERSION>
			<RMTRACKLINK>2364</RMTRACKLINK>
			<REASON>Added store procedure to improve import performance</REASON>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE PROCEDURE sp_ManageDATA_DmgData
(
 @ObjType  smallint,
 @MaskData nvarchar(200),
 @DmgType  smallint,
 @FKey     int
)
AS
BEGIN
  DECLARE @DmgDataId   int
  DECLARE @FieldNumber smallInt
  DECLARE @DataMaskId  int
  SET @FieldNumber     = null
  SET @DataMaskId      = null
  --PRINT '@OBJTYPE =  ' + CAST(@OBJTYPE AS VARCHAR)
  --PRINT '@MaskData = ' + @MaskData
  SELECT @DmgDataId = DATA_DmgData.DmgDataId
    FROM DATA_DmgData
   WHERE DATA_DmgData.FKey    = @FKey   
     AND DATA_DmgData.ObjType = @ObjType
     AND DATA_DmgData.DmgType = @Dmgtype;
  IF (@DmgDataId IS NULL)
   BEGIN
     --PRINT 'INSERT'
     insert into DATA_DmgData (
        FieldNumber,
     ObjType,
        MaskData,
        DataMaskId,
        DmgType,
        FKey
        ) values (
        @FieldNumber,
        @ObjType,
        @MaskData,
        @DataMaskId,
        @DmgType,
        @FKey
        )
    END
  ELSE
   BEGIN
      update DATA_DmgData SET
       DATA_DmgData.MaskData = @MaskData
       where DATA_DmgData.DmgDataId = @DmgDataId        
    END

END
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.499</SQLVERSION>
			<RMTRACKLINK>2357</RMTRACKLINK>
			<REASON/>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER PROCEDURE [dbo].[spui_GetCounter]
 -- Add the parameters for the stored procedure here
 @CounterType smallint,
 @IdentifierAK varchar(32),
 @ReferenceTime varchar(32),
 @Counter integer output  
AS
BEGIN
declare @CounterId  smallint

 SET NOCOUNT ON;

 select @Counter = Counter ,
     @CounterId = CounterId
 from DATA_Counter (nolock)
 where CounterType = @CounterType and IdentifierAK = @IdentifierAK and
  IsNull(@ReferenceTime,'NEVER') = IsNull(ReferenceTime,'NEVER')


 if @Counter is null 
 begin
   select @Counter = 1

   insert into DATA_Counter (CounterType, IdentifierAK, ReferenceTime, Counter)
    values            (@CounterType, @IdentifierAK, IsNull(@ReferenceTime,'Never'), @Counter) 

 end
 else
 begin

   select @Counter = @Counter+1

   update DATA_Counter
   set    Counter = @Counter
   where  CounterId =  @CounterId

 end

end
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.498</SQLVERSION>
			<RMTRACKLINK>2357</RMTRACKLINK>
			<REASON>Add SP to manage the counter generation
[0] Add SP
[1] Drop Index
[2] Create new index</REASON>
			<TABLENAMES>DATA_Counter=CounterId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE PROCEDURE spui_GetCounter
 -- Add the parameters for the stored procedure here
 @CounterType smallint,
 @IdentifierAK varchar(32),
 @ReferenceTime varchar(32),
 @Counter smallint output  
AS
BEGIN
declare @CounterId  smallint

 SET NOCOUNT ON;

 select @Counter = Counter ,
     @CounterId = CounterId
 from DATA_Counter (nolock)
 where CounterType = @CounterType and IdentifierAK = @IdentifierAK and
  IsNull(@ReferenceTime,'ALL') = IsNull(ReferenceTime,'ALL')


 if @Counter is null 
 begin
   select @Counter = 1

   insert into DATA_Counter (CounterType, IdentifierAK, ReferenceTime, Counter)
    values            (@CounterType, @IdentifierAK, IsNull(@ReferenceTime,'ALL'), @Counter) 

 end
 else
 begin

   select @Counter = @Counter+1

   update DATA_Counter
   set    Counter = @Counter
   where  CounterId =  @CounterId

 end

end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'DATA_Counter') AND name = N'Counter_idx1')
  DROP INDEX Counter_idx1 ON DATA_Counter WITH ( ONLINE = OFF )
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE NONCLUSTERED INDEX [idxCounterAK] ON [dbo].[DATA_Counter] 
(
 [CounterType] ASC,
 [IdentifierAK] ASC,
 [ReferenceTime] ASC
)WITH (PAD_INDEX  = OFF, 
       STATISTICS_NORECOMPUTE  = OFF, 
       SORT_IN_TEMPDB = OFF, 
       IGNORE_DUP_KEY = OFF, 
       DROP_EXISTING = OFF, 
       ONLINE = OFF, 
       ALLOW_ROW_LOCKS  = ON, 
       ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>1.497</SQLVERSION>
			<RMTRACKLINK>2050</RMTRACKLINK>
			<REASON>SIAE_Event
[0] Add field [GroupedPerDay] Smallint Default 0 NOT NULL,
			</REASON>
			<TABLENAMES>SIAE_Event=EventId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table SIAE_Event
add GroupedPerDay Smallint Default 0 NOT NULL;
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>francescosalvi</ADDEDBY>
			<SQLVERSION>1.496</SQLVERSION>
			<RMTRACKLINK>2061</RMTRACKLINK>
			<REASON>Remove field DATA_DepositDetail.PaymentType</REASON>
			<TABLENAMES>DATA_DepositDetail=DepositDetailId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE [dbo].[DATA_DepositDetail]
DROP COLUMN [PaymentType]
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>francescosalvi</ADDEDBY>
			<SQLVERSION>1.495</SQLVERSION>
			<RMTRACKLINK>2061</RMTRACKLINK>
			<REASON>Added field DATA_DepositDetail.PaymentType</REASON>
			<TABLENAMES>DATA_DepositDetail=DepositDetailId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_DepositDetail
add PaymentType Integer NULL;
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>francescosalvi</ADDEDBY>
			<SQLVERSION>1.494</SQLVERSION>
			<RMTRACKLINK>2061</RMTRACKLINK>
			<REASON>Create table DATA_DepositVoucher</REASON>
			<TABLENAMES>DATA_DepositVoucher=DepositVoucherId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [DATA_DepositVoucher]
(
	[DepositVoucherId] Integer Identity(1,1) NOT NULL, UNIQUE ([DepositVoucherId]),
	[DepositDetailId] Integer NOT NULL,
	[VoucherId] Integer NOT NULL, UNIQUE ([VoucherId]),
Primary Key ([DepositVoucherId])
) 



				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_DepositVoucher] add  foreign key([DepositDetailId]) references [DATA_DepositDetail] ([DepositDetailId])  on update no action on delete no action
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>1.493</SQLVERSION>
			<RMTRACKLINK>2262</RMTRACKLINK>
			<REASON>DATA_Transaction
[0] Add Rounding Float Default 0 NOT NULL;
			</REASON>
			<TABLENAMES>DATA_Transaction=TransactionId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Transaction 
add Rounding Float Default 0 NOT NULL;

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>1.492</SQLVERSION>
			<RMTRACKLINK>2262</RMTRACKLINK>
			<REASON>CNF_RoundingRule 
[0-3] Remove columns not longer used
[4] Add [CustomRoundDown] Nvarchar(10) NULL,
[5] Add [CustomRoundUp] Nvarchar(10) NULL,
[6]  Add [Enabled] Smallint Default 1 NOT NULL,

			</REASON>
			<TABLENAMES>CNF_RoundingRule=RoundingRuleId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_RoundingRule 
drop column CustomDownToZero;



				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>
alter table CNF_RoundingRule 
drop column CustomUpToFive;




				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_RoundingRule 
drop column CustomDownToFive;




				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_RoundingRule 
drop column CustomUpToZero;

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_RoundingRule 
add CustomRoundDown Nvarchar(10) NULL;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_RoundingRule 
add CustomRoundUp Nvarchar(10) NULL;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_RoundingRule 
add Enabled Smallint Default 1 NOT NULL;

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>1.491</SQLVERSION>
			<RMTRACKLINK>2262</RMTRACKLINK>
			<REASON>CNF_Currency
[0-1] Add foreign key on CNF_RooundingRule</REASON>
			<TABLENAMES>CNF_Currency=CurrencyId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_Currency
add RoundingRuleId Integer NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> Alter table CNF_Currency 
 add  foreign key(RoundingRuleId) references CNF_RoundingRule (RoundingRuleId)


				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>1.490</SQLVERSION>
			<RMTRACKLINK>2262</RMTRACKLINK>
			<REASON>CNF_RoundingRule
[0] Create Table
[1] Add foreign key on CNF_System
			</REASON>
			<TABLENAMES>CNF_RoundingRule=RoundingRuleId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>
Create table [CNF_RoundingRule]
(
	[RoundingRuleId] Integer Identity(1,1) NOT NULL,
	[SystemId] Integer NOT NULL,
	[RoundingCode] Nvarchar(10) NOT NULL,
	[RoundingName] Nvarchar(50) NOT NULL,
	[RoundingType] Smallint NOT NULL,
	[RoundingGroup] Smallint NOT NULL,
	[Rounding] Integer NOT NULL,
	[Decimals] Integer NOT NULL,
	[CustomNotRounded] Nvarchar(10) NULL,
	[CustomDownToZero] Nvarchar(10) NULL,
	[CustomUpToFive] Nvarchar(10) NULL,
	[CustomDownToFive] Nvarchar(10) NULL,
	[CustomUpToZero] Nvarchar(10) NULL,
Primary Key ([RoundingRuleId])
) 



				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_RoundingRule] add  foreign key([systemId]) references [CNF_System] ([SystemId])  on update no action on delete no action
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>francescosalvi</ADDEDBY>
			<SQLVERSION>1.489</SQLVERSION>
			<RMTRACKLINK>2134</RMTRACKLINK>
			<REASON>Added a field to cnf_PaymentMethod</REASON>
			<TABLENAMES>cnf_PaymentMethod=PaymentMethodID</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_PaymentMethod
add OriginalVoid Smallint NOT NULL DEFAULT 0
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AlessandroBadii</ADDEDBY>
			<SQLVERSION>1.488</SQLVERSION>
			<RMTRACKLINK>2281</RMTRACKLINK>
			<REASON>CNF_PaymentMethod
[0] add field Code</REASON>
			<TABLENAMES>CNF_PaymentMethod=PaymentMethodId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_PaymentMethod
add Code nvarchar(10) NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AlessandroBadii</ADDEDBY>
			<SQLVERSION>1.487</SQLVERSION>
			<RMTRACKLINK>1519</RMTRACKLINK>
			<REASON>CNF_Survey
[0] ALTER COLUMN [DmgCategoryId]</REASON>
			<TABLENAMES>CNF_Survey=SurveyId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>declare @foreign_key_name nvarchar(max),
@dropstmt nvarchar(max);

--Search for the name of Foreign Key
    select @foreign_key_name = f.name
      from sys.foreign_keys AS f
inner join sys.foreign_key_columns AS fc 
        on f.object_id = fc.constraint_object_id 
     where f.parent_object_id = object_id(N'[dbo].[CNF_Survey]')
       and f.referenced_object_id = object_id(N'[dbo].[CNF_DmgCategory]')
       and COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'DmgCategoryId';

--If found delete it
if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[CNF_Survey] DROP CONSTRAINT [' + @foreign_key_name + ']';
  execute sp_executesql @dropstmt
end;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_Survey
alter column DmgCategoryId SmallInt Null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.486</SQLVERSION>
			<RMTRACKLINK>2257</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>RES_CNF_RequirementTemplateSet=RequirementTemplateSetId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>drop table  [RES_CNF_RequirementTemplateSet]


				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>        
Create table [RES_CNF_RequirementTemplateSet]
(
	[RequirementTemplateSetId] Integer NOT NULL identity(1,1),
	[RequirementTemplateMasterId] Integer NOT NULL,
	[RequirementTemplateChildId] Integer NOT NULL,
Primary Key ([RequirementTemplateSetId])
) 

Alter table [RES_CNF_RequirementTemplateSet] add constraint fkRequirementTemplateSetMaster  foreign key([RequirementTemplateMasterId]) references [RES_CNF_RequirementTemplate] ([RequirementTemplateId])
Alter table [RES_CNF_RequirementTemplateSet] add constraint fkRequirementTemplateSetChild  foreign key([RequirementTemplateChildId]) references [RES_CNF_RequirementTemplate] ([RequirementTemplateId])


				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.485</SQLVERSION>
			<RMTRACKLINK>2257</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>RES_CNF_RequirementTemplateSet=RequirementTemplateSetId
RES_CNF_Performance=PerformanceId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>
Create table [RES_CNF_RequirementTemplateSet]
(
	[RequirementTemplateSetId] Integer NOT NULL,
	[RequirementTemplateMasterId] Integer NOT NULL,
	[RequirementTemplateChildId] Integer NOT NULL,
Primary Key ([RequirementTemplateSetId])
) 

Alter table [RES_CNF_RequirementTemplateSet] add constraint fkRequirementTemplateSetMaster  foreign key([RequirementTemplateMasterId]) references [RES_CNF_RequirementTemplate] ([RequirementTemplateId])
Alter table [RES_CNF_RequirementTemplateSet] add constraint fkRequirementTemplateSetChild  foreign key([RequirementTemplateChildId]) references [RES_CNF_RequirementTemplate] ([RequirementTemplateId])




Alter table RES_CNF_Performance Add RequirementTemplateId  Integer NULL


Alter table [RES_CNF_Performance ] add constraint fkPerformance_RequirementTemplate  foreign key([RequirementTemplateId]) references [RES_CNF_RequirementTemplate] ([RequirementTemplateId])
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AlessandroBadii</ADDEDBY>
			<SQLVERSION>1.484</SQLVERSION>
			<RMTRACKLINK>1519</RMTRACKLINK>
			<REASON>CNF_MatrixCell
[0] add field ExtendedInfoTicketType</REASON>
			<TABLENAMES>CNF_MatrixCell=MatrixCellId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_MatrixCell
add ExtendedInfoTicketType Smallint NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Andrea</ADDEDBY>
			<SQLVERSION>1.483</SQLVERSION>
			<RMTRACKLINK>1930</RMTRACKLINK>
			<REASON>CNF_projection
[0] ALTER COLUMN [AccessConfigurationId]
[1] ALTER COLUMN [LocationId] int</REASON>
			<TABLENAMES>CNF_Projection=ProjectionId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE [dbo].[CNF_Projection] ALTER COLUMN [AccessConfigurationId] int
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE [dbo].[CNF_Projection] ALTER COLUMN [LocationId] int
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Andrea</ADDEDBY>
			<SQLVERSION>1.482</SQLVERSION>
			<RMTRACKLINK>1930</RMTRACKLINK>
			<REASON>CNF_Projection
[0] Create Table
[1] Add foreign key on Location
[2] Add foreign key on Admission profile</REASON>
			<TABLENAMES>CNF_Projection=ProjectionId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_Projection]
(
	[ProjectionId] Integer Identity(1,1) NOT NULL, UNIQUE ([ProjectionId]),
	[AccessConfigurationId] Integer NOT NULL,
	[LocationId] Integer NOT NULL,
	[Date] Datetime NOT NULL,
	[ProjectionValue] Integer NOT NULL,
	[Adjustment] Integer NULL,
Primary Key ([ProjectionId])
) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Projection] add  foreign key([LocationId]) references [CNF_Location] ([LocationId])  on update no action on delete no action 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Projection] add  foreign key([AccessConfigurationId]) references [ADM_AccessConfiguration] ([AccessConfigurationId])  on update no action on delete no action 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.481</SQLVERSION>
			<RMTRACKLINK>914</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>RES_ScheduleDetail=ScheduleDetailId
RES_Schedule=ScheduleId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table RES_Schedule add Quantity Integer Not Null default 1;
alter table RES_ScheduleDetail add Quantity Integer Not Null default 1;
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>1.480</SQLVERSION>
			<RMTRACKLINK>2050</RMTRACKLINK>
			<REASON>[0] Add field AdditionalCode NVarChar(8) on CNF_MatrixCell</REASON>
			<TABLENAMES>CNF_MatrixCell=MatrixCellId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE CNF_MatrixCell add AdditionalCode Nvarchar(8) NULL;

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.479</SQLVERSION>
			<RMTRACKLINK>2127</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>CNF_Scheduler=SchedulerId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Scheduler add ValidDays Varchar(100)
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.478</SQLVERSION>
			<RMTRACKLINK>2196</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>RES_CNF_MatrixCell=MatrixCellId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT> 
Create table [RES_CNF_MatrixCell]
(
	[MatrixCellId] Integer NOT NULL,
	[UseQtyInSchedule] Smallint Default 1 NOT NULL,
Primary Key ([MatrixCellId])
) 

Alter table [RES_CNF_MatrixCell] add constraint CNF_MatrixCell_CNF_RES_MatrixCell foreign key([MatrixCellId]) references [CNF_MatrixCell] ([MatrixCellId])  



				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.477</SQLVERSION>
			<RMTRACKLINK/>
			<REASON/>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>
Create table [SYS_Lock]
(
	[Context] Nchar(10) NOT NULL,
	[Key] Nchar(10) NOT NULL,
	[Holder] Nchar(10) NOT NULL,
Primary Key ([Context],[Key])
) 


Create Index [idxSysLockHolded] ON [SYS_Lock] ([Context] ,[Holder] ) 


				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AlessandroBadii</ADDEDBY>
			<SQLVERSION>1.476</SQLVERSION>
			<RMTRACKLINK>2137</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>DATA_TicketStatusLog=LogId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [DATA_TicketStatusLog]
(
	[LogId] Integer Identity NOT NULL,
	[SiteId] Integer NOT NULL,
	[WorkstationId] Integer NOT NULL,
	[TicketId] Integer NOT NULL,
	[UserId] Integer NOT NULL,
	[DateTime] Datetime NOT NULL,
	[Status] Integer NOT NULL,
Primary Key ([LogId])
)  

Alter table [DATA_TicketStatusLog] add  foreign key([UserId]) references [CNF_User] ([UserId]) 

Alter table [DATA_TicketStatusLog] add  foreign key([SiteId]) references [CNF_Site] ([SiteId]) 

Alter table [DATA_TicketStatusLog] add  foreign key([WorkstationId]) references [CNF_Workstation] ([WorkstationId])  

Alter table [DATA_TicketStatusLog] add  foreign key([TicketId]) references [DATA_Ticket] ([TicketId])     
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.475</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>CNF_SpaceStructure
[0] add field recursiveName
[1]create temp view to update DB
[2]update Db
[3] drop view</REASON>
			<TABLENAMES>CNF_SpaceStructure=SpaceStructureId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_SpaceStructure
  add RecursiveName nvarchar(200) null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>create view SpaceStructTemp
as

with Tree (Main, Child, Name)
as
(
select 
  SpaceStructureId Main,
  SpaceStructureId Child,
  convert(varchar(200), Name) Name
from CNF_SpaceStructure st
where ParentId is null

union all

select 
  Tree.Main Main,
  CNF_SpaceStructure.SpaceStructureId Child,
  convert(varchar(200), Tree.Name + ' ï¿½ '+ CNF_SpaceStructure.Name) Name
from 
  CNF_SpaceStructure inner join 
  Tree Tree on Tree.child = CNF_SpaceStructure.ParentId 
)

select 
*
from Tree
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_SpaceStructure
  set RecursiveName = 
    (  select Name 
       from SpaceStructTemp 
       where Child = CNF_SpaceStructure.SpaceStructureId
     )
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>drop view SpaceStructTemp
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>davideapicella</ADDEDBY>
			<SQLVERSION>1.474</SQLVERSION>
			<RMTRACKLINK>2186</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>DATA_Note=NoteId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Note
  alter column Note nvarchar(4000) null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.473</SQLVERSION>
			<RMTRACKLINK>1371</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>CNF_Event=EventId
CNF_Performance=PerformanceId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Performance add BlockPerformanceOnSale smallint not null default 0;
alter table CNF_Event add BlockPerformanceOnSale smallint not null default 0;

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.472</SQLVERSION>
			<RMTRACKLINK>2186</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>DATA_Note=NoteId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_NOTE
  set Note = SUBSTRING(Note, 0, 3999)

alter table DATA_Note
  alter column Note nvarchar(4000) null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.471</SQLVERSION>
			<RMTRACKLINK>2077</RMTRACKLINK>
			<REASON/>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE view [dbo].[vwStatisticalGroup]
as
select 
Main.StatisticalGroupId MainId,
cschild.StatisticalGroupId ChildId,
Main.StatisticalGroupDescription,
cschild.StatisticalGroupDescription Child,
Main.Level MainLevel,
cschild.Level ChildLevel,
cschild.Level-Main.Level RelLevel,
Main.Position MainPosition,
cschild.Position ChildPosition,
cschild.Position-Main.Position RelPosition

from
(
select 
csg.Level,
csg.Position,
csg.StatisticalGroupId,
csg.Position StartPos,
csg.StatisticalGroupDescription,
Min(csgns.Position) EndPos
from
cnf_statisticalgroup csg left join
cnf_statisticalgroup csgns on csgns.Level &lt;= csg.Level and csgns.Position&gt;csg.Position
group by
csg.Level,
csg.Position,
csg.StatisticalGroupDescription,
csg.StatisticalGroupId,
csg.Position
union
select
0,
0,
null,
0,
'All',
null
) Main left join
( select * from cnf_statisticalgroup 
 union 
 select
  0,'','All',null,0,0) as cschild on cschild.Position &gt;= Main.StartPos and cschild.Position &lt;= IsNull(EndPos-1, cschild.Position)


				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.470</SQLVERSION>
			<RMTRACKLINK>1744</RMTRACKLINK>
			<REASON>ADM_AccessPoint
[0] add field FreeExitTime</REASON>
			<TABLENAMES>ADM_AccessPoint=WorkstationId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table ADM_AccessPoint 
  add FreeExitTime DateTime
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>davideapicella</ADDEDBY>
			<SQLVERSION>1.469</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>DATA_Voucher
[0] Added MaxTickets</REASON>
			<TABLENAMES>DATA_Voucher=VoucherId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table DATA_Voucher 
add MaxTickets Smallint NULL DEFAULT NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>davideapicella</ADDEDBY>
			<SQLVERSION>1.468</SQLVERSION>
			<RMTRACKLINK>1320</RMTRACKLINK>
			<REASON>DATA_Account
[0] added OfflineAccountAK</REASON>
			<TABLENAMES>DATA_Account=AccountId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table DATA_Account 
add OfflineAccountAK Varchar(32) NULL DEFAULT NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.467</SQLVERSION>
			<RMTRACKLINK>2029</RMTRACKLINK>
			<REASON>DATA_Ticket
[0] remove field saleNote</REASON>
			<TABLENAMES>DATA_Ticket=ticketId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table DATA_Ticket
  drop column SaleNote
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AlessandroBadii</ADDEDBY>
			<SQLVERSION>1.466</SQLVERSION>
			<RMTRACKLINK>2087</RMTRACKLINK>
			<REASON>DATA_Sale
[0] Add RefAccountId</REASON>
			<TABLENAMES>DATA_Sale=SaleId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table DATA_Sale
  add RefAccountId Integer null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.465</SQLVERSION>
			<RMTRACKLINK>1579</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>DATA_PaymentCredit=PaymentId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_PaymentCredit add [AmountDisc] Float default 0 NULL;
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.464</SQLVERSION>
			<RMTRACKLINK>1402</RMTRACKLINK>
			<REASON>[ADM_AccessPoint]
[0] add field ignoreAntiPassBack</REASON>
			<TABLENAMES>ADM_AccessPoint=WorkstationId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table ADM_AccessPoint
  add IgnoreAntipassBack smallInt null default 0
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.463</SQLVERSION>
			<RMTRACKLINK>1579</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>DATA_IncentiveTicketUsage=IncentiveTicketUsageId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>   
Create table [DATA_IncentiveTicketUsage]
(
	[IncentiveTicketUsageId] Integer Identity(1,1) NOT NULL,
	[SaleItemId] Integer NOT NULL,
	[IncentiveTicketId] Integer NOT NULL,
	[Quantity] Integer NULL,
Primary Key ([IncentiveTicketUsageId])
) 

Alter table [DATA_IncentiveTicketUsage] add constraint FK_IncentiveTicketUsage_SaleItem foreign key([SaleItemId]) references [DATA_SaleItem] ([SaleItemId])


Alter table [DATA_IncentiveTicketUsage] add constraint FK_IncentiveTicketUsage_IncentiveTicket foreign key([IncentiveTicketId]) references [CNF_IncentiveTicket] ([IncentiveTicketId]) 
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.462</SQLVERSION>
			<RMTRACKLINK>1579</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>CNF_IncentiveTicket=IncentiveTicketId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>    
Create table [CNF_IncentiveTicket]
(
	[IncentiveTicketId] Integer Identity(1,1) NOT NULL,
	[AccountId] Integer NOT NULL,
	[MatrixCellId] Integer NOT NULL,
	[Quantity] Integer NOT NULL,
	[UsedQuantity] Integer default 0 NOT NULL,
	[ValidFrom] Datetime NULL,
	[ValidTo] Datetime NULL,
Primary Key ([IncentiveTicketId]))

Alter table [CNF_IncentiveTicket] add constraint FK_IncetiveTicket_MatrixCell foreign key([MatrixCellId]) references [CNF_MatrixCell] ([MatrixCellId])

Alter table [CNF_IncentiveTicket] add constraint FK_IncetiveTicket_Account foreign key([AccountId]) references [DATA_Account] ([AccountId])


				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AlessandroBadii</ADDEDBY>
			<SQLVERSION>1.461</SQLVERSION>
			<RMTRACKLINK>2029</RMTRACKLINK>
			<REASON>DATA_Ticket
[0] Add SaleNote</REASON>
			<TABLENAMES>DATA_Ticket=TicketId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table DATA_Ticket
  add SaleNote nvarchar(300) null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.460</SQLVERSION>
			<RMTRACKLINK>1974</RMTRACKLINK>
			<REASON>DATA_MediaIdentifierBlackList
[0] add field EventId
[1] add FK on CNF_Event</REASON>
			<TABLENAMES>DATA_MediaIdentifierBlackList=MediaBlackListId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table DATA_MediaIdentifierBlackList
  add EventId integer null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> Alter table DATA_MediaIdentifierBlackList 
 add  foreign key(EventId) references CNF_Event (EventId) 
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.459</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>[CNF_MatrixCell]
0: add fielf ForceSingleAccount</REASON>
			<TABLENAMES>CNF_MatrixCell=MatrixCellId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_MAtrixCell
  add ForceSingleAccount Smallint NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.458</SQLVERSION>
			<RMTRACKLINK>914</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>RES_Data_Transaction=ResDataTransactionId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [RES_Data_Transaction]
(
	[ResDataTransactionId] Integer Identity(1,1) NOT NULL,
	[PerformanceId] Integer NOT NULL,
	[TransactionId] Integer NULL,
	[UserId] Integer NULL,
	[WorkstationId] Integer NOT NULL,
Primary Key ([ResDataTransactionId])
) 

Alter table [RES_Data_Transaction] add constraint RES_Data_Transaction_Data_Transaction foreign key([TransactionId]) references [DATA_Transaction] ([TransactionId]) 

Alter table [RES_Data_Transaction] add constraint RES_Data_Transaction_WorkStation foreign key([WorkstationId]) references [CNF_Workstation] ([WorkstationId])

Alter table [RES_Data_Transaction] add constraint RES_Data_Transaction_Performance foreign key([PerformanceId]) references [CNF_Performance] ([PerformanceId]) 


DROP PROCEDURE [dbo].[sp_ui_RES_Data_Sale_delete]
DROP PROCEDURE [dbo].[sp_ui_RES_Data_Sale_insert]
DROP PROCEDURE [dbo].[sp_ui_RES_Data_Sale_update]


Drop Table RES_Data_Sale
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.457</SQLVERSION>
			<RMTRACKLINK>914</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>RES_Data_Sale=ResDataSaleId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT> Create table [RES_Data_Sale]
(
	[ResDataSaleId] Integer Identity(1,1) NOT NULL,
	[PerformanceId] Integer NOT NULL,
	[SaleId] Integer NULL,
	[UserId] Integer NULL,
	[WorkstationId] Integer NOT NULL,
Primary Key ([ResDataSaleId])
) 

Alter table [RES_Data_Sale] add constraint RES_Data_Sale_Data_Sale foreign key([SaleId]) references [DATA_Sale] ([SaleId]) 

Alter table [RES_Data_Sale] add constraint RES_Data_Sale_WorkStation foreign key([WorkstationId]) references [CNF_Workstation] ([WorkstationId])

Alter table [RES_Data_Sale] add constraint RES_Data_Sale_Performance foreign key([PerformanceId]) references [CNF_Performance] ([PerformanceId]) 


				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.456</SQLVERSION>
			<RMTRACKLINK>1079</RMTRACKLINK>
			<REASON>CNF_SaleLimit
[0] remove Index
[1] add field AccountId
[2] update AccountId
[3] add FK on DATA_Account
[4] remove Field EntyTable
[5] remove Field EntityId

			</REASON>
			<TABLENAMES>CNF_SaleLimit=SaleLimitId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>drop Index TicketAccount
  on CNF_SaleLimit
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_SaleLimit
  Add AccountId int null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_SaleLimit
  set AccountId=EntityId
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_SaleLimit 
  add foreign key(AccountId) references DATA_Account (AccountId)  on update no action on delete no action 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_SaleLimit
  drop column EntityTable
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_SaleLimit
  drop column EntityId
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_SaleLimit
  alter column AccountId int not null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>1.455</SQLVERSION>
			<RMTRACKLINK>1933</RMTRACKLINK>
			<REASON>CNF_StatisticalGroup
[0] Add field ParentId  Integer
     Add field Position  Integer Not null
     Add field Level  Integer Not null
[1] Add self foreign key 
			</REASON>
			<TABLENAMES>CNF_StatisticalGroup=StatisticalGroupId
			</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_StatisticalGroup add ParentId Integer NULL;

alter table CNF_StatisticalGroup add Position Integer NOT NULL;

alter table CNF_StatisticalGroup add Level Integer NOT NULL;




				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_StatisticalGroup] add  foreign key([ParentId]) references [CNF_StatisticalGroup] ([StatisticalGroupId])   


				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AlessandroBadii</ADDEDBY>
			<SQLVERSION>1.454</SQLVERSION>
			<RMTRACKLINK>914</RMTRACKLINK>
			<REASON>RES_CNF_Resource
[0] Add Color
RES_CNF_ResourceType
[1] Add Color</REASON>
			<TABLENAMES>RES_CNF_Resource=ResourceId
RES_CNF_ResourceType=ResourceTypeId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table RES_CNF_Resource
  Add Color nvarchar(100) null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table RES_CNF_ResourceType
  Add Color nvarchar(100) null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AlessandroBadii</ADDEDBY>
			<SQLVERSION>1.453</SQLVERSION>
			<RMTRACKLINK>1746</RMTRACKLINK>
			<REASON>CNF_DocTemplate
[0] Add DirectPrint</REASON>
			<TABLENAMES>CNF_DocTemplate=DocTemplateId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_DocTemplate
  Add DirectPrint nvarchar(300) null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>1.452</SQLVERSION>
			<RMTRACKLINK>1933</RMTRACKLINK>
			<REASON>CNF_StatisticalGroup
CNF_StatisticalGroupValidity
[0] Create Table CNF_StatisticalGroup
[1] Create Table CNF_StatisticalGroupValidity
[2] Add foreign key for CNF_StatisticalGroupValidity on CNF_MatrixCell
[3] Add foreign key for CNF_StatisticalGroupValidity on CNF_StatisticalGroup
			</REASON>
			<TABLENAMES>CNF_StatisticalGroup=StatisticalGroupId
CNF_StatisticalGroupValidity=StatisticalGroupValidityId
			</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_StatisticalGroup]
(
	[StatisticalGroupId] Integer Identity(1,1) NOT NULL, UNIQUE ([StatisticalGroupId]),
	[StatisticalGroupCode] Varchar(10) NOT NULL,
	[StatisticalGroupDescription] Nvarchar(100) NULL,
Primary Key ([StatisticalGroupId])
) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_StatisticalGroupValidity]
(
	[StatisticalGroupValidityId] Integer Identity(1,1) NOT NULL, UNIQUE ([StatisticalGroupValidityId]),
	[StatisticalGroupId] Integer NOT NULL,
	[MatrixCellId] Integer NOT NULL,
Primary Key ([StatisticalGroupValidityId])
)



				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_StatisticalGroupValidity] add  foreign key([StatisticalGroupId]) references [CNF_StatisticalGroup] ([StatisticalGroupId])





				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_StatisticalGroupValidity] add  foreign key([MatrixCellId]) references [CNF_MatrixCell] ([MatrixCellId])

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AlessandroBadii</ADDEDBY>
			<SQLVERSION>1.451</SQLVERSION>
			<RMTRACKLINK>2025</RMTRACKLINK>
			<REASON>CNF_CostCenter
[0] Update CostCenterDescription</REASON>
			<TABLENAMES>CNF_CostCenter=CostCenterId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_CostCenter
alter column CostCenterDescription nvarchar(100) null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>davideapicella</ADDEDBY>
			<SQLVERSION>1.450</SQLVERSION>
			<RMTRACKLINK>791</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>MSG_CNF_Message=MessageId
MSG_CNF_Attachment=AttachmentId
MSG_CNF_Message2Entity=Message2EntityId
MSG_DATA_Thread=ThreadId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [MSG_DATA_Thread] drop constraint Thread_Message2EntityId
Drop Index [IdxMSG_DATA_Thread_Message2EntityId] ON [MSG_DATA_Thread]
Alter table [MSG_DATA_Thread] drop column Message2EntityId
Alter table [MSG_DATA_Thread] drop column ReferenceThreadId

Create Index [IdxMSG_CNF_Message_MessageId] ON [MSG_CNF_Message] ([MessageId])
Create Index [IdxMSG_CNF_Message_ValidFrom] ON [MSG_CNF_Message] ([ValidFrom])
Create Index [IdxMSG_CNF_Message_ValidTo] ON [MSG_CNF_Message] ([ValidTo])
Create Index [IdxMSG_CNF_Message_MessageStatus] ON [MSG_CNF_Message] ([MessageStatus])
Create Index [IdxMSG_CNF_Attachment_MessageId] ON [MSG_CNF_Attachment] ([MessageId])
Create Index [IdxMSG_CNF_Message2Entity_MessageId] ON [MSG_CNF_Message2Entity] ([MessageId])
Create Index [IdxMSG_CNF_Message2Entity_EntityType] ON [MSG_CNF_Message2Entity] ([EntityType])
Create Index [IdxMSG_CNF_Message2Entity_EntityId] ON [MSG_CNF_Message2Entity] ([EntityId])
Create Index [IdxMSG_DATA_Thread_UserId] ON [MSG_DATA_Thread] ([UserId])
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.449</SQLVERSION>
			<RMTRACKLINK>2018</RMTRACKLINK>
			<REASON>DATA_Account
[0] remove Index 
[1]Field Displayname is now nvarchar
[2] Field Address1 is now nvarchar
[3] Field CompanyName is now nvarchar
[4]reAdd Index</REASON>
			<TABLENAMES>DATA_Account=AccountId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>drop Index IDX_Account_DisplayName
  on DATA_Account
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Account
  alter column DisplayName nVarChar(100) null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Account
  alter column Address1 nVarChar(100) null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Account
  alter column CompanyName nVarChar(100) null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create Index IDX_Account_DisplayName 
  on DATA_Account (DisplayName) 
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.448</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>[0] Add field FlatSheet null
[1] set value
[2] alter field as not null</REASON>
			<TABLENAMES>CNF_MatrixSheet=MatrixSheetId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_MatrixSheet
  add FlatSheet smallInt null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_MatrixSheet
  set FlatSheet = 0 where ProductType &lt; 2
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_MatrixSheet
  set FlatSheet = 1 where ProductType &gt;= 2
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> Alter table CNF_MAtrixSheet  
   alter column FlatSheet smallint not null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AlessandroBadii</ADDEDBY>
			<SQLVERSION>1.447</SQLVERSION>
			<RMTRACKLINK>1798</RMTRACKLINK>
			<REASON>[0] Add field StartCommValidity
[1] Add field EndCommValidity</REASON>
			<TABLENAMES>CNF_Commission2Account=Commission2AccountId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_Commission2Account
  Add StartCommValidity DateTime null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_Commission2Account
  Add EndCommValidity DateTime null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.446</SQLVERSION>
			<RMTRACKLINK>914</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>RES_ScheduleDetail=ScheduleDetailId</TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.445</SQLVERSION>
			<RMTRACKLINK>914</RMTRACKLINK>
			<REASON/>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[RequirementTemplateItem_Requirement]') AND parent_object_id = OBJECT_ID(N'[dbo].[RES_CNF_RequirementTemplateItem]'))
ALTER TABLE [dbo].[RES_CNF_RequirementTemplateItem] DROP CONSTRAINT [RequirementTemplateItem_Requirement]


IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[RequirementTemplateItem_RequirementTemplate]') AND parent_object_id = OBJECT_ID(N'[dbo].[RES_CNF_RequirementTemplateItem]'))
ALTER TABLE [dbo].[RES_CNF_RequirementTemplateItem] DROP CONSTRAINT [RequirementTemplateItem_RequirementTemplate]


IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_RES_ScheduleDetail_RequirementTemplateItem]') AND parent_object_id = OBJECT_ID(N'[dbo].[RES_ScheduleDetail]'))
ALTER TABLE [dbo].[RES_ScheduleDetail] DROP CONSTRAINT [FK_RES_ScheduleDetail_RequirementTemplateItem]

IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_RES_ScheduleDetail_RequirementTemplateItem]') AND parent_object_id = OBJECT_ID(N'[dbo].[RES_ScheduleDetail]'))
ALTER TABLE [dbo].[RES_ScheduleDetail] DROP CONSTRAINT [FK_RES_ScheduleDetail_RequirementTemplateItem]


IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[RequirementTemplateItem_Requirement]') AND parent_object_id = OBJECT_ID(N'[dbo].[RES_CNF_RequirementTemplateItem]'))
ALTER TABLE [dbo].[RES_CNF_RequirementTemplateItem] DROP CONSTRAINT [RequirementTemplateItem_Requirement]

IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[RequirementTemplateItem_RequirementTemplate]') AND parent_object_id = OBJECT_ID(N'[dbo].[RES_CNF_RequirementTemplateItem]'))
ALTER TABLE [dbo].[RES_CNF_RequirementTemplateItem] DROP CONSTRAINT [RequirementTemplateItem_RequirementTemplate]

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RES_CNF_RequirementTemplateItem]') AND type in (N'U'))
DROP TABLE [dbo].[RES_CNF_RequirementTemplateItem]





IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_ui_RES_CNF_RequirementTemplateItem_insert]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_ui_RES_CNF_RequirementTemplateItem_insert]

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_ui_RES_CNF_RequirementTemplateItem_update]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_ui_RES_CNF_RequirementTemplateItem_update]

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_ui_RES_CNF_RequirementTemplateItem_delete]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_ui_RES_CNF_RequirementTemplateItem_delete]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [RES_CNF_RequirementTemplateItem]
(
	[RequirementTemplateItemId] Integer Identity(1,1) NOT NULL,
	[RequirementTemplateId] Integer NOT NULL,
	[RequirementId] Integer NOT NULL,
	[QtyFromSale] Smallint Default 0 NULL,
	[Quantity] Integer NULL,
Primary Key ([RequirementTemplateItemId])
) 


Alter table [RES_CNF_RequirementTemplateItem] add constraint FK_RequirementTemplateItem_Requirement foreign key ([RequirementId]) references [RES_CNF_Requirement] ([RequirementId]);
Alter table [RES_CNF_RequirementTemplateItem] add constraint FK_RequirementTemplateItem_RequirementTemplate foreign key ([RequirementTemplateId]) references [RES_CNF_RequirementTemplate] ([RequirementTemplateId]);

Alter Table RES_ScheduleDetail drop column [RequirementTemplateTemId];

Alter Table RES_ScheduleDetail add [RequirementTemplateItemId] integer null;

Alter table [RES_ScheduleDetail] add constraint FK_RES_ScheduleDetail_RequirementTemplateItem foreign key([RequirementTemplateItemId]) references [RES_CNF_RequirementTemplateItem] ([RequirementTemplateItemId]);
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>	create procedure [dbo].[sp_ui_RES_CNF_RequirementTemplateItem_insert]	
		@RequirementTemplateItemId Integer output ,
		@RequirementTemplateId Integer,
		@RequirementId Integer,
		@QtyFromSale SmallInt,
		@Quantity Integer
	as
	begin
		insert into RES_CNF_RequirementTemplateItem
			(RequirementTemplateId, RequirementId, QtyFromSale, Quantity)
		values 	
			(@RequirementTemplateId,@RequirementId,@QtyFromSale,@Quantity)


		select @RequirementTemplateItemId= SCOPE_IDENTITY() 


	end;




				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> create procedure [dbo].[sp_ui_RES_CNF_RequirementTemplateItem_update]	
		@RequirementTemplateItemId Integer,
		@RequirementTemplateId Integer,
		@RequirementId Integer,
		@QtyFromSale SmallInt,
		@Quantity Integer
	as
	begin
		update	RES_CNF_RequirementTemplateItem
		set	RequirementTemplateId=@RequirementTemplateId,
			RequirementId=@RequirementId,
			QtyFromSale=@QtyFromSale,
			Quantity=@Quantity
		where	RequirementTemplateItemId=@RequirementTemplateItemId

	end;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>        	create procedure [dbo].[sp_ui_RES_CNF_RequirementTemplateItem_delete]	
		@RequirementTemplateItemId Integer	
	as
	begin
		delete from	RES_CNF_RequirementTemplateItem
		where	RequirementTemplateItemId=@RequirementTemplateItemId

	end;
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>davideapicella</ADDEDBY>
			<SQLVERSION>1.444</SQLVERSION>
			<RMTRACKLINK>791</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>MSG_CNF_Message=MessageId
MSG_CNF_Attachment=AttachmentId
MSG_CNF_Message2Entity=Message2EntityId
MSG_DATA_Thread=ThreadId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table MSG_CNF_Message2Entity ALTER COLUMN EntityId Int NOT NULL

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table MSG_CNF_Message ADD ShowType SmallInt NOT NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE TABLE [MSG_DATA_Thread](
	[ThreadId] [int] IDENTITY(1,1) NOT NULL,
	[MessageId] [int] NOT NULL,
	[SystemId] [int] NOT NULL,
	[WorkstationId] [int] NOT NULL,
	[UserId] [int] NOT NULL,
	[Message2EntityId] [int] NOT NULL, 
	[CreationDate] [datetime] NOT NULL,
	[ConfirmStatus] [SmallInt] NOT NULL,
	[MessageText] [ntext] NOT NULL,
	[ReferenceThreadId] [int] NULL,
Primary Key ([ThreadId])
)
Alter table [MSG_DATA_Thread] add constraint Thread_MessageId foreign key([MessageId]) references [MSG_CNF_Message] ([MessageId])
Alter table [MSG_DATA_Thread] add constraint Thread_Message2EntityId foreign key([Message2EntityId]) references [MSG_CNF_Message2Entity] ([Message2EntityId])

Create Index [IdxMSG_DATA_Thread_MessageId] ON [MSG_DATA_Thread] ([MessageId])
Create Index [IdxMSG_DATA_Thread_Message2EntityId] ON [MSG_DATA_Thread] ([Message2EntityId])
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.443</SQLVERSION>
			<RMTRACKLINK>914</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>RES_CNF_ResourceType=ResourceTypeId
RES_CNF_ResourceType_Requirement=ResourceTypeRequirementId
RES_CNF_ResourceRequirement=ResourceRequirementId
			</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>
alter table RES_CNF_ResourceType drop column AllocationMode;

alter table RES_CNF_ResourceType_Requirement add  AllocationMode integer not null default 0;
alter table RES_CNF_ResourceRequirement add  AllocationMode integer not null default 0;
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>ALollobrigida</ADDEDBY>
			<SQLVERSION>1.442</SQLVERSION>
			<RMTRACKLINK>1806</RMTRACKLINK>
			<REASON>STOCK_CNF_ProductCategory
[0] Add field ExternalCode 
[1] Add index on table STOCK_CNF_ProductCategory  &lt;IdxSTOCK_CNF_ProductCategoryExternalCode&gt; on ExternalCode</REASON>
			<TABLENAMES>STOCK_CNF_ProductCategory=CategoryId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>  Alter Table STOCK_CNF_ProductCategory add ExternalCode Nvarchar(10) NULL

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create Index [IdxSTOCK_CNF_ProductCategory_ExternalCode] ON [STOCK_CNF_ProductCategory] ([ExternalCode] )  

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.441</SQLVERSION>
			<RMTRACKLINK>914</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>RES_CNF_Event=EventId
RES_CNF_Performance=PerformanceId
RES_Schedule=ScheduleId
RES_ScheduleDetail=ScheduleDetailId
RES_ResourceCalendar=ResourceCalendarId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>
Create table [RES_CNF_Event]
(
	[EventId] Integer NOT NULL,
	[AllocateResource] Smallint NOT NULL,
	[AllocateResourceOnSale] Smallint NOT NULL,
	[SellWithoutResource] Smallint NOT NULL,
	[SellWithoutResourceLimit] Integer NULL,
	[RequirementTemplateId] Integer NULL,
Primary Key ([EventId])
);

Create table [RES_CNF_Performance]
(
	[PerformanceId] Integer NOT NULL,
	[Allocated] Smallint NOT NULL,
Primary Key ([PerformanceId])
)


Create table [RES_Schedule]
(
	[ScheduleId] Integer Identity(1,1) NOT NULL,
	[ResourceId] Integer NOT NULL,
	[Note] Nvarchar(100) NULL,
	[Date] Datetime NOT NULL,
	[Duration] Integer NOT NULL,
	[FromTime] Datetime NOT NULL,
Primary Key ([ScheduleId])
) 

Create table [RES_ScheduleDetail]
(
	[ScheduleDetailId] Integer Identity(1,1) NOT NULL,
	[ScheduleId] Integer NOT NULL,
	[PerformanceId] Integer NOT NULL,
	[RequirementTemplateTemId] Integer NOT NULL,
	[RequirementId] Integer NOT NULL,
Primary Key ([ScheduleDetailId])
)


Create table [RES_ResourceCalendar]
(
	[ResourceCalendarId] Integer Identity(1,1) NOT NULL,
	[ResourceId] Integer NOT NULL,
	[CalendarId] Integer NULL,
	[Date] Datetime NOT NULL,
Primary Key ([ResourceCalendarId])
) 


Create UNIQUE Index [idxResourceCalendarUnique] ON [RES_ResourceCalendar] ([ResourceId] ,[Date] ) 


Create table [RES_ResourceCalendar_TimeFrame]
(
	[ResourceCalendarTimeFrameId] Integer Identity(1,1) NOT NULL,
	[ResourceCalendarId] Integer NOT NULL,
	[FromTime] Datetime NOT NULL,
	[Duration] Integer NOT NULL,
	[Note] Nvarchar(100) NULL,
Primary Key ([ResourceCalendarTimeFrameId])
) 

Alter table [RES_CNF_Event] add constraint FK_RES_CNF_Event_CNF_Event foreign key([EventId]) references [CNF_Event] ([EventId]) ;
Alter table [RES_CNF_Event] add constraint FK_RES_CNF_Event_RequirementTempale foreign key([RequirementTemplateId]) references [RES_CNF_RequirementTemplate] ([RequirementTemplateId]);

Alter table [RES_CNF_Performance] add constraint FK_RES_CNF_Performance_CNF_Performance  foreign key([PerformanceId]) references [CNF_Performance] ([PerformanceId]) ;


Alter table [RES_Schedule] add constraint FK_RES_Schedule_Resource foreign key([ResourceId]) references [RES_CNF_Resource] ([ResourceId]);


Alter table [RES_ScheduleDetail] add constraint FK_RES_ScheduleDetail_Schedule foreign key([ScheduleId]) references [RES_Schedule] ([ScheduleId]);
Alter table [RES_ScheduleDetail] add constraint FK_RES_ScheduleDetail_Requirement foreign key([RequirementId]) references [RES_CNF_Requirement] ([RequirementId]);
Alter table [RES_ScheduleDetail] add constraint FK_RES_ScheduleDetail_RequirementTemplateItem foreign key([RequirementTemplateTemId]) references [RES_CNF_RequirementTemplateItem] ([RequirementTemplateTemId]);
Alter table [RES_ScheduleDetail] add constraint FK_RES_ScheduleDetail_Performance foreign key([PerformanceId]) references [RES_CNF_Performance] ([PerformanceId]);




Alter table [RES_ResourceCalendar_TimeFrame] add constraint FK_RES_ResourceCalendar_TimeFrame_ResourceCalendar  foreign key([ResourceCalendarId]) references [RES_ResourceCalendar] ([ResourceCalendarId]);
Alter table [RES_ResourceCalendar] add constraint FK_RES_ResourceCalendar_Resource foreign key([ResourceId]) references [RES_CNF_Resource] ([ResourceId]); 
Alter table [RES_ResourceCalendar] add constraint FK_RES_ResourceCalendar_Celandar foreign key([CalendarId]) references [CNF_Calendar] ([CalendarId]);

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>1.440</SQLVERSION>
			<RMTRACKLINK>1973</RMTRACKLINK>
			<REASON>Add index on table CNF_SpaceStructure - Field PerformanceId</REASON>
			<TABLENAMES>CNF_SpaceStructure=SpaceStructureId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create Index [IdxCNF_SpaceStructure_PerformanceId] ON [CNF_SpaceStructure] ([PerformanceId] ) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AlessandroBadii</ADDEDBY>
			<SQLVERSION>1.439</SQLVERSION>
			<RMTRACKLINK>1752</RMTRACKLINK>
			<REASON>[0] Add field TabOrder smallint null</REASON>
			<TABLENAMES>CNF_DataMask=DataMaskId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE CNF_DataMask add TabOrder smallint null;
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>1.438</SQLVERSION>
			<RMTRACKLINK>1929</RMTRACKLINK>
			<REASON>[0] Add field RenewType smallint not null</REASON>
			<TABLENAMES>CNF_MatrixCell=MatrixCellId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE CNF_MatrixCell add RenewType smallint not null default 0;
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.437</SQLVERSION>
			<RMTRACKLINK>914</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>CNF_CalendarTimeFrame=TimeFrameId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter Table CNF_CalendarTimeFrame add Color Varchar(10) not null;
Alter Table CNF_CalendarTimeFrame add Category NVarchar(50) not null;
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AlessandroBadii</ADDEDBY>
			<SQLVERSION>1.436</SQLVERSION>
			<RMTRACKLINK>1928</RMTRACKLINK>
			<REASON>CNF_Promotion
[0] Update Code</REASON>
			<TABLENAMES>CNF_Promotion=PromotionId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_Promotion
alter column Code nvarchar(40) null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.435</SQLVERSION>
			<RMTRACKLINK>1932</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>STOCK_Movement=MovementId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table STOCK_Movement alter column Value float;
alter table STOCK_Movement alter column TotValue float;
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.434</SQLVERSION>
			<RMTRACKLINK>914</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>CNF_CalendarValidity=CalendarValidityId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE CNF_CalendarValidity add TimeFrameId int null;

Alter table [CNF_CalendarValidity] add constraint FK_CNF_CalendarValidity_TimeFrame  foreign key([TimeFrameId]) references [CNF_CalendarTimeFrame] ([TimeFrameId]); 



				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.433</SQLVERSION>
			<RMTRACKLINK>914</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>CNF_CalendarTimeFrame=TimeFrameId
CNF_CalendarTimeFrameItem=TimeFrameItemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>DROP PROCEDURE [dbo].[sp_ui_RES_CNF_CalendarTimeFrame_delete]
DROP PROCEDURE [dbo].[sp_ui_RES_CNF_CalendarTimeFrame_update]
DROP PROCEDURE [dbo].[sp_ui_RES_CNF_CalendarTimeFrame_insert]
DROP PROCEDURE [dbo].[sp_ui_RES_CNF_CalendarTimeFrameItem_delete]
DROP PROCEDURE [dbo].[sp_ui_RES_CNF_CalendarTimeFrameItem_update]
DROP PROCEDURE [dbo].[sp_ui_RES_CNF_CalendarTimeFrameItem_insert]


exec SP_RENAME 'RES_CNF_CalendarTimeFrame', 'CNF_CalendarTimeFrame'
exec SP_RENAME 'RES_CNF_CalendarTimeFrameItem', 'CNF_CalendarTimeFrameItem'


				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.432</SQLVERSION>
			<RMTRACKLINK>914</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>CNF_Calendar=CalendarId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter Table CNF_Calendar drop column  CalendarType;

Alter Table CNF_Calendar add TimeFrame SmallInt null;

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AlessandroBadii</ADDEDBY>
			<SQLVERSION>1.431</SQLVERSION>
			<RMTRACKLINK>1947</RMTRACKLINK>
			<REASON>CNF_Performance
[0] Add PerformanceName</REASON>
			<TABLENAMES>CNF_Performance=PerformanceId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_Performance
  add PerformanceName nvarchar(100) null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>1.430</SQLVERSION>
			<RMTRACKLINK>905</RMTRACKLINK>
			<REASON>[0] Update Tables: CNF_SpaceStructure - CNF_SeatCategory - CNF_EnvelopeCapacity - CNF_Seat
[1] CNF_SpaceStructure: Add FK on CNF_Performance and Update Data for performance already present
[2] CNF_EnvelopeCapacity: Add FK on CNF_SpaceStructure and Update field of new SpaceStructureId prvious created 
[3] CNF_SeatCategory:  Add FK on CNF_Performance and Update Data for performance already present
[4] CNF_EnvelopeCapacity: Add FK on CNF_SeatCategory and Update field of new SeatCategoryId prvious created 
[5] CNF_Seat: Add FK on CNF_SpaceStructure and Update field of new SpaceStructureId prvious created 
[6] CNF_Seat: Add FK on CNF_SeatCategory and Update field of new SeatCategoryId prvious created  
[7] New Table SEAT_CNF_SpaceStructureSeat and Fill Data for Structure created from Seat Desiger
[8] CNF_Seat - Remove FK on CNF_Capacity
[9] CNF_EnvelopeCapacity - Remove FK on CNF_Capacity
[10] CNF_Envelope - Remove FK on ADM_AccessConfiguration
[11] DATA_CapacityCounter - Remove FK on CNF_Capacity (table no longer used)
[12] CNF_Capacity - Remove FK on CNF_Performance
[13] CNF_Capacity - Remove FK on CNF_SpaceStructure
[14] CNF_Capacity - Remove FK on CNF_SeatCategory
[15] CNF_EnvelopeCapacity - Remove IDX for CNF_Capacity/CNF_Envelope
[16] CNF_EnvelopeCapacity - Remove "not Null" field CapacityId
[17] CNF_Seat - Remove "not Null" field CapacityId
			</REASON>
			<TABLENAMES>CNF_SpaceStructure=SpaceStructureId
CNF_SeatCategory=SeatCategoryId
CNF_EnvelopeCapacity=EnvelopeCapacityId
CNF_Seat=SeatId
SEAT_CNF_SpaceStructureSeat=SpaceStructureSeatId
			</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>-- SCRIPT 0

-- CNF_SpaceStructure - Add field ExternalReference
Alter table CNF_SpaceStructure add  ExternalReference Char(10) NULL;

-- CNF_SeatCategory - Add field ExternalReference
Alter table CNF_SeatCategory add  ExternalReference Char(10) NULL;

-- CNF_SpaceStructure - Add field PerformanceId
Alter table CNF_SpaceStructure add  PerformanceId integer;

-- CNF_SpaceStructure - Create a temporary field for Old SpaceStructureId
Alter table CNF_SpaceStructure add Temp_SpaceStructureId integer;

-- CNF_EnvelopeCapacity - Add field SpaceStructureId
Alter table CNF_EnvelopeCapacity add  SpaceStructureId integer;

-- CNF_SeatCategory - Add field PerformanceId
Alter table CNF_SeatCategory add  PerformanceId integer;

-- CNF_SeatCategory - Create a temporary field for Old SeatCategoryId
Alter table CNF_SeatCategory add Temp_SeatCategoryId integer;

-- CNF_EnvelopeCapacity - Add field SeatCategoryId
Alter table CNF_EnvelopeCapacity add SeatCategoryId integer;

-- CNF_Seat - Add field SpaceStructureId
Alter table CNF_Seat add SpaceStructureId integer;

-- CNF_Seat - Add field SeatCategoryId
Alter table CNF_Seat add SeatCategoryId integer;

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>-- SCRIPT 1


-- CNF_SpaceStructure - Add FK (nullable) on CNF_Performance
-- =========================================================


------------
-- CNF_SpaceStructure - Insert record in CNF_Capacity related to SpaceStructure
------------


-- CNF_SpaceStructure - Insert record related to CNF_Capacity


with CapacitySpace (TMP_SSId, TMP_PerfId) 
  as (
    SELECT distinct 
      SpaceStructureId,
      PerformanceId
    FROM CNF_Capacity
    WHERE PerformanceId is not null   
    GROUP BY PerformanceId, SpaceStructureId
   )


insert into CNF_SpaceStructure

  (
       AccessConfigurationId
      ,PriorityOrder
      ,SpaceStructureType
      ,Enabled
      ,IsSeat
      ,Temp_SpaceStructureId
      ,PerformanceId
      ,Name
  )

select 1, 100, 100, 0, 0, TMP_SSId, TMP_PerfId, 'TEMP'
  from CapacitySpace;



-- Update new record with its correct data

update CNF_SpaceStructure
set

       AccessConfigurationId = SS.AccessConfigurationId
      ,ParentId = SS.ParentId
      ,PriorityOrder = SS.PriorityOrder
      ,SpaceStructureType = SS.SpaceStructureType
      ,Name = SS.Name
      ,QuantityMin = SS.QuantityMin
      ,QuantityMax = SS.QuantityMax
      ,Enabled = SS.Enabled
      ,Code = SS.Code
      ,IsSeat = SS.IsSeat

from CNF_SpaceStructure inner join CNF_SpaceStructure SS on 
CNF_SpaceStructure.Temp_SpaceStructureId = SS.SpaceStructureId;



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

-- CNF_SpaceStructure - Add FK on CNF_Performance

Alter table [CNF_SpaceStructure] add foreign key([PerformanceId]) references [CNF_Performance] ([PerformanceId]);


				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>-- SCRIPT 2


-- CNF_EnvelopeCapacity - Add FK on CNF_SpaceStructure
-- ====================================================

-- CNF_EnvelopeCapacity - Fill field SpaceStructureId (with PerformanceId filled)

UPDATE    CNF_EnvelopeCapacity
SET       SpaceStructureId = SS.SpaceStructureId
FROM      CNF_SpaceStructure AS SS INNER JOIN
          CNF_Capacity ON SS.Temp_SpaceStructureId = CNF_Capacity.SpaceStructureId AND 
             SS.PerformanceId = CNF_Capacity.PerformanceId INNER JOIN
          CNF_EnvelopeCapacity ON CNF_Capacity.CapacityId = CNF_EnvelopeCapacity.CapacityId

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

-- CNF_EnvelopeCapacity - Fill field SpaceStructureId (with PerformanceId NULL)

UPDATE    CNF_EnvelopeCapacity
SET              SpaceStructureId = CNF_Capacity.SpaceStructureId
FROM         CNF_Capacity INNER JOIN
                      CNF_EnvelopeCapacity ON CNF_Capacity.CapacityId = CNF_EnvelopeCapacity.CapacityId
WHERE     (CNF_Capacity.PerformanceId IS NULL)

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

-- CNF_EnvelopeCapacity - Add FK on CNF_SpaceStructure

Alter table [CNF_EnvelopeCapacity] add foreign key([SpaceStructureId]) references [CNF_SpaceStructure] ([SpaceStructureId]);



				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>-- SCRIPT 3


-- CNF_SeatCategory - Add FK (nullable) on CNF_Performance
-- =========================================================

------------
-- CNF_SeatCategory - Insert record for each one in CNF_Capacity related to SeatCategory
------------


-- CNF_SeatCategory - Insert record related to CNF_Capacity


with CapacitySeatCategory (TMP_SCId, TMP_PerfId) 
  as (
    SELECT distinct 
      SeatCategoryId,
      PerformanceId
    FROM CNF_Capacity
    WHERE PerformanceId is not null   
    GROUP BY PerformanceId, SeatCategoryId
   )


insert into CNF_SeatCategory
  (
       AccessConfigurationId
      ,Name
      ,Quantity
      ,PerformanceId
      ,Temp_SeatCategoryId
  )

select 1, 'TEMP', 1000, TMP_PerfId, TMP_SCId
  from CapacitySeatCategory;

-- Update new record with its correct data

update CNF_SeatCategory
set

       AccessConfigurationId = SC.AccessConfigurationId
      ,Name = SC.Name
      ,Quantity = SC.Quantity
      ,Category = SC.Category
      ,Color = SC.Color
      ,AttributeId = SC.AttributeId
      ,Code = SC.Code

from CNF_SeatCategory inner join CNF_SeatCategory SC on 
CNF_SeatCategory.Temp_SeatCategoryId = SC.SeatCategoryId;

-- CNF_SeatCategory - Add FK on CNF_Performance

Alter table [CNF_SeatCategory] add foreign key([PerformanceId]) references [CNF_Performance] ([PerformanceId]);


				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>-- SCRIPT 4


-- CNF_EnvelopeCapacity - Add FK on CNF_SeatCategory
-- ====================================================

-- CNF_EnvelopeCapacity - Fill field SeatCategoryId (with PerformanceId filled)

UPDATE    CNF_EnvelopeCapacity
SET       SeatCategoryId = SC.SeatCategoryId
FROM      CNF_SeatCategory AS SC INNER JOIN
          CNF_Capacity ON SC.Temp_SeatCategoryId = CNF_Capacity.SeatCategoryId AND 
             SC.PerformanceId = CNF_Capacity.PerformanceId INNER JOIN
          CNF_EnvelopeCapacity ON CNF_Capacity.CapacityId = CNF_EnvelopeCapacity.CapacityId

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

-- CNF_EnvelopeCapacity - Fill field SeatCategoryId (with PerformanceId NULL)

UPDATE    CNF_EnvelopeCapacity
SET              SeatCategoryId = CNF_Capacity.SeatCategoryId
FROM         CNF_Capacity INNER JOIN
                      CNF_EnvelopeCapacity ON CNF_Capacity.CapacityId = CNF_EnvelopeCapacity.CapacityId
WHERE     (CNF_Capacity.PerformanceId IS NULL)


-- CNF_EnvelopeCapacity - Add FK on CNF_SeatCategory

Alter table [CNF_EnvelopeCapacity] add foreign key([SeatCategoryId]) references [CNF_SeatCategory] ([SeatCategoryId]);


				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>-- SCRIPT 5

-- CNF_Seat - Add FK on CNF_SpaceStructure
-- =======================================


-- CNF_Seat - Fill field SpaceStructureId (with PerformanceId filled) 

UPDATE    CNF_Seat
SET              SpaceStructureId = CNF_SpaceStructure.SpaceStructureId
FROM         CNF_Seat INNER JOIN
                      CNF_Capacity ON CNF_Seat.CapacityId = CNF_Capacity.CapacityId INNER JOIN
                      CNF_SpaceStructure ON CNF_Capacity.SpaceStructureId = CNF_SpaceStructure.Temp_SpaceStructureId AND 
                      CNF_Capacity.PerformanceId = CNF_SpaceStructure.PerformanceId

-- CNF_Seat - Fill field SpaceStructureId (with PerformanceId NULL) 


UPDATE    CNF_Seat
SET       SpaceStructureId = CNF_Capacity.SpaceStructureId
FROM      CNF_Capacity INNER JOIN
             CNF_Seat ON CNF_Capacity.CapacityId = CNF_Seat.CapacityId
WHERE     (CNF_Capacity.PerformanceId IS NULL)


-- CNF_Seat - Add FK on CNF_SpaceStructure

Alter table [CNF_Seat] add foreign key([SpaceStructureId]) references [CNF_SpaceStructure] ([SpaceStructureId]);

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>-- SCRIPT 6


-- CNF_Seat - Add FK on CNF_SeatCategory
-- =======================================

-- CNF_Seat - Fill field SeatCategoryId

-- CNF_Seat - Fill field SeatCategoryId (with PerformanceId filled) 

UPDATE    CNF_Seat
SET              SeatCategoryId = CNF_SeatCategory.SeatCategoryId
FROM         CNF_Seat INNER JOIN
                      CNF_Capacity ON CNF_Seat.CapacityId = CNF_Capacity.CapacityId INNER JOIN
                      CNF_SeatCategory ON CNF_Capacity.SeatCategoryId = CNF_SeatCategory.Temp_SeatCategoryId AND 
                      CNF_Capacity.PerformanceId = CNF_SeatCategory.PerformanceId

-- CNF_Seat - Fill field SeatCategoryId (with PerformanceId NULL) 


UPDATE    CNF_Seat
SET       SeatCategoryId = CNF_Capacity.SeatCategoryId
FROM      CNF_Capacity INNER JOIN
             CNF_Seat ON CNF_Capacity.CapacityId = CNF_Seat.CapacityId
WHERE     (CNF_Capacity.PerformanceId IS NULL)


-- CNF_Seat - Add FK on CNF_SeatCategory

Alter table [CNF_Seat] add foreign key([SeatCategoryId]) references [CNF_SeatCategory] ([SeatCategoryId]);


				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>-- SCRIPT 7


-- New table SEAT_CNF_SpaceStructureSeat
-- =================================



Create table [SEAT_CNF_SpaceStructureSeat]
(
	[SpaceStructureSeatId] Integer Identity(1,1) NOT NULL, UNIQUE ([SpaceStructureSeatId]),
	[SpaceStructureId] Integer NOT NULL,
	[SeatActive] Smallint Default 0 NOT NULL,
Primary Key ([SpaceStructureSeatId])
);



-- SEAT_CNF_SpaceStructureSeat - Fill Data

INSERT INTO SEAT_CNF_SpaceStructureSeat
                      (SpaceStructureId, SeatActive)
SELECT     SpaceStructureId, IsSeat
FROM         CNF_SpaceStructure;


-- SEAT_CNF_SpaceStructureSeat - Add FK on CNF_SpaceStructure

Alter table [SEAT_CNF_SpaceStructureSeat] add foreign key([SpaceStructureId]) references [CNF_SpaceStructure] ([SpaceStructureId]);


				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>-- SCRIPT 8


-- CNF_Seat - Remove FK on CNF_Capacity
-- =======================================

declare @foreign_key_name nvarchar(max),
@dropstmt nvarchar(max);

select @foreign_key_name = f.name
from sys.foreign_keys AS f
inner join sys.foreign_key_columns AS fc 
on  f.object_id = fc.constraint_object_id    
where  f.parent_object_id = object_id(N'[dbo].[CNF_Seat]') 
and  f.referenced_object_id = object_id(N'[dbo].[CNF_Capacity]')          
and COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'CapacityId'; 

if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[CNF_Seat] DROP CONSTRAINT [' + @foreign_key_name + ']'
  execute sp_executesql @dropstmt
end;


				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>-- SCRIPT 9


-- CNF_EnvelopeCapacity - Remove FK on CNF_Capacity
-- =======================================

declare @foreign_key_name nvarchar(max),
@dropstmt nvarchar(max);

select @foreign_key_name = f.name
from sys.foreign_keys AS f
inner join sys.foreign_key_columns AS fc 
on  f.object_id = fc.constraint_object_id    
where  f.parent_object_id = object_id(N'[dbo].[CNF_EnvelopeCapacity]') 
and  f.referenced_object_id = object_id(N'[dbo].[CNF_Capacity]')          
and COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'CapacityId'; 

if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[CNF_EnvelopeCapacity] DROP CONSTRAINT [' + @foreign_key_name + ']'
  execute sp_executesql @dropstmt
end;

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>-- SCRIPT 10


-- CNF_Envelope - Remove FK on ADM_AccessConfiguration
-- =======================================

declare @foreign_key_name nvarchar(max),
@dropstmt nvarchar(max);


select @foreign_key_name = f.name
from sys.foreign_keys AS f
inner join sys.foreign_key_columns AS fc 
on  f.object_id = fc.constraint_object_id    
where  f.parent_object_id = object_id(N'[dbo].[ADM_AccessConfiguration]')  
and  f.referenced_object_id = object_id(N'[dbo].[CNF_Envelope]')            
and COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'EnvelopeId'; 

if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[ADM_AccessConfiguration] DROP CONSTRAINT [' + @foreign_key_name + ']'
  execute sp_executesql @dropstmt
end;

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>-- SCRIPT 11


-- DATA_CapacityCounter - Remove FK on CNF_Capacity (table no longer used)
-- =================================================================

declare @foreign_key_name nvarchar(max),
@dropstmt nvarchar(max);


select @foreign_key_name = f.name
from sys.foreign_keys AS f
inner join sys.foreign_key_columns AS fc 
on  f.object_id = fc.constraint_object_id    
where  f.parent_object_id = object_id(N'[dbo].[DATA_CapacityCounter]')  
and  f.referenced_object_id = object_id(N'[dbo].[CNF_Capacity]')            
and COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'CapacityId'; 

if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[DATA_CapacityCounter] DROP CONSTRAINT [' + @foreign_key_name + ']'
  execute sp_executesql @dropstmt
end;

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>-- SCRIPT 12


-- CNF_Capacity - Remove FK on CNF_Performance
-- =================================================================

declare @foreign_key_name nvarchar(max),
@dropstmt nvarchar(max);


select @foreign_key_name = f.name
from sys.foreign_keys AS f
inner join sys.foreign_key_columns AS fc 
on  f.object_id = fc.constraint_object_id    
where  f.parent_object_id = object_id(N'[dbo].[CNF_Capacity]')  
and  f.referenced_object_id = object_id(N'[dbo].[CNF_Performance]')           
and COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'PerformanceId'; 

if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[CNF_Capacity] DROP CONSTRAINT [' + @foreign_key_name + ']'
  execute sp_executesql @dropstmt
end;

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>-- SCRIPT 13


-- CNF_Capacity - Remove FK on CNF_SpaceStructure
-- =================================================================

declare @foreign_key_name nvarchar(max),
@dropstmt nvarchar(max);


select @foreign_key_name = f.name
from sys.foreign_keys AS f
inner join sys.foreign_key_columns AS fc 
on  f.object_id = fc.constraint_object_id    
where  f.parent_object_id = object_id(N'[dbo].[CNF_Capacity]')  
and  f.referenced_object_id = object_id(N'[dbo].[CNF_SpaceStructure]')           
and COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'SpaceStructureId'; 

if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[CNF_Capacity] DROP CONSTRAINT [' + @foreign_key_name + ']'
  execute sp_executesql @dropstmt
end;

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>-- SCRIPT 14


-- CNF_Capacity - Remove FK on CNF_SeatCategory
-- =================================================================

declare @foreign_key_name nvarchar(max),
@dropstmt nvarchar(max);


select @foreign_key_name = f.name
from sys.foreign_keys AS f
inner join sys.foreign_key_columns AS fc 
on  f.object_id = fc.constraint_object_id    
where  f.parent_object_id = object_id(N'[dbo].[CNF_Capacity]')  
and  f.referenced_object_id = object_id(N'[dbo].[CNF_SeatCategory]')           
and COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'SeatCategoryId'; 

if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[CNF_Capacity] DROP CONSTRAINT [' + @foreign_key_name + ']'
  execute sp_executesql @dropstmt
end;


				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>-- SCRIPT 15


-- CNF_EnvelopeCapacity - Remove IDX for CNF_Capacity/CNF_Envelope
-- =================================================================

DROP INDEX IDX_EnvelopeCapacity_Unique 
  ON CNF_EnvelopeCapacity;


				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>-- SCRIPT 16



-- CNF_EnvelopeCapacity - Remove "not Null" for field CapacityId
-- ===========================================================

alter table CNF_EnvelopeCapacity alter column CapacityId integer null;


				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>-- SCRIPT 17


-- CNF_Seat - Remove "not Null" for field CapacityId
-- ===========================================================

alter table CNF_Seat alter column CapacityId integer null;

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.429</SQLVERSION>
			<RMTRACKLINK>1895</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>CNF_MultiLanguage=MultiLanguageId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table cnf_multilanguage add transtemp nvarchar(250);
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update cnf_multilanguage set transtemp = translation;

alter table cnf_multilanguage drop column Translation;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>exec sp_RENAME 'cnf_multilanguage.transtemp', 'Translation' , 'COLUMN'
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.428</SQLVERSION>
			<RMTRACKLINK>1835</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>DATA_SaleItem=SaleItemID</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>
alter table [DATA_SaleItem] Add [ProductSaleItemId] Integer NULL;
alter table [DATA_SaleItem] Add [RefundedQuantity] Smallint NULL;


Alter table [DATA_SaleItem] add constraint DATA_SaleItem_DATA_SaleITemProductRefunded foreign key([ProductSaleItemId]) references [DATA_SaleItem] ([SaleItemId]);


				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AlessandroBadii</ADDEDBY>
			<SQLVERSION>1.427</SQLVERSION>
			<RMTRACKLINK>1629</RMTRACKLINK>
			<REASON>DATA_Ticket
[0] Update PrintedPrice</REASON>
			<TABLENAMES>DATA_Ticket=TicketId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table DATA_Ticket
alter column PrintedPrice Float null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.426</SQLVERSION>
			<RMTRACKLINK>914</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>RES_CNF_ResourceType=ResourceTypeId
RES_CNF_ResourceType_Requirement=ResourceTypeRequirementId
RES_CNF_Resource=ResourceId
RES_CNF_ResourceRequirement=ResourceRequirementId
RES_CNF_CalendarTimeFrame=TimeFrameId
RES_CNF_CalendarTimeFrameItem=TimeFrameItemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [RES_CNF_ResourceType]
(
	[ResourceTypeId] Integer Identity(1,1) NOT NULL,
	[Description] Nvarchar(50) NOT NULL,
	[AllocationMode] Smallint NOT NULL,
	[NeedCalendar] Smallint Default 1 NOT NULL,
	[SetupTime] Integer Default 0 NOT NULL,
	[UnSetupTime] Integer Default 0 NOT NULL,
	[DmgCategoryId] Integer NULL,
	[CalendarId] Integer NULL,
Primary Key ([ResourceTypeId])
) 


Create table [RES_CNF_ResourceType_Requirement]
(
	[ResourceTypeRequirementId] Integer Identity(1,1) NOT NULL,
	[RequirementId] Integer NOT NULL,
	[ResourceTypeId] Integer NOT NULL,
Primary Key ([ResourceTypeRequirementId])
) 


Create table [RES_CNF_Resource]
(
	[ResourceId] Integer Identity(1,1) NOT NULL,
	[ResourceTypeId] Integer NOT NULL,
	[Description] Nvarchar(50) NOT NULL,
	[Quantity] Integer NOT NULL,
	[SetupTime] Integer NULL,
	[UnsetupTime] Integer NULL,
	[CalendarId] Integer NULL,
Primary Key ([ResourceId])
) 

Create table [RES_CNF_ResourceRequirement]
(
	[ResourceRequirementId] Integer Identity(1,1) NOT NULL,
	[Quantity] Integer Default 1 NOT NULL,
	[ResourceId] Integer NOT NULL,
	[RequirementId] Integer NOT NULL,
Primary Key ([ResourceRequirementId])
) 

Create table [RES_CNF_CalendarTimeFrame]
(
	[TimeFrameId] Integer  Identity(1,1) NOT NULL,
	[Description] Nvarchar(50) NOT NULL,
Primary Key ([TimeFrameId])
) 

Create table [RES_CNF_CalendarTimeFrameItem]
(
	[TimeFrameItemId] Integer  Identity(1,1) NOT NULL,
	[TimeFrameId] Integer NOT NULL,
	[FromTime] Datetime NULL,
	[Durantion] Integer NOT NULL,
Primary Key ([TimeFrameItemId])
) 


Alter table [RES_CNF_ResourceType_Requirement] add constraint ResourceType_Requirement_ResourceType foreign key([ResourceTypeId]) references [RES_CNF_ResourceType] ([ResourceTypeId]);
Alter table [RES_CNF_Resource] add constraint Resource_ResourceType foreign key([ResourceTypeId])  references [RES_CNF_ResourceType] ([ResourceTypeId]);
Alter table [RES_CNF_ResourceRequirement] add constraint ResourceRequirement_Resource foreign key([ResourceId]) references [RES_CNF_Resource] ([ResourceId]); 
Alter table [RES_CNF_CalendarTimeFrameItem] add constraint CalendarTimeFrameItem_CalendarTimeFrame foreign key([TimeFrameId]) references [RES_CNF_CalendarTimeFrame] ([TimeFrameId]);


Alter table [RES_CNF_ResourceType_Requirement] add constraint ResourceType_Requirement_Requirement foreign key([RequirementId]) references [RES_CNF_Requirement] ([RequirementId]);
Alter table [RES_CNF_ResourceRequirement] add constraint ResourceRequirement_Requirement foreign key([RequirementId]) references [RES_CNF_Requirement] ([RequirementId]);


Alter table [RES_CNF_Resource] add constraint Resource_Calendar foreign key([CalendarId]) references [CNF_Calendar] ([CalendarId]);
Alter table [RES_CNF_ResourceType] add constraint ResourceType_Calendar  foreign key([CalendarId]) references [CNF_Calendar] ([CalendarId]);

Alter table [RES_CNF_ResourceType] add constraint ResourceType_DmgCategory   foreign key([DmgCategoryId]) references [CNF_DmgCategory] ([DmgCategoryId]);
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>davideapicella</ADDEDBY>
			<SQLVERSION>1.425</SQLVERSION>
			<RMTRACKLINK>791</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>MSG_CNF_Message=MessageId
MSG_CNF_Attachment=AttachmentId
MSG_CNF_Message2Entity=Message2EntityId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>
Create table [MSG_CNF_Message]
(
	[MessageId] Integer Identity(1,1) NOT NULL,
	[SystemId] Integer NOT NULL,
	[WorkstationId] Integer NOT NULL,
	[UserId] Integer NOT NULL,
	[CreationDate] Datetime NOT NULL,
	[MessageType] Smallint NOT NULL,
	[ConfirmType] Smallint NOT NULL,
	[ValidFrom] Datetime NULL,
	[ValidTo] Datetime NULL,
	[MessageSubject] Nvarchar(250) NOT NULL,
	[MessageText] Ntext NOT NULL,
	[MessageStatus] Smallint NOT NULL,
	[MessageAttachment] Smallint NOT NULL,
	[Note] Ntext NULL,
Primary Key ([MessageId])
)

Create table [MSG_CNF_Attachment]
(
	[AttachmentId] Integer Identity(1,1) NOT NULL,
	[MessageId] Integer NOT NULL,
	[CreationDate] Datetime NOT NULL,
	[Attachment] Image NOT NULL,
	[AttachmentName] Nvarchar(50) NOT NULL,
	[AttachmentType] Smallint NOT NULL,
	[Note] Ntext NULL,
Primary Key ([AttachmentId])
)

Create table [MSG_CNF_Message2Entity]
(
	[Message2EntityId] Integer  Identity(1,1) NOT NULL,
	[MessageId] Integer NOT NULL,
	[EntityType] Smallint NOT NULL,
	[EntityId] Char(1) NOT NULL,	
Primary Key ([Message2EntityId])
)

Alter table [MSG_CNF_Attachment] add constraint Attachment_Message foreign key([MessageId]) references [MSG_CNF_Message] ([MessageId])  
Alter table [MSG_CNF_Message2Entity] add constraint Message2Entity_Message foreign key([MessageId]) references [MSG_CNF_Message] ([MessageId])   
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.424</SQLVERSION>
			<RMTRACKLINK>914</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>RES_CNF_RequirementTemplate=RequirementTemplateId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>sp_RENAME 'RES_CNF_RequirementTemplate.Descripton', 'Description' , 'COLUMN'
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.423</SQLVERSION>
			<RMTRACKLINK>1757</RMTRACKLINK>
			<REASON>CNF_DataMask
[0] Added field IgnoreComponentLink
[1] update fields</REASON>
			<TABLENAMES>CNF_DataMask=DataMaskId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_DataMask
  add IgnoreComponentLink Smallint NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> update CNF_DataMask   
   set IgnoreComponentLink = 0    
   where IgnoreComponentLink is null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.422</SQLVERSION>
			<RMTRACKLINK>912</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>RES_CNF_Requirement=RequirementId
RES_CNF_RequirementTemplate=RequirementTemplateId
RES_CNF_RequirementTemplateItem=RequirementTemplateTemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>
Create table [RES_CNF_Requirement]
(
	[RequirementId] Integer Identity(1,1) NOT NULL,
	[Description] Nvarchar(50) NOT NULL,
	[Note] Text NULL,
	[Exclusive] Smallint Default 0 NOT NULL,
Primary Key ([RequirementId])
) 


Create table [RES_CNF_RequirementTemplate]
(
	[RequirementTemplateId] Integer Identity(1,1) NOT NULL,
	[Descripton] Nvarchar(50) NOT NULL,
	[Note] Text NULL,
Primary Key ([RequirementTemplateId])
) 


Create table [RES_CNF_RequirementTemplateItem]
(
	[RequirementTemplateTemId] Integer Identity(1,1) NOT NULL,
	[RequirementTemplateId] Integer NOT NULL,
	[RequirementId] Integer NOT NULL,
	[QtyFromSale] Smallint Default 0 NULL,
	[Quantity] Integer NULL,
Primary Key ([RequirementTemplateTemId])
) 



Alter table [RES_CNF_RequirementTemplateItem] add constraint RequirementTemplateItem_Requirement  foreign key ([RequirementId]) references [RES_CNF_Requirement] ([RequirementId]);
Alter table [RES_CNF_RequirementTemplateItem] add constraint RequirementTemplateItem_RequirementTemplate foreign key ([RequirementTemplateId]) references [RES_CNF_RequirementTemplate] ([RequirementTemplateId]);



				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.421</SQLVERSION>
			<RMTRACKLINK>1723</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>CNF_WorkStation=WorkstationId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table [CNF_Workstation] add [ExternalCode] Nvarchar(50) null;
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.420</SQLVERSION>
			<RMTRACKLINK>913</RMTRACKLINK>
			<REASON/>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>alter view [dbo].[vwStock_Inventory]
as
select
SCP.MinStock,
SCP.MatrixCellId as MatrixcellId,
SCP.SKU as Product,
STOCK_CNF_Warehouse.WarehouseId as  WarehouseId,
STOCK_CNF_Um.Description Um,
STOCK_CNF_Warehouse.Description as WareHouse,
sum(qtyleft) qtyleft,
sum(qtyout) qtyout,
sum(qtytomove) qtytomove
from
(select
matrixcellid,
warehouseid,
sum(qtyleft) qtyleft,
0 qtyout,
0 qtytomove
from
stock_movement (nolock)
where
InOut = 1
group by
matrixcellid,
warehouseid
union
select
matrixcellid,
warehouseid,
0,
sum(qty) qtyout,
sum(qty-qtymoved) qtytomove
from
stock_movement (nolock)
where
stock_movement.InOut = -1 and 
stock_movement.MovementDate = dateadd(day,datediff(day,0,getdate()),0)
group by
matrixcellid,
warehouseid) as inventory  inner join
STOCK_CNF_Product SCP with (nolock) on inventory.MatrixCellId = SCP.MatrixCellId inner join 
STOCK_CNF_Warehouse with (nolock) on inventory.warehouseid = STOCK_CNF_Warehouse.warehouseid inner join
STOCK_CNF_Um with (nolock) on STOCK_CNF_Um.UmId=SCP.UmId
group by
SCP.MinStock,
SCP.MatrixCellId ,
SCP.SKU,
STOCK_CNF_Warehouse.WarehouseId ,
STOCK_CNF_Um.Description ,
STOCK_CNF_Warehouse.Description 


				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE NONCLUSTERED INDEX [idx_StockMovement_InOut] ON [dbo].[STOCK_Movement] 
(
	[WarehouseId] ASC,
	[MatrixCellId] ASC,
	[InOut] ASC
)


CREATE NONCLUSTERED INDEX [idx_StockMovement_Item] ON [dbo].[STOCK_Movement] 
(
	[ItemId] ASC
)

CREATE NONCLUSTERED INDEX [idx_StockMovement_QtyLeft] ON [dbo].[STOCK_Movement] 
(
	[MovementDate] ASC,
	[MatrixCellId] ASC,
	[WarehouseId] ASC,
	[QtyLeft] ASC
)


CREATE NONCLUSTERED INDEX [idx_StockMovement_QtyToMove] ON [dbo].[STOCK_Movement] 
(
	[QtyMoved] ASC,
	[Qty] ASC,
	[MatrixCellId] ASC,
	[WarehouseId] ASC,
	[InOut] ASC,
	[Completed] ASC
)

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.419</SQLVERSION>
			<RMTRACKLINK>1682</RMTRACKLINK>
			<REASON>[0] add field InsUserId
[1] fill UpdUserId with admin Id
[2] set UpdUserId not null
[3] fill InsUserId with AdminId
[4] set InsUserId not null
[5] add FK on UserId for upd
[6] add FK on UserId for ins</REASON>
			<TABLENAMES>DATA_Account=AccountId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT> Alter table DATA_Account 
   add InsUserId Integer null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_Account
  set UpdUserId = 1  
  where UpdUserId is null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table DATA_Account
  alter column UpdUserId integer not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Update DATA_Account
  set InsUserId=1  
  where InsUserId is Null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Account
  alter column InsUserId integer not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> Alter table DATA_Account 
   add  foreign key(UpdUserId) references CNF_User (UserId)  on update no action on delete no action 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> Alter table DATA_Account 
   add  foreign key(InsUserId) references CNF_User (UserId)  on update no action on delete no action 
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.418</SQLVERSION>
			<RMTRACKLINK>913</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>STOCK_Movement=MovementId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table STOCK_Movement add Completed Smallint not null default 0;
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.417</SQLVERSION>
			<RMTRACKLINK/>
			<REASON/>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>create view vwStock_Inventory
as

select 
SCP.MinStock,
CNF_MatrixCellOption.MatrixCellId as MatrixcellId,
STOCK_CNF_Warehouse.WarehouseId as  WarehouseId,
CNF_MatrixCellOption.OptionValue as Product,
STOCK_CNF_Um.Description Um,
STOCK_CNF_Warehouse.Description as WareHouse,
MovOut.QtyOut,
MovOut.QtyToMove,
sum(qtyleft) QtyLeft
from
stock_movement with (nolock) inner join
STOCK_CNF_Product SCP with (nolock) on SCP.MatrixCellId= STOCK_Movement.MatrixCellId inner join
CNF_MatrixCellOption with (nolock) on CNF_MatrixCellOption.MatrixCellId=STOCK_Movement.MatrixCellId and CNF_MatrixCellOption.OptionType = 5 inner join
STOCK_CNF_Warehouse with (nolock) on STOCK_CNF_Warehouse.WareHouseId=STOCK_Movement.WareHouseId inner join
STOCK_CNF_Um with (nolock) on STOCK_CNF_Um.UmId=SCP.UmId left join
( select WarehouseId,
	MatrixCellId,
	sum(qty-qtymoved) QtyToMove,
	sum(qty ) QtyOut
  from STOCK_Movement sto with (nolock)
  where sto.InOut = -1 and 
		sto.MovementDate = dateadd(day,datediff(day,0,getdate()),0)
group by
WarehouseId,
MatrixCellId
 ) MovOut on MovOut.warehouseid = STOCK_CNF_Warehouse.warehouseid and 
		MovOut.MatrixCellId = SCP.MatrixCellId

group by
SCP.MinStock,
CNF_MatrixCellOption.MatrixCellId ,
STOCK_CNF_Warehouse.WarehouseId,
CNF_MatrixCellOption.OptionValue,
MovOut.QtyOut,
MovOut.QtyToMove,
STOCK_CNF_Um.Description,
STOCK_CNF_Warehouse.Description
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AlessandroBadii</ADDEDBY>
			<SQLVERSION>1.416</SQLVERSION>
			<RMTRACKLINK>1629</RMTRACKLINK>
			<REASON>CNF_MatrixCellOption
[0] Update OptionValue</REASON>
			<TABLENAMES>CNF_MatrixCellOption=MatrixCellOptionId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_MatrixCellOption
alter column OptionValue nvarchar(100) null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.415</SQLVERSION>
			<RMTRACKLINK>913</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>STOCK_Movement=MovementId
STOCK_MovementRef=MovementRefId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter Table Stock_MovementRef Add Qty Float Not Null default 0;
Alter Table Stock_Movement Add MovementTime DateTime;
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.414</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>CNF_Event_Permission
[0] create table
[1]Add FK on EventId
[2] add FK on AccountId
[3] add FK on DmgId
[4] add FK on SiteId
[5] add FK on UserId
[6] add Fk on UserGroupId
[7] add FK on OperatingAreaId
[8] add FK on WorkstationId
			</REASON>
			<TABLENAMES>CNF_Event_Permission=EventPermissionId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT> Create table [CNF_Event_Permission]
(
	[EventPermissionId] Integer Identity(1,1) NOT NULL,
	[EventId] Integer NOT NULL,
	[SiteId] Integer NULL,
	[OperatingAreaId] Integer NULL,
	[WorkstationId] Integer NULL,
	[UserGroupId] Integer NULL,
	[UserId] Integer NULL,
	[DmgCategoryId] Integer NULL,
	[AccountId] Integer NULL,
	[Allow] Smallint NULL,
Primary Key ([EventPermissionId])
) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_Event_Permission 
  add  foreign key(EventId) references CNF_Event (EventId)
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> Alter table CNF_Event_Permission 
 add  foreign key(AccountId) references DATA_Account (AccountId)




				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_Event_Permission 
add  foreign key(DmgCategoryId) references CNF_DmgCategory (DmgCategoryId)


				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> Alter table CNF_Event_Permission 
   add  foreign key(SiteId) references CNF_Site (SiteId)
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_Event_Permission 
  add  foreign key(UserId) references CNF_User (UserId) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_Event_Permission 
  add  foreign key(UserGroupId) references CNF_UserGroup (UserGroupId)

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_Event_Permission 
  add  foreign key(OperatingAreaId) references CNF_OperatingArea (OperatingAreaId)

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> Alter table CNF_Event_Permission 
 add  foreign key(WorkstationId) references CNF_Workstation (WorkstationId)

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.413</SQLVERSION>
			<RMTRACKLINK>913</RMTRACKLINK>
			<REASON/>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table STOCK_CNF_ProductCategory alter column ParentId Integer null;
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.412</SQLVERSION>
			<RMTRACKLINK>913</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>STOCK_CNF_ProductCategory=CategoryId
STOCK_CNF_Product=MatrixCellId
STOCK_Movement=MovementId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>
CREATE TABLE [STOCK_CNF_ProductCategory](
[CategoryId] [Integer] Identity(1,1)  NOT NULL,
[ParentId] [Integer]   NOT NULL,
[Description] [Nvarchar](50)   NOT NULL,
CONSTRAINT [pk_STOCK_CNF_ProductCategory] PRIMARY KEY CLUSTERED
(
[CategoryId]
) ON [PRIMARY]
) ON [PRIMARY]



Alter Table STOCK_CNF_Product Add [CheckInventoryOnSale] [Smallint]  Default 0 NOT NULL


Alter Table STOCK_CNF_Product drop column SalesWoInventory;



Alter Table STOCK_CNF_Product Add [DefaultCost] [Money]   NULL



Alter Table STOCK_CNF_Product Add [DefaultSupplier] [Integer]   NULL



Alter Table STOCK_CNF_Product Add [CategoryId] [Integer]   NULL



Alter Table STOCK_Movement Add [QtyMoved] [Float]   NULL



Alter Table STOCK_Movement Alter Column [MovementType] [Smallint]   NOT NULL



ALTER TABLE [dbo].[STOCK_CNF_ProductCategory]   WITH NOCHECK ADD  CONSTRAINT [Relationship1244] FOREIGN KEY([ParentId])
REFERENCES [dbo].[STOCK_CNF_ProductCategory] ([CategoryId])


ALTER TABLE [dbo].[STOCK_CNF_ProductCategory] CHECK CONSTRAINT [Relationship1244]



ALTER TABLE [dbo].[STOCK_CNF_Product]   WITH NOCHECK ADD  CONSTRAINT [Relationship1245] FOREIGN KEY([CategoryId])
REFERENCES [dbo].[STOCK_CNF_ProductCategory] ([CategoryId])



ALTER TABLE [dbo].[STOCK_CNF_Product] CHECK CONSTRAINT [Relationship1245]


ALTER TABLE [dbo].[STOCK_CNF_Product]   WITH NOCHECK ADD  CONSTRAINT [Relationship1240] FOREIGN KEY([DefaultSupplier])
REFERENCES [dbo].[DATA_Account] ([AccountId])

ALTER TABLE [dbo].[STOCK_CNF_Product] CHECK CONSTRAINT [Relationship1240]
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AlessandroBadii</ADDEDBY>
			<SQLVERSION>1.411</SQLVERSION>
			<RMTRACKLINK>913</RMTRACKLINK>
			<REASON>STOCK_Movement
[0] Delete AccountId
[1] Delete MinStock
[2] Delete SalesWoInventory

STOCK_Product
[3] Add MinStock
[4] Add SalesWoInventory</REASON>
			<TABLENAMES>STOCK_Movement=MovementId
STOCK_CNF_Product=MatrixCellId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table STOCK_Movement
  Drop Column AccountId;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table STOCK_Movement
  Drop Column MinStock;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table STOCK_Movement
  Drop Column SalesWoInventory;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table STOCK_CNF_Product
  Add MinStock Float null;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table STOCK_CNF_Product
  Add SalesWoInventory Smallint null;
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AlessandroBadii</ADDEDBY>
			<SQLVERSION>1.410</SQLVERSION>
			<RMTRACKLINK>913</RMTRACKLINK>
			<REASON>STOCK_Movement
[0] Add AccountId
[1] Add MinStock
[2] Add SalesWoInventory</REASON>
			<TABLENAMES>STOCK_Movement=MovementId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table STOCK_Movement
  Add AccountId Integer null;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table STOCK_Movement
  Add MinStock Float null;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table STOCK_Movement
  Add SalesWoInventory Smallint null;
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.409</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>DATA_Account
[0] Add Field UpdAccountId</REASON>
			<TABLENAMES>DATA_ACCOUNT=AccountId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>if COL_LENGTH('DATA_Account', 'UpdUserId') is null 
begin
  alter table DATA_Account
    add UpdUserId integer null
end
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>davideapicella</ADDEDBY>
			<SQLVERSION>1.408</SQLVERSION>
			<RMTRACKLINK>1640</RMTRACKLINK>
			<REASON>DATA_MediaIdentifierBlackList
[0]  alter column BlockCause Smallint NULL</REASON>
			<TABLENAMES>DATA_MediaIdentifierBlackList=MediaBlackListId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table DATA_MediaIdentifierBlackList
  alter column BlockCause Smallint NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AlessandroBadii</ADDEDBY>
			<SQLVERSION>1.407</SQLVERSION>
			<RMTRACKLINK>913</RMTRACKLINK>
			<REASON>STOCK_CNF_ProductUm
[0] Add SellUnit</REASON>
			<TABLENAMES>STOCK_CNF_ProductUm=ProductUmId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table STOCK_CNF_ProductUm
  Add SellUnit Integer not null default 0;
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AlessandroBadii</ADDEDBY>
			<SQLVERSION>1.406</SQLVERSION>
			<RMTRACKLINK>1675</RMTRACKLINK>
			<REASON>DATA_AccountFinancial
[0] Update ExternalCode1
[1] Update FirstName
[2] Update SurName
[3] Update ZipCode
[4] Update City
[5] Update State
[6] Update Country
[7] Update HomePhone
[8] Update BusinessPhone
[9] Update Fax
[10] Update MobilePhone
[11] Update EmailAddress1</REASON>
			<TABLENAMES>DATA_Account=AccountId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table DATA_Account
alter column ExternalCode1 nvarchar(100) null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table DATA_Account
alter column FirstName nvarchar(100) null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table DATA_Account
alter column SurName nvarchar(100) null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table DATA_Account
alter column ZipCode nvarchar(100) null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table DATA_Account
alter column City nvarchar(100) null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table DATA_Account
alter column State nvarchar(100) null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table DATA_Account
alter column Country nvarchar(100) null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table DATA_Account
alter column HomePhone nvarchar(100) null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table DATA_Account
alter column BusinessPhone nvarchar(100) null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table DATA_Account
alter column Fax nvarchar(100) null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table DATA_Account
alter column MobilePhone nvarchar(100) null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table DATA_Account
alter column EmailAddress1 nvarchar(100) null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AlessandroBadii</ADDEDBY>
			<SQLVERSION>1.405</SQLVERSION>
			<RMTRACKLINK>888</RMTRACKLINK>
			<REASON>DATA_AccountFinancial
[0] Update AgreedLimitDeposit</REASON>
			<TABLENAMES>DATA_AccountFinancial=AccountId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table DATA_AccountFinancial 
alter column AgreedLimitDeposit float null 
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.404</SQLVERSION>
			<RMTRACKLINK>913</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>STOCK_Movement=MovementId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table STOCK_Movement alter column UmId int null;
alter table STOCK_Movement alter column MovementType int not null;
alter table STOCK_Movement alter column UmQty float null;
alter table STOCK_Movement alter column ItemId int null;
alter table STOCK_Movement alter column QtyLeft float null;

alter table STOCK_Movement alter column MovementDate smalldatetime  null;

alter table STOCK_Movement add  InOut Smallint  not null default 0;
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.403</SQLVERSION>
			<RMTRACKLINK>913</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>STOCK_Movement=MovementId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter Table STOCK_Movement add MovementDate smalldatetime not null default getdate();
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.402</SQLVERSION>
			<RMTRACKLINK>913</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>STOCK_Movement=MovementId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter Table STOCK_Movement add QtyLeft float null;
Alter Table STOCK_Movement add OnSale smallint not null default 0;
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.401</SQLVERSION>
			<RMTRACKLINK>913</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>STOCK_CNF_WarehouseAssign=WarehouseAssignId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE [dbo].[STOCK_CNF_WarehouseAssign] ADD SiteId Integer;


ALTER TABLE [dbo].[STOCK_CNF_WarehouseAssign]   WITH NOCHECK ADD  CONSTRAINT [Relationship1239] FOREIGN KEY([SiteId])
REFERENCES [dbo].[CNF_Site] ([SiteId])

ALTER TABLE [dbo].[STOCK_CNF_WarehouseAssign] CHECK CONSTRAINT [Relationship1239]
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AlessandroBadii</ADDEDBY>
			<SQLVERSION>1.400</SQLVERSION>
			<RMTRACKLINK>888</RMTRACKLINK>
			<REASON>DATA_AccountFinancial
[0] Add AgreedLimitDeposit</REASON>
			<TABLENAMES>DATA_AccountFinancial=AccountId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table DATA_AccountFinancial
  add AgreedLimitDeposit float not null default 0
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.399</SQLVERSION>
			<RMTRACKLINK>913</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>STOCK_CNF_Um=UmId
STOCK_CNF_Product=MatrixCellId
STOCK_CNF_ProductBarcodes=ProductBarcodeIf
STOCK_CNF_ProductUm=ProductUmId
STOCK_CNF_Warehouse=WarehouseId
STOCK_CNF_WarehouseAssign=WarehouseAssignId
STOCK_Movement=MovementId
STOCK_MovementRef=MovementRefId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>                

CREATE TABLE [STOCK_CNF_Um](
[UmId] [Integer] Identity(1,1)  NOT NULL,
[Description] [Nvarchar](50)   NOT NULL,
CONSTRAINT [pk_STOCK_CNF_Um] PRIMARY KEY CLUSTERED
(
[UmId]
) ON [PRIMARY]
) ON [PRIMARY]


CREATE TABLE [STOCK_CNF_Product](
[MatrixCellId] [Integer]   NOT NULL,
[SKU] [Varchar](20)   NOT NULL,
[UmId] [Integer]   NOT NULL,
CONSTRAINT [pk_STOCK_CNF_Product] PRIMARY KEY CLUSTERED
(
[MatrixCellId]
) ON [PRIMARY]
) ON [PRIMARY]


CREATE TABLE [STOCK_CNF_ProductBarcodes](
[ProductBarcodeIf] [Integer] Identity(1,1)  NOT NULL,
[Barcode] [Varchar](20)   NOT NULL,
[MatrixCellId] [Integer]   NOT NULL,
CONSTRAINT [pk_STOCK_CNF_ProductBarcodes] PRIMARY KEY CLUSTERED
(
[ProductBarcodeIf]
) ON [PRIMARY]
) ON [PRIMARY]


CREATE TABLE [STOCK_CNF_ProductUm](
[ProductUmId] [Integer] Identity(1,1)  NOT NULL,
[Conversion] [Float]   NOT NULL,
[UmId] [Integer]   NOT NULL,
[MatrixCellId] [Integer]   NOT NULL,
CONSTRAINT [pk_STOCK_CNF_ProductUm] PRIMARY KEY CLUSTERED
(
[ProductUmId]
) ON [PRIMARY]
) ON [PRIMARY]


CREATE TABLE [STOCK_CNF_Warehouse](
[WarehouseId] [Integer] Identity(1,1)  NOT NULL,
[Description] [Nvarchar](50)   NOT NULL,
CONSTRAINT [pk_STOCK_CNF_Warehouse] PRIMARY KEY CLUSTERED
(
[WarehouseId]
) ON [PRIMARY]
) ON [PRIMARY]


CREATE TABLE [STOCK_CNF_WarehouseAssign](
[WarehouseAssignId] [Integer] Identity(1,1)  NOT NULL,
[OperatingAreaId] [Integer]   NULL,
[WorkstationId] [Integer]   NULL,
[WarehouseId] [Integer]   NOT NULL,
CONSTRAINT [pk_STOCK_CNF_WarehouseAssign] PRIMARY KEY CLUSTERED
(
[WarehouseAssignId]
) ON [PRIMARY]
) ON [PRIMARY]


CREATE TABLE [STOCK_Movement](
[MovementId] [Integer] Identity(1,1)  NOT NULL,
[UserId] [Integer]   NOT NULL,
[WarehouseId] [Integer]   NOT NULL,
[MovementType] [Smallint]   NULL,
[MatrixCellId] [Integer]   NOT NULL,
[UmId] [Integer]   NOT NULL,
[Qty] [Float]   NOT NULL,
[UmQty] [Float]   NOT NULL,
[Value] [Money]   NULL,
[TotValue] [Money]   NULL,
[ItemId] [Integer]   NOT NULL,
[UmConversion] [Float]   NULL,
CONSTRAINT [pk_STOCK_Movement] PRIMARY KEY CLUSTERED
(
[MovementId]
) ON [PRIMARY]
) ON [PRIMARY]


CREATE TABLE [STOCK_MovementRef](
[MovementRefId] [Integer] Identity(1,1)  NOT NULL,
[MainMovementId] [Integer]   NOT NULL,
[ChildMovementId] [Integer]   NOT NULL,
CONSTRAINT [pk_STOCK_MovementRef] PRIMARY KEY CLUSTERED
(
[MovementRefId]
) ON [PRIMARY]
) ON [PRIMARY]



				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE [dbo].[STOCK_CNF_WarehouseAssign]   WITH NOCHECK ADD  CONSTRAINT [Relationship1230] FOREIGN KEY([WorkstationId])
REFERENCES [dbo].[CNF_Workstation] ([WorkstationId])

ALTER TABLE [dbo].[STOCK_CNF_WarehouseAssign] CHECK CONSTRAINT [Relationship1230]



ALTER TABLE [dbo].[STOCK_Movement]   WITH NOCHECK ADD  CONSTRAINT [Relationship1232] FOREIGN KEY([UserId])
REFERENCES [dbo].[CNF_User] ([UserId])

ALTER TABLE [dbo].[STOCK_Movement] CHECK CONSTRAINT [Relationship1232]



ALTER TABLE [dbo].[STOCK_CNF_WarehouseAssign]   WITH NOCHECK ADD  CONSTRAINT [Relationship1229] FOREIGN KEY([OperatingAreaId])
REFERENCES [dbo].[CNF_OperatingArea] ([OperatingAreaId])

ALTER TABLE [dbo].[STOCK_CNF_WarehouseAssign] CHECK CONSTRAINT [Relationship1229]


ALTER TABLE [dbo].[STOCK_Movement]   WITH NOCHECK ADD  CONSTRAINT [Relationship1231] FOREIGN KEY([ItemId])
REFERENCES [dbo].[DATA_TransactionItem] ([ItemId])

ALTER TABLE [dbo].[STOCK_Movement] CHECK CONSTRAINT [Relationship1231]


ALTER TABLE [dbo].[STOCK_CNF_Product]   WITH NOCHECK ADD  CONSTRAINT [Relationship1220] FOREIGN KEY([MatrixCellId])
REFERENCES [dbo].[CNF_MatrixCell] ([MatrixCellId])

ALTER TABLE [dbo].[STOCK_CNF_Product] CHECK CONSTRAINT [Relationship1220]


ALTER TABLE [dbo].[STOCK_Movement]   WITH NOCHECK ADD  CONSTRAINT [Relationship1235] FOREIGN KEY([MatrixCellId])
REFERENCES [dbo].[CNF_MatrixCell] ([MatrixCellId])

ALTER TABLE [dbo].[STOCK_Movement] CHECK CONSTRAINT [Relationship1235]

ALTER TABLE [dbo].[STOCK_CNF_Product]   WITH NOCHECK ADD  CONSTRAINT [Relationship1221] FOREIGN KEY([UmId])
REFERENCES [dbo].[STOCK_CNF_Um] ([UmId])

ALTER TABLE [dbo].[STOCK_CNF_Product] CHECK CONSTRAINT [Relationship1221]

ALTER TABLE [dbo].[STOCK_CNF_ProductUm]   WITH NOCHECK ADD  CONSTRAINT [Relationship1223] FOREIGN KEY([UmId])
REFERENCES [dbo].[STOCK_CNF_Um] ([UmId])

ALTER TABLE [dbo].[STOCK_CNF_ProductUm] CHECK CONSTRAINT [Relationship1223]

ALTER TABLE [dbo].[STOCK_Movement]   WITH NOCHECK ADD  CONSTRAINT [Relationship1234] FOREIGN KEY([UmId])
REFERENCES [dbo].[STOCK_CNF_Um] ([UmId])

ALTER TABLE [dbo].[STOCK_Movement] CHECK CONSTRAINT [Relationship1234]


ALTER TABLE [dbo].[STOCK_CNF_ProductBarcodes]   WITH NOCHECK ADD  CONSTRAINT [Relationship1222] FOREIGN KEY([MatrixCellId])
REFERENCES [dbo].[STOCK_CNF_Product] ([MatrixCellId])

ALTER TABLE [dbo].[STOCK_CNF_ProductBarcodes] CHECK CONSTRAINT [Relationship1222]

ALTER TABLE [dbo].[STOCK_CNF_ProductUm]   WITH NOCHECK ADD  CONSTRAINT [Relationship1224] FOREIGN KEY([MatrixCellId])
REFERENCES [dbo].[STOCK_CNF_Product] ([MatrixCellId])

ALTER TABLE [dbo].[STOCK_CNF_ProductUm] CHECK CONSTRAINT [Relationship1224]

ALTER TABLE [dbo].[STOCK_CNF_WarehouseAssign]   WITH NOCHECK ADD  CONSTRAINT [Relationship1228] FOREIGN KEY([WarehouseId])
REFERENCES [dbo].[STOCK_CNF_Warehouse] ([WarehouseId])

ALTER TABLE [dbo].[STOCK_CNF_WarehouseAssign] CHECK CONSTRAINT [Relationship1228]

ALTER TABLE [dbo].[STOCK_Movement]   WITH NOCHECK ADD  CONSTRAINT [Relationship1233] FOREIGN KEY([WarehouseId])
REFERENCES [dbo].[STOCK_CNF_Warehouse] ([WarehouseId])

ALTER TABLE [dbo].[STOCK_Movement] CHECK CONSTRAINT [Relationship1233]


ALTER TABLE [dbo].[STOCK_MovementRef]   WITH NOCHECK ADD  CONSTRAINT [Relationship1236] FOREIGN KEY([MainMovementId])
REFERENCES [dbo].[STOCK_Movement] ([MovementId])

ALTER TABLE [dbo].[STOCK_MovementRef] CHECK CONSTRAINT [Relationship1236]

ALTER TABLE [dbo].[STOCK_MovementRef]   WITH NOCHECK ADD  CONSTRAINT [Relationship1237] FOREIGN KEY([MainMovementId])
REFERENCES [dbo].[STOCK_Movement] ([MovementId])

ALTER TABLE [dbo].[STOCK_MovementRef] CHECK CONSTRAINT [Relationship1237]
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>davideapicella</ADDEDBY>
			<SQLVERSION>1.398</SQLVERSION>
			<RMTRACKLINK>2</RMTRACKLINK>
			<REASON>CNF_License
[0] Create CNF_License table
[1] Drop old table CNF_Licence </REASON>
			<TABLENAMES>CNF_License=LicenseId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_License] (
	[LicenseId] Integer Identity(1,1) NOT NULL,
        [SystemId] Integer NOT NULL,
	[Description] Nvarchar(100) NOT NULL,
	[LicenseType] Integer NOT NULL,
	[LicenseSubType] Integer NOT NULL,
	[LicenceCode] Nvarchar(50) NOT NULL,
	[CreationDate] Datetime NOT NULL,
	[ImportDate] Datetime NOT NULL,
	[Enabled] Smallint NOT NULL,
Primary Key  ([LicenseId])
)

Alter table [CNF_License] add  foreign key([SystemId]) references [CNF_System] ([SystemId])
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>declare @foreign_key_name nvarchar(max),
@dropstmt nvarchar(max);

select @foreign_key_name = f.name
from sys.foreign_keys AS f
inner join sys.foreign_key_columns AS fc 
on  f.object_id = fc.constraint_object_id    
where  f.parent_object_id = object_id(N'[dbo].[CNF_Licence]')  -- TABELLA DA CUI SI VUOLE RIMUOVERE LA FK
and  f.referenced_object_id = object_id(N'[dbo].[CNF_Licence]')           -- TABELLA DEL RIFERIMENTO DELLA FK 
and COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'ParentId'; -- CAMPO FK DA RIMUOVERE

if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[CNF_Licence] DROP CONSTRAINT [' + @foreign_key_name + ']'; --  TABELLA DA CUI SI VUOLE RIMUOVERE LA FK
  execute sp_executesql @dropstmt
end;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>declare @foreign_key_name nvarchar(max),
@dropstmt nvarchar(max);

select @foreign_key_name = f.name
from sys.foreign_keys AS f
inner join sys.foreign_key_columns AS fc 
on  f.object_id = fc.constraint_object_id    
where  f.parent_object_id = object_id(N'[dbo].[CNF_Licence]')  -- TABELLA DA CUI SI VUOLE RIMUOVERE LA FK
and  f.referenced_object_id = object_id(N'[dbo].[CNF_System]')           -- TABELLA DEL RIFERIMENTO DELLA FK 
and COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'SystemId'; -- CAMPO FK DA RIMUOVERE

if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[CNF_Licence] DROP CONSTRAINT [' + @foreign_key_name + ']'; --  TABELLA DA CUI SI VUOLE RIMUOVERE LA FK
  execute sp_executesql @dropstmt
end;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>declare @foreign_key_name nvarchar(max),
@dropstmt nvarchar(max);

select @foreign_key_name = f.name
from sys.foreign_keys AS f
inner join sys.foreign_key_columns AS fc 
on  f.object_id = fc.constraint_object_id    
where  f.parent_object_id = object_id(N'[dbo].[CNF_Right]')  -- TABELLA DA CUI SI VUOLE RIMUOVERE LA FK
and  f.referenced_object_id = object_id(N'[dbo].[CNF_Licence]')           -- TABELLA DEL RIFERIMENTO DELLA FK 
and COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'LicenceId'; -- CAMPO FK DA RIMUOVERE

if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[CNF_Right] DROP CONSTRAINT [' + @foreign_key_name + ']'; --  TABELLA DA CUI SI VUOLE RIMUOVERE LA FK
  execute sp_executesql @dropstmt
end;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DROP TABLE CNF_Licence
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.397</SQLVERSION>
			<RMTRACKLINK>1604 </RMTRACKLINK>
			<REASON>DATA_SaleItem
[0] update field
[1] set people count as non null


			</REASON>
			<TABLENAMES>DATA_SaleItem=SaleItemId
			</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT> update DATA_SaleItem 
   set PeopleCount = 1 where PeopleCount is null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> Alter table DATA_SaleItem 
   alter column PeopleCount Integer not null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.396</SQLVERSION>
			<RMTRACKLINK>1516</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>DATA_Payment=PaymentId
CNF_PaymentMethod=PaymentMethodId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table DATA_Payment add PaymentFee float not null default 0;

Alter table CNF_PaymentMethod add FeeType smallint not null default 0;
Alter table CNF_PaymentMethod add Fee float not null default 0;
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>AlessandroBadii</ADDEDBY>
			<SQLVERSION>1.395</SQLVERSION>
			<RMTRACKLINK>1538</RMTRACKLINK>
			<REASON>CNF_PAY
[0] add StartTime
[1] add EndTime
[2] add Sunday
[3] add Monday
[4] add Tuesday
[5] add Wednesday
[6] add Thursday
[7] add Friday
[8] add Saturday</REASON>
			<TABLENAMES>CNF_PAY=PayId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_PAY
  Add StartTime dateTime null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_PAY
  Add EndTime dateTime null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_PAY
  Add Sunday smallint null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_PAY
  Add Monday smallint null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_PAY
  Add Tuesday smallint null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_PAY
  Add Wednesday smallint null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_PAY
  Add Thursday smallint null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_PAY
  Add Friday smallint null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_PAY
  Add Saturday smallint null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.394</SQLVERSION>
			<RMTRACKLINK>1537</RMTRACKLINK>
			<REASON>DATA_Voucher
[0] set voucher code as varchar(40)</REASON>
			<TABLENAMES>DATA_Voucher=VoucherId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table DATA_Voucher
  alter column VoucherCode nvarchar(40) not null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.393</SQLVERSION>
			<RMTRACKLINK>1520</RMTRACKLINK>
			<REASON>Adding reference beet transactionitem and ruleid so the old transactionitem could be restored in case of generated by system too</REASON>
			<TABLENAMES>DATA_SaleItem=SaleItemId
DATA_TransactionItem=ItemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter Table DATA_SaleItem add [PromotionItemRuleId] [int] NULL;
Alter Table DATA_TransactionItem add [PromotionItemRuleId] [int] NULL;

ALTER TABLE [dbo].[DATA_SaleItem]  WITH CHECK ADD  CONSTRAINT [FK_DATA_SaleItem_PromotionItemRule] FOREIGN KEY([PromotionItemRuleId])
REFERENCES [dbo].[CNF_PromotionItemRule] ([PromotionItemRuleId])


ALTER TABLE [dbo].[DATA_TransactionItem]  WITH CHECK ADD  CONSTRAINT [FK_DATA_TransactionItem_PromotionItemRule] FOREIGN KEY([PromotionItemRuleId])
REFERENCES [dbo].[CNF_PromotionItemRule] ([PromotionItemRuleId])

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>davideapicella</ADDEDBY>
			<SQLVERSION>1.392</SQLVERSION>
			<RMTRACKLINK>1313</RMTRACKLINK>
			<REASON>CNF_Performance
[0] add field minonscreen</REASON>
			<TABLENAMES>CNF_Performance=PerformanceId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT> Alter Table CNF_Performance 
   Add MinonScreen Integer null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.391</SQLVERSION>
			<RMTRACKLINK>1450</RMTRACKLINK>
			<REASON>CNF_PriceList
[0..1] add field ValidFromTime and ValidToTime</REASON>
			<TABLENAMES>CNF_PriceList=PriceListId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT> Alter table CNF_PriceList   
   add ValidFromTime dateTime null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> Alter table CNF_PriceList   
   add ValidToTime dateTime null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.390</SQLVERSION>
			<RMTRACKLINK>1371</RMTRACKLINK>
			<REASON>CNF_Performance
[0] add field BlockPerformance smallint not null</REASON>
			<TABLENAMES>CNF_Performance=PerformanceId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_Performance
  add BlockPerformance smallint not null default 0
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.389</SQLVERSION>
			<RMTRACKLINK>932</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>CNF_Mask_Utility=MaskUtilityId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_Mask_Utility] (
	[MaskUtilityId] Integer Identity(1,1) NOT NULL,
	[MaskId] Integer NOT NULL,
	[UtilityAK] Nvarchar(10) NOT NULL,
	[Params] Nvarchar(200) NULL,
Primary Key  ([MaskUtilityId])
) 

Alter table [CNF_Mask_Utility] add  foreign key([MaskId]) references [CNF_Mask] ([MaskId]) 
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ettore Bottega</ADDEDBY>
			<SQLVERSION>1.388</SQLVERSION>
			<RMTRACKLINK>903</RMTRACKLINK>
			<REASON>New table DATA_BankAccount</REASON>
			<TABLENAMES>DATA_BankAccount=BankAccountId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [DATA_BankAccount] (
	[BankAccountId] Integer Identity(1,1) NOT NULL,
	[AccountId] Integer NOT NULL,
	[HolderName] Nvarchar(100) NULL,
	[SortCode] Nvarchar(8) NULL,
	[AccountNumber] Nvarchar(20) NULL,
	[CountryCode] Char(2) NULL,
Primary Key  ([BankAccountId])
) 

Alter table [DATA_BankAccount] add  foreign key([AccountId]) references [DATA_Account] ([AccountId])
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.387</SQLVERSION>
			<RMTRACKLINK>1381</RMTRACKLINK>
			<REASON>CNF_Calendar
Renamed colomn CalendarNote in CalendarDescription</REASON>
			<TABLENAMES>CNF_Calendar=CalendarId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_Calendar
  drop column CalendarNote
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> Alter table CNF_Calendar 
   add CalendarDescription nvarchar(50) null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.386</SQLVERSION>
			<RMTRACKLINK>1381</RMTRACKLINK>
			<REASON>CNF_Calendar
[0] add field enabled not null
[1] add Fk to SystemId</REASON>
			<TABLENAMES>CNF_Calendar=CalendarId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_Calendar
  add Enabled smallint not null default 1
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_Calendar
  add SystemId integer
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>  update CNF_Calendar  
    set SystemId = (Select SystemId from CNF_System)
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>  alter table CNF_Calendar  
    alter column SystemId integer not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_Calendar 
  add  foreign key(SystemId) references CNF_System (SystemId)
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.385</SQLVERSION>
			<RMTRACKLINK>1381</RMTRACKLINK>
			<REASON>CNF_Calendar
[0] add fiedl CalendarCode not null</REASON>
			<TABLENAMES>CNF_Calendar=CalendarId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_Calendar
  add CalendarCode nVarchar(8) not null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>skhan</ADDEDBY>
			<SQLVERSION>1.384</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>CNF_CNF_Pay
[0] create field PayAmount</REASON>
			<TABLENAMES>CNF_PAY=PayId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_PAY
add PayAmount float null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.383</SQLVERSION>
			<RMTRACKLINK>1316</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>DATA_SaleCoupon=SaleCouponId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter Table DATA_SaleCoupon Add Qty Integer not null default 1;
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>FABRY</ADDEDBY>
			<SQLVERSION>1.382</SQLVERSION>
			<RMTRACKLINK>1322</RMTRACKLINK>
			<REASON>New table CNF_Site_LoginPermission</REASON>
			<TABLENAMES>CNF_Site_LoginPermission=SiteLoginPermissionId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_Site_LoginPermission] (
	[SiteLoginPermissionId] Integer Identity(1,1) NOT NULL,
	[LoginSiteId] Integer NOT NULL,
	[SiteId] Integer NULL,
	[OperatingAreaId] Integer NULL,
	[WorkstationId] Integer NULL,
	[UserGroupId] Integer NULL,
	[UserId] Integer NULL,
	[DmgCategoryId] Integer NULL,
	[AccountId] Integer NULL,
	[Allow] Smallint NULL,
Primary Key  ([SiteLoginPermissionId])
) 

Alter table [CNF_Site_LoginPermission] add  foreign key([LoginSiteId]) references [CNF_Site] ([SiteId])
Alter table [CNF_Site_LoginPermission] add  foreign key([SiteId]) references [CNF_Site] ([SiteId])
Alter table [CNF_Site_LoginPermission] add  foreign key([OperatingAreaId]) references [CNF_OperatingArea] ([OperatingAreaId]) 
Alter table [CNF_Site_LoginPermission] add  foreign key([WorkstationId]) references [CNF_Workstation] ([WorkstationId]) 
Alter table [CNF_Site_LoginPermission] add  foreign key([UserGroupId]) references [CNF_UserGroup] ([UserGroupId])
Alter table [CNF_Site_LoginPermission] add  foreign key([UserId]) references [CNF_User] ([UserId]) 
Alter table [CNF_Site_LoginPermission] add  foreign key([DmgCategoryId]) references [CNF_DmgCategory] ([DmgCategoryId]) 
Alter table [CNF_Site_LoginPermission] add  foreign key([AccountId]) references [DATA_Account] ([AccountId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.381</SQLVERSION>
			<RMTRACKLINK>1319</RMTRACKLINK>
			<REASON>CNF_CNF_Commission2Account
[0] drop index 
[1] create field AccountId
[2] update AccountId value
[3] set accountID not null
[4] add FK con Account
[5] drop field entityTable
[6] drop field entityId
[7] add index
			</REASON>
			<TABLENAMES>CNF_Commission2Account=Commission2AccountId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>DROP INDEX IncentiveAccount 
  ON CNF_Commission2Account 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Commission2Account
  add AccountId integer null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_Commission2Account
set AccountId = EntityId
  where EntityId &lt;&gt; 0

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Commission2Account
  alter column AccountId integer not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_Commission2Account 
  add  foreign key(AccountId) references DATA_Account (AccountId) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table  CNF_Commission2Account
  drop column EntityId
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> alter table  CNF_Commission2Account
  drop column EntityTable
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create UNIQUE Index IDX_IncentiveAccount  
  ON CNF_Commission2Account (PayId,AccountId)
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.380</SQLVERSION>
			<RMTRACKLINK>1143</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>CNF_DataMask=DataMaskId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE CNF_DATAMASK ADD VisibleLevel SMALLINT;
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.379</SQLVERSION>
			<RMTRACKLINK>1242</RMTRACKLINK>
			<REASON>Translation Added to Dmg</REASON>
			<TABLENAMES>DATA_DmgData_Translate=DmgDataTranslateId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE TABLE [DATA_DmgData_Translate](
	[DmgDataTranslateId] [int] IDENTITY(1,1) NOT NULL,
	[DmgDataId] [int] NOT NULL,
	[MaskData] [nvarchar](100) NULL,
	[LanguageId] [int] NULL,
PRIMARY KEY CLUSTERED 
(
	[DmgDataTranslateId] ASC
) ON [PRIMARY]
) ON [PRIMARY]

ALTER TABLE [dbo].[DATA_DmgData_Translate]  ADD CONSTRAINT DATA_DmgData_DmgData_Translate  FOREIGN KEY ([DmgDataId])
REFERENCES [dbo].[DATA_DmgData] ([DMGDATAID])


ALTER TABLE [dbo].[DATA_DmgData_Translate]  ADD CONSTRAINT CNF_Language_DmgData_Translate FOREIGN KEY ([LanguageId])
REFERENCES [dbo].[CNF_Language] ([LanguageId])

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.378</SQLVERSION>
			<RMTRACKLINK>1252</RMTRACKLINK>
			<REASON>CNF_LedgerAccount
[0] set field AccountCode null
[1] set field AccountName null</REASON>
			<TABLENAMES>CNF_LedgerAccount=LedgerAccountId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_LedgerAccount
  alter column AccountCode nvarchar(30) null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_LedgerAccount
  alter column AccountName nvarchar(50) null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.377</SQLVERSION>
			<RMTRACKLINK>1252</RMTRACKLINK>
			<REASON>CNF_PaymentMethod
[0] remove FK to CostCenterId
[1] remove field
CNF_LedgerAccount
[2]add field
[3] add FK</REASON>
			<TABLENAMES>CNF_PaymentMethod=PaymentMethodId
CNF_LedgerAccount=LedgerAccountId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_PaymentMethod
  set CostCenterId = Null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>declare @foreign_key_name nvarchar(max),
@dropstmt nvarchar(max);

select @foreign_key_name = f.name
from sys.foreign_keys AS f
inner join sys.foreign_key_columns AS fc 
on  f.object_id = fc.constraint_object_id 
where  f.parent_object_id = object_id(N'[dbo].[CNF_PaymentMethod]')
and  f.referenced_object_id = object_id(N'[dbo].[CNF_CostCenter]')
and COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'CostCenterId';

if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[CNF_PaymentMethod] DROP CONSTRAINT [' + @foreign_key_name + ']';
  execute sp_executesql @dropstmt
end;

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_PaymentMethod
  drop column CostCenterId
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> Alter table CNF_LedgerAccount
  add CostCenterId integer null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_LedgerAccount 
  add  foreign key(CostCenterId) references CNF_CostCenter (CostCenterId) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.376</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>CNF_PaymentMethod
[0..1] add Fk on CNF_CostCenter</REASON>
			<TABLENAMES>CNF_PaymentMethod=PaymentMethodId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT> Alter table CNF_PaymentMethod
  add CostCenterId integer null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_PaymentMethod 
  add  foreign key(CostCenterId) references CNF_CostCenter (CostCenterId) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.375</SQLVERSION>
			<RMTRACKLINK>1246</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>DATA_ACCOUNT=ACCOUNTID</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>DROP INDEX [IDX_Account_DisplayName] ON [dbo].[DATA_Account]
ALTER TABLE data_account ALTER COLUMN [DisplayName] varchar(100)
CREATE NONCLUSTERED INDEX [IDX_Account_DisplayName] ON [dbo].[DATA_Account] 
(
	[DisplayName] ASC
)
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabrizioPedrazzi</ADDEDBY>
			<SQLVERSION>1.374</SQLVERSION>
			<RMTRACKLINK>808</RMTRACKLINK>
			<REASON>
RMTrack 905

0) CNF_SpaceStructure
Add field IsSeat smallint

1) CNF_SpaceStructure
Porting value from old field IsSeat (ADM_AccessConfiguration) in CNF_SpaceStructure

-----------

RMTrack 808

2) DATA_Ticket
Update values in PeopleCount from Null to 1  

3) DATA_Ticket
Set as not null field PeopleCount


			</REASON>
			<TABLENAMES>CNF_SpaceStructure=SpaceStructureId
DATA_Ticket=TicketId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>  Alter table CNF_SpaceStructure
  add IsSeat Smallint Default 0 NOT NULL 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_SpaceStructure 
set CNF_SpaceStructure.IsSeat = 
    (Select ADM_AccessConfiguration.IsSeat from ADM_AccessConfiguration
     where ADM_AccessConfiguration.AccessConfigurationId = CNF_SpaceStructure.AccessConfigurationId)     

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_Ticket 
set DATA_Ticket.PeopleCount = 1
where DATA_Ticket.PeopleCount is null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>  alter table DATA_Ticket
  alter column PeopleCount integer not null  
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.373</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>DATA_Ticket
[0] add field peopleCount to manage group Ticket

DATA_SaleItem
[1] add field peopleCount to manga group ticket in reservation</REASON>
			<TABLENAMES>DATA_Ticket=TicketId
DATA_SaleItem=SaleItemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table DATA_Ticket
  add PeopleCount integer 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table DATA_SaleItem
  add PeopleCount integer 
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.372</SQLVERSION>
			<RMTRACKLINK>866</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>DATA_SaleItemRule=SaleItemRuleId
DATA_TransactionItemRule=TransactionItemRuleId
DATA_SaleCoupon=SaleCouponId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [DATA_TransactionItemRule] (
	[TransactionItemRuleId] Integer Identity(1,1) NOT NULL,
	[PromotionItemRuleId] Integer NULL,
	[ItemId] Integer NOT NULL,
	[FeeorDiscount] Integer NOT NULL,
	[Perc] Float NULL,
	[Forfait] Money NULL,
	[Price] Money NULL,
	[GeneratedByTheSystem] Bit NOT NULL,
	[ApplyToQty] Integer NULL,
Primary Key  ([TransactionItemRuleId])
) 


Create table [DATA_SaleItemRule] (
	[SaleItemRuleId] Integer Identity(1,1) NOT NULL,
	[PromotionItemRuleId] Integer NULL,
	[SaleItemId] Integer NOT NULL,
	[FeeorDiscount] Integer NOT NULL,
	[Perc] Float NULL,
	[Forfait] Money NULL,
	[Price] Money NULL,
	[GeneratedByTheSystem] Bit NOT NULL,
	[ApplyToQty] Integer NULL,
Primary Key  ([SaleItemRuleId])
) 


Create table [DATA_SaleCoupon] (
	[SaleCouponId] Integer Identity(1,1) NOT NULL,
        [SaleId] Integer NOT NULL,
	[PromotionId] Integer NOT NULL,
Primary Key  ([SaleCouponId])
)

Alter table [DATA_TransactionItemRule] add constraint FK_DATA_TransactionItemRule_Transaction  foreign key ([ItemId]) references [DATA_TransactionItem] ([ItemId]) 
Alter table [DATA_TransactionItemRule] add constraint FK_DATA_TransactionItemRule_PromotionItemRule foreign key ([PromotionItemRuleId]) references [CNF_PromotionItemRule] ([PromotionItemRuleId])
Alter table [DATA_SaleItemRule] add constraint FK_DATA_SaleIteRule_SaleItem foreign key([SaleItemId]) references [DATA_SaleItem] ([SaleItemId]) 
Alter table [DATA_SaleItemRule] add constraint FK_DATA_SaleIteRule_PromotionItemRule foreign key([PromotionItemRuleId]) references [CNF_PromotionItemRule] ([PromotionItemRuleId])
Alter table [DATA_SaleCoupon] add constraint FK_DATA_SaleCoupon_Promotion foreign key([PromotionId]) references [CNF_Promotion] ([PromotionId])
Alter table [DATA_SaleCoupon] add constraint FK_DATA_SaleCoupon_Sale foreign key([SaleId]) references [DATA_Sale] ([SaleId]) 




				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.371</SQLVERSION>
			<RMTRACKLINK>1141</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>DATA_ACCOUNT=ACCOUNTID</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE data_account ALTER COLUMN [CompanyName] varchar(100)
ALTER TABLE data_account ALTER COLUMN [Address1] varchar(100)
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.370</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add FK SystemId to table CNF_ExternalMediaType</REASON>
			<TABLENAMES>CNF_ExternalMediaType=ExternalMediaTypeId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT> Alter table CNF_ExternalMediaType
  add SystemId integer null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Update CNF_ExternalMediaType
   set SystemId=(Select SystemId From CNF_System) 



				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_ExternalMediaType
  alter column SystemId integer not null  
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_ExternalMediaType 
  add  foreign key(SystemId) references CNF_System (SystemId) 
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>skhan</ADDEDBY>
			<SQLVERSION>1.369</SQLVERSION>
			<RMTRACKLINK/>
			<REASON/>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Commission2Account] add  foreign key([PayId]) references [CNF_Pay] ([PayId])
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Pay] add  foreign key([MatrixCellId]) references [CNF_MatrixCell] ([MatrixCellId])
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create UNIQUE Index [IncentiveAccount]  ON [CNF_Commission2Account] ([PayId] ,[EntityId] ,[EntityTable] )
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>skhan</ADDEDBY>
			<SQLVERSION>1.368</SQLVERSION>
			<RMTRACKLINK/>
			<REASON/>
			<TABLENAMES>CNF_Commission2Account=Commission2AccountId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT> DROP TABLE [CNF_Commission2Account]

 Create table [CNF_Commission2Account] (
	[Commission2AccountId] Integer Identity(1,1) NOT NULL,
	[PayId] Integer NOT NULL,
	[EntityId] Integer NULL,
	[EntityTable] Smallint NULL,
	[Enabled] Smallint NULL,
Primary Key  ([Commission2AccountId])
)
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>skhan</ADDEDBY>
			<SQLVERSION>1.367</SQLVERSION>
			<RMTRACKLINK/>
			<REASON/>
			<TABLENAMES>CNF_Commission2Account=Cimmission2AccountId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_Commission2Account] (
	[Cimmission2AccountId] Integer Identity(1,1) NOT NULL,
	[PayId] Integer NOT NULL,
	[EntityId] Integer NULL,
	[EntityTable] Smallint NULL,
	[Enabled] Smallint NULL,
Primary Key  ([Cimmission2AccountId])
)
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.366</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>DATA_SaleItem

[0,1] Add Field ActiveFrom, ActiveTo</REASON>
			<TABLENAMES>DATA_SaleItem=SaleItemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT> Alter table DATA_SaleItem 
   add ActiveFrom Datetime NULL

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> Alter table DATA_SaleItem 
   add ActiveTo Datetime NULL

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.365</SQLVERSION>
			<RMTRACKLINK>866</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>CNF_PromotionItemRule=PromotionItemRuleId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter Table CNF_PromotionItemRule add RepeatRange Integer;
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.364</SQLVERSION>
			<RMTRACKLINK>866</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>CNF_Promotion=PromotionId
CNF_PromotionAssociation=PromotionAssociationId
CNF_PromotionItem=PromotionItemId
CNF_PromotionItemRule=PromotionItemRuleId
CNF_PromotionProduct=PromotionProductId
CNF_PromotionValidity=PromotionValidityId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Drop Table DATA_TransactionItemPromotion;
Drop table CNF_PromotionProduct;
Drop table CNF_PromotionItem;

Create table [CNF_PromotionItem] (
	[PromotionItemId] Integer Identity(1,1) NOT NULL,
	[PromotionId] Integer NOT NULL,
	[Description] Nvarchar(50) NOT NULL,
	[Notes] Text NULL,
	[RuleType] Nvarchar(30) NULL,
Primary Key  ([PromotionItemId])
);

Create table [CNF_PromotionProduct] (
	[PromotionProductId] Integer Identity(1,1) NOT NULL,
	[MatrixCellId] Integer NOT NULL,
	[PromotionItemRuleId] Integer NOT NULL,
Primary Key  ([PromotionProductId])
);

Create table [CNF_PromotionItemRule] (
	[PromotionItemRuleId] Integer Identity(1,1) NOT NULL,
	[PromotionItemId] Integer NOT NULL,
	[MaxForTransaction] Integer NULL,
	[AnyProduct] Integer NULL,
	[FromQty] Integer NULL,
	[ToQty] Integer NULL,
	[UpsaleRevenue] Integer NULL,
	[UpsaleQuantity] Integer NULL,
	[FromRevenue] Money NULL,
	[ToRevenue] Money NULL,
	[ApplytoQty] Integer NULL,
	[DiscPerc] Float NULL,
	[PromotionPrice] Money NULL,
	[DiscForfait] Money NULL,
	[NewProduct] Integer NULL,
	[ApplyDiscountToAllItem] Integer NULL,
Primary Key  ([PromotionItemRuleId])
);


Alter table [CNF_PromotionItemRule] add  foreign key([PromotionItemId]) references [CNF_PromotionItem] ([PromotionItemId]);
Alter table [CNF_PromotionProduct] add  foreign key([PromotionItemRuleId]) references [CNF_PromotionItemRule] ([PromotionItemRuleId]);
Alter table [CNF_PromotionItem] add  foreign key  ([PromotionId]) references [CNF_Promotion] ([PromotionId]); 


				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>skhan</ADDEDBY>
			<SQLVERSION>1.363</SQLVERSION>
			<RMTRACKLINK>929</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>CNF_PAY=PayId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT> DROP TABLE [CNF_PAY]

 Create table [CNF_PAY] (
	[PayId] Integer Identity(1,1) NOT NULL,
	[MatrixCellId] Integer NULL,
	[PayCode] Nvarchar(10) NOT NULL,
	[Description] Ntext NULL,
	[PayType] Nvarchar(30) NOT NULL,
	[PayMethod] Nvarchar(30) NOT NULL,
	[MinTarget] Integer NULL,
	[MaxTarget] Integer NULL,
	[StartValidity] Datetime NULL,
	[EndValidity] Datetime NULL,
	[PayPeriod] Nvarchar(30) NOT NULL,
	[Enabled] Smallint NULL,
Primary Key  ([PayId])
)
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ettore Bottega</ADDEDBY>
			<SQLVERSION>1.362</SQLVERSION>
			<RMTRACKLINK>871</RMTRACKLINK>
			<REASON>Adding tables to manage sale validity rights on Attribute and MatrixSheet</REASON>
			<TABLENAMES>CNF_MatrixSheet_SaleValidity=MatrixSheetSaleValidityId
CNF_Attribute_SaleValidity=AttributeSaleValidityId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_MatrixSheet_SaleValidity] (
	[MatrixSheetSaleValidityId] Integer Identity(1,1) NOT NULL,
	[MatrixSheetId] Integer NOT NULL,
	[SiteId] Integer NULL,
	[OperatingAreaId] Integer NULL,
	[WorkstationId] Integer NULL,
	[UserGroupId] Integer NULL,
	[UserId] Integer NULL,
	[DmgCategoryId] Integer NULL,
	[AccountId] Integer NULL,
	[Allow] Smallint NULL,
Primary Key  ([MatrixSheetSaleValidityId])
)
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_Attribute_SaleValidity] (
	[AttributeSaleValidityId] Integer Identity(1,1) NOT NULL,
	[AttributeId] Integer NOT NULL,
	[SiteId] Integer NULL,
	[OperatingAreaId] Integer NULL,
	[WorkstationId] Integer NULL,
	[UserGroupId] Integer NULL,
	[UserId] Integer NULL,
	[DmgCategoryId] Integer NULL,
	[AccountId] Integer NULL,
	[Allow] Smallint NULL,
Primary Key  ([AttributeSaleValidityId])
) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_MatrixSheet_SaleValidity] add  foreign key([SiteId]) references [CNF_Site] ([SiteId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_MatrixSheet_SaleValidity] add  foreign key([OperatingAreaId]) references [CNF_OperatingArea] ([OperatingAreaId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_MatrixSheet_SaleValidity] add  foreign key([WorkstationId]) references [CNF_Workstation] ([WorkstationId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_MatrixSheet_SaleValidity] add  foreign key([UserGroupId]) references [CNF_UserGroup] ([UserGroupId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_MatrixSheet_SaleValidity] add  foreign key([UserId]) references [CNF_User] ([UserId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_MatrixSheet_SaleValidity] add  foreign key([DmgCategoryId]) references [CNF_DmgCategory] ([DmgCategoryId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_MatrixSheet_SaleValidity] add  foreign key([AccountId]) references [DATA_Account] ([AccountId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_MatrixSheet_SaleValidity] add  foreign key([MatrixSheetId]) references [CNF_MatrixSheet] ([MatrixSheetId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Attribute_SaleValidity] add  foreign key([SiteId]) references [CNF_Site] ([SiteId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Attribute_SaleValidity] add  foreign key([OperatingAreaId]) references [CNF_OperatingArea] ([OperatingAreaId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Attribute_SaleValidity] add  foreign key([WorkstationId]) references [CNF_Workstation] ([WorkstationId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Attribute_SaleValidity] add  foreign key([UserGroupId]) references [CNF_UserGroup] ([UserGroupId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Attribute_SaleValidity] add  foreign key([UserId]) references [CNF_User] ([UserId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Attribute_SaleValidity] add  foreign key([DmgCategoryId]) references [CNF_DmgCategory] ([DmgCategoryId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Attribute_SaleValidity] add  foreign key([AccountId]) references [DATA_Account] ([AccountId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Attribute_SaleValidity] add  foreign key([AttributeId]) references [CNF_Attribute] ([AttributeId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>skhan</ADDEDBY>
			<SQLVERSION>1.361</SQLVERSION>
			<RMTRACKLINK>929</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>CNF_PAY=PayId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>DROP TABLE [CNF_PAY]

 Create table [CNF_PAY] (
	[PayId] Integer Identity(1,1) NOT NULL,
	[MatrixCellId] Integer NULL,
	[PayCode] Nvarchar(10) NOT NULL,
	[Description] Ntext NULL,
	[PayType] Nvarchar(30) NOT NULL,
	[PayMethod] Nvarchar(30) NOT NULL,
	[MinTarget] Integer NULL,
	[MaxTarget] Integer NULL,
	[StartValidity] Datetime NULL,
	[EndValidity] Datetime NULL,
	[PayPeriod] Nvarchar(30) NOT NULL,
	[Enabled] Smallint NULL,
Primary Key  ([PayId])
)
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>smcdonald</ADDEDBY>
			<SQLVERSION>1.360</SQLVERSION>
			<RMTRACKLINK>936</RMTRACKLINK>
			<REASON>CNF_Seat add field SeatLabel</REASON>
			<TABLENAMES>CNF_Seat=SeatId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_Seat add SeatLabel varchar(100) null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER procedure [dbo].[sp_ui_CNF_Seat_insert]
  @SeatId Integer output,
  @EnvelopeId int,
  @SeatMapId int,
  @RowLabel nvarchar(60),
  @ColLabel nvarchar(60),
  @Weight int,
  @FlagInfo smallint,
  @Enabled smallint,
  @PerformanceId int,
  @ReferenceTable smallint,
  @ReferenceId int,
  @CapacityId int,
  @BookingReference varchar(38),
  @SeatLabel varchar(100)
as
begin
  insert into CNF_Seat (
    EnvelopeId,
    SeatMapId,
    RowLabel,
    ColLabel,
    Weight,
    FlagInfo,
    Enabled,
    PerformanceId,
    ReferenceTable,
    ReferenceId,
    CapacityId,
    BookingReference,
    SeatLabel
  ) values (
    @EnvelopeId,
    @SeatMapId,
    @RowLabel,
    @ColLabel,
    @Weight,
    @FlagInfo,
    @Enabled,
    @PerformanceId,
    @ReferenceTable,
    @ReferenceId,
    @CapacityId,
    @BookingReference,
    @SeatLabel
  )

  select @SeatId=SCOPE_IDENTITY()

end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER procedure [dbo].[sp_ui_CNF_Seat_update]
  @SeatId int,
  @EnvelopeId int,
  @SeatMapId int,
  @RowLabel nvarchar(60),
  @ColLabel nvarchar(60),
  @Weight int,
  @FlagInfo smallint,
  @Enabled smallint,
  @PerformanceId int,
  @ReferenceTable smallint,
  @ReferenceId int,
  @CapacityId int,
  @BookingReference varchar(38),
  @SeatLabel varchar(100)
as
begin
  update CNF_Seat
  set
    EnvelopeId=@EnvelopeId,
    SeatMapId=@SeatMapId,
    RowLabel=@RowLabel,
    ColLabel=@ColLabel,
    Weight=@Weight,
    FlagInfo=@FlagInfo,
    Enabled=@Enabled,
    PerformanceId=@PerformanceId,
    ReferenceTable=@ReferenceTable,
    ReferenceId=@ReferenceId,
    CapacityId=@CapacityId,
    BookingReference=@BookingReference,
    SeatLabel=@SeatLabel
  where
    SeatId=@SeatId
end
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>skhan</ADDEDBY>
			<SQLVERSION>1.359</SQLVERSION>
			<RMTRACKLINK>929</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>CNF_Pay=PayId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT> Create table [CNF_PAY] (
	[PayId] Integer NOT NULL,
	[MatrixCellId] Integer NULL,
	[PayCode] Nvarchar(10) NOT NULL,
	[Description] Ntext NULL,
	[PayType] Nvarchar(30) NOT NULL,
	[PayMethod] Nvarchar(30) NOT NULL,
	[MinTarget] Integer NULL,
	[MaxTarget] Integer NULL,
	[StartValidity] Datetime NULL,
	[EndValidity] Datetime NULL,
	[PayPeriod] Nvarchar(30) NOT NULL,
	[Enabled] Smallint NULL,
Primary Key  ([PayId])
)
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.358</SQLVERSION>
			<RMTRACKLINK>866</RMTRACKLINK>
			<REASON/>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>Drop Table [CNF_PromotionAssociation] 

Create table [CNF_PromotionAssociation] (
	[PromotionAssociationId] Integer Identity(1,1) NOT NULL,
	[PromotionId] Integer NOT NULL,
	[SiteId] Integer NULL,
	[OperatingAreaId] Integer NULL,
	[WorkstationId] Integer NULL,
	[Allow] Smallint NOT NULL,
	[ClientCategoryId] Varchar(32) NULL,
	[CliendId] Integer NULL,
Primary Key  ([PromotionAssociationId])
) 


Alter table [CNF_PromotionAssociation] add constraint fkPromotionAssociation_Site   foreign key([SiteId]) references [CNF_Site] ([SiteId]) 
Alter table [CNF_PromotionAssociation] add constraint fkPromotionAssociation_WorkStation   foreign key([WorkStationId]) references [CNF_WorkStation] ([WorkstationId]) 
Alter table [CNF_PromotionAssociation] add constraint fkPromotionAssociation_OpArea   foreign key([OperatingAreaId]) references [CNF_OperatingArea] ([OperatingAreaId]) 
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.357</SQLVERSION>
			<RMTRACKLINK>866</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>CNF_Promotion=PromotionId
CNF_PromotionValidity=PromotionValidityId
CNF_PromotionAssociation=PromotionAssociationId
CNF_PromotionItem=PromotionItemId
CNF_PromotionProduct=PromotionProductId
DATA_TransactionItemPromotion=TransactionItemPromotionId
DATA_TransactionItem=ItemId
DATA_SaleItem=SaleItemID</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>       
Create table [CNF_Promotion] (
	[PromotionId] Integer Identity(1,1) NOT NULL,
	[Description] Nvarchar(30) NULL,
	[Active] Smallint NOT NULL,
	[Code] Nvarchar(10) NULL,
	[Notes] Text NULL,
	[PromotionType] Smallint NULL,
Primary Key  ([PromotionId])
) 

Create table [CNF_PromotionValidity] (
	[PromotionValidityId] Integer Identity(1,1) NOT NULL,
	[PromotionId] Integer NOT NULL,
	[FromDate] Smalldatetime NOT NULL,
	[ToDate] Smalldatetime NULL,
	[Sunday] Smallint NULL,
	[Monday] Smallint NULL,
	[Tuesday] Smallint NULL,
	[Wednesday] Smallint NULL,
	[Thursday] Smallint NULL,
	[Friday] Smallint NULL,
	[Saturday] Smallint NULL,
	[FromTime] Datetime NULL,
	[ToTime] Datetime NULL,
Primary Key  ([PromotionValidityId])
) 

Create table [CNF_PromotionAssociation] (
	[PromotionAssociationId] Integer Identity(1,1) NOT NULL,
	[PromotionId] Integer NOT NULL,
	[SiteId] Integer NOT NULL,
	[OperatingAreaId] Integer NOT NULL,
	[WorkstationId] Integer NOT NULL,
	[Allow] Smallint NULL,
	[ClientCategoryId] Varchar(32) NULL,
	[CliendId] Integer NULL,
Primary Key  ([PromotionAssociationId])
) 

Create table [CNF_PromotionItem] (
	[PromotionItemId] Integer Identity(1,1) NOT NULL,
	[DiscountPerc] Float NULL,
	[DiscountForfait] Float NULL,
	[Quantity] Integer NOT NULL,
	[MaxQty] Integer NULL,
	[PromotionId] Integer NOT NULL,
Primary Key  ([PromotionItemId])
) 

Create table [CNF_PromotionProduct] (
	[PromotionProductId] Integer Identity(1,1) NOT NULL,
	[MatrixCellId] Integer NOT NULL,
	[PromotionItemId] Integer NOT NULL,
Primary Key  ([PromotionProductId])
) 

Create table [DATA_TransactionItemPromotion] (
	[TransactionItemPromotionId] Integer Identity(1,1) NOT NULL,
	[TransactionItemId] Integer NOT NULL,
	[PromotionItemId] Integer NOT NULL,
	[Quantity] Integer NULL,
	[DiscountPerc] Float NULL,
	[DiscountForfait] Money NULL,
	[DiscountTot] Money NULL,
Primary Key  ([TransactionItemPromotionId])
) 


Alter table [CNF_PromotionValidity] add  foreign key([PromotionId]) references [CNF_Promotion] ([PromotionId]) 
Alter table [CNF_PromotionAssociation] add  foreign key([PromotionId]) references [CNF_Promotion] ([PromotionId]) 
Alter table [CNF_PromotionItem] add  foreign key([PromotionId]) references [CNF_Promotion] ([PromotionId]) 
Alter table [CNF_PromotionProduct] add  foreign key([PromotionItemId]) references [CNF_PromotionItem] ([PromotionItemId]) 
Alter table [DATA_TransactionItemPromotion] add  foreign key([PromotionItemId]) references [CNF_PromotionItem] ([PromotionItemId]) 

Alter table [CNF_PromotionAssociation] add  foreign key([SiteId]) references [CNF_Site] ([SiteId]) 
Alter table [CNF_PromotionAssociation] add  foreign key([WorkStationId]) references [CNF_WorkStation] ([WorkstationId]) 
Alter table [CNF_PromotionAssociation] add  foreign key([OperatingAreaId]) references [CNF_OperatingArea] ([OperatingAreaId]) 

Alter Table DATA_TransactionItem Drop column OfferId;

Alter Table DATA_TransactionItem Add Discount Money Not Null Default 0;
Alter Table DATA_TransactionItem Add QtyUsedForPromotion Money Not Null Default 0;

Alter Table DATA_SaleItem Drop Column OfferId;

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.356</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>CNF_Seat
  add field BookingReference</REASON>
			<TABLENAMES>CNF_Seat=SeatId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_Seat
  add BookingReference varchar(38) null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.355</SQLVERSION>
			<RMTRACKLINK>1053</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>CNF_User=UserId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table cnf_user drop column [HystoricalPsw];   
alter table cnf_user add  [HystoricalPsw] text;
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.354</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>CNF_matrixCell
0) add field sold not null
1) set value to the field
2) Set sold as not null</REASON>
			<TABLENAMES>CNF_MatrixCell=MatrixCellId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_MatrixCell
  add Sold smallint default 0 not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_MatrixCell 
set CNF_MatrixCell.Sold =1
where CNF_MatrixCell.MatrixCellId in (select DATA_SaleItem.MatrixCellId  from DATA_SaleItem)
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.353</SQLVERSION>
			<RMTRACKLINK>1053</RMTRACKLINK>
			<REASON>Add field to store historical password</REASON>
			<TABLENAMES>CNF_User=UserId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE CNF_USER ADD HystoricalPsw VarChar(100);
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.352</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Fix error in previous patch</REASON>
			<TABLENAMES>CNF_CostCenter=CostCenterId</TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.351</SQLVERSION>
			<RMTRACKLINK>900</RMTRACKLINK>
			<REASON>REmoving columns
			</REASON>
			<TABLENAMES>CNF_CostCenter=CostCenterId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table cnf_costcenter drop column Percentage;
alter table cnf_costcenter drop column Decimals;
alter table cnf_costcenter drop column Rounding;
alter table cnf_costcenter drop column costcenteroption;
alter table cnf_costcenter drop column fixedamount;
alter table cnf_costcenter drop column CostCenterType;


				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.350</SQLVERSION>
			<RMTRACKLINK>900</RMTRACKLINK>
			<REASON>Adding Autoinc key</REASON>
			<TABLENAMES>CNF_CostCenter_Validity=CostCenterValidityId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>drop table CNF_COSTCENTER_VALIDITY;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_CostCenter_Validity] (
	[CostCenterValidityId] Integer NOT NULL UNIQUE IDENTITY (1,1),
	[CostCenterId] Integer NOT NULL,
	[MatrixCellId] Integer NOT NULL,
	[FromDate] Datetime NOT NULL,
	[ToDate] Datetime NOT NULL,
	[Price] Float NULL,
	[Percentage] Float NULL,
	[RemaningValues] Bit NULL,
Primary Key  ([CostCenterValidityId])
) 


				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> Alter table [CNF_CostCenter_Validity] add  foreign key([CostCenterId]) references [CNF_CostCenter] ([CostCenterId]) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_CostCenter_Validity] add  foreign key([MatrixCellId]) references [CNF_MatrixCell] ([MatrixCellId]) 
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.349</SQLVERSION>
			<RMTRACKLINK>1077</RMTRACKLINK>
			<REASON>CNF_MatrixSheet
1)add field Enabled small int not null</REASON>
			<TABLENAMES>CNF_MatrixSheet=MatrixSheetId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_MatrixSheet
  add Enabled smallint default 1 not null;
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ettore Bottega</ADDEDBY>
			<SQLVERSION>1.348</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Removed FK AccountId from DATA_SurveyItem</REASON>
			<TABLENAMES>DATA_SurveyItem=SurveyItemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>declare @foreign_key_name nvarchar(max),
@dropstmt nvarchar(max);

--Search for the name of Foreign Key
    select @foreign_key_name = f.name
      from sys.foreign_keys AS f
inner join sys.foreign_key_columns AS fc 
        on f.object_id = fc.constraint_object_id 
     where f.parent_object_id = object_id(N'[dbo].[DATA_SurveyItem]')
       and f.referenced_object_id = object_id(N'[dbo].[DATA_Account]')
       and COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'AccountId';

--If found delete it
if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[DATA_SurveyItem] DROP CONSTRAINT [' + @foreign_key_name + ']';
  execute sp_executesql @dropstmt
end;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_SurveyItem
drop column AccountId
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.347</SQLVERSION>
			<RMTRACKLINK>900</RMTRACKLINK>
			<REASON>Adding cost center validity to matrix cell</REASON>
			<TABLENAMES>CNF_CostCenter_Validity=CostCenterValidityId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_CostCenter_Validity] (
	[CostCenterValidityId] Integer NOT NULL UNIQUE,
	[CostCenterId] Integer NOT NULL,
	[MatrixCellId] Integer NOT NULL,
	[FromDate] Datetime NOT NULL,
	[ToDate] Datetime NOT NULL,
	[Price] Float NULL,
	[Percentage] Float NULL,
	[RemaningValues] Bit NULL,
Primary Key  ([CostCenterValidityId])
) 


				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_CostCenter_Validity] add  foreign key([CostCenterId]) references [CNF_CostCenter] ([CostCenterId]) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_CostCenter_Validity] add  foreign key([MatrixCellId]) references [CNF_MatrixCell] ([MatrixCellId]) 
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ettore Bottega</ADDEDBY>
			<SQLVERSION>1.346</SQLVERSION>
			<RMTRACKLINK>887</RMTRACKLINK>
			<REASON>- Add field Enabled to CNF_Survey
- Set SurveyName NOT NULL</REASON>
			<TABLENAMES>CNF_Survey=SurveyId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Survey
  add Enabled Smallint NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_Survey
  set Enabled=1
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Survey
  alter column Enabled smallint not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_Survey
  set SurveyName = 'New Survey'   
  where SurveyName is null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Survey
  alter column SurveyName Nvarchar(100) NOT NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.345</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>CNF_DmgCategory
[0] add field linkedDmgCat</REASON>
			<TABLENAMES>CNF_DmgCategory=DmgCategoryId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table CNF_DmgCategory
  add LinkedDmgCat integer null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ettore Bottega</ADDEDBY>
			<SQLVERSION>1.344</SQLVERSION>
			<RMTRACKLINK>887</RMTRACKLINK>
			<REASON>Create tables CNF_Survey, DATA_SurveyItem</REASON>
			<TABLENAMES>CNF_Survey=SurveyId
DATA_SurveyItem=SurveyItemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_Survey] (
	[SurveyId] Integer Identity(1,1) NOT NULL UNIQUE,
	[DmgCategoryId] Integer NOT NULL,
	[SurveyType] Smallint NOT NULL,
	[SurveyName] Nvarchar(100) NULL,
	[Frequency] Integer NULL,
Primary Key  ([SurveyId])
) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Survey] add  foreign key([DmgCategoryId]) references [CNF_DmgCategory] ([DmgCategoryId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [DATA_SurveyItem] (
	[SurveyItemId] Integer Identity(1,1) NOT NULL UNIQUE,
	[SurveyId] Integer NOT NULL,
	[EntityType] Smallint NOT NULL,
	[EntityId] Integer NOT NULL,
	[AccountId] Integer NOT NULL,
	[InsUserId] Integer NOT NULL,
	[InsWorkstationId] Integer NOT NULL,
	[InsDateTime] Datetime NOT NULL,
Primary Key  ([SurveyItemId])
) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_SurveyItem] add  foreign key([InsWorkstationId]) references [CNF_Workstation] ([WorkstationId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_SurveyItem] add  foreign key([InsUserId]) references [CNF_User] ([UserId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_SurveyItem] add  foreign key([AccountId]) references [DATA_Account] ([AccountId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_SurveyItem] add  foreign key([SurveyId]) references [CNF_Survey] ([SurveyId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ettore Bottega</ADDEDBY>
			<SQLVERSION>1.343</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Sets by default the DataType to 1 for the CNF_Right items which have DataType = 0, but have DATA_Right configured.
This happens mainly for right "EnabledCreditPaymentMethods"</REASON>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_Right 
   set DataType = 1 
 where RightId in (
           select DR.RightId 
             from DATA_Right DR 
       inner join CNF_Right CR on 
                DR.RightID = CR.Rightid and 
                CR.DataType = 0
)
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Saverio Pangallo</ADDEDBY>
			<SQLVERSION>1.342</SQLVERSION>
			<RMTRACKLINK>988</RMTRACKLINK>
			<REASON>Rename DATA_OfflineUpdate to OFF_Update
Rename DATA_OfflineUpload to OFF_Upload
Create Table OFF_TckValidity
Rename DATA_OfflineTicketUsage to OFF_TicketUsage</REASON>
			<TABLENAMES>OFF_Update=UpdateId
OFF_Upload=UploadId
OFF_TckValidity=TckValidityId
OFF_TicketUsage=TicketUsageId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>declare @foreign_key_name nvarchar(max),
@dropstmt nvarchar(max);

--Search for the name of Foreign Key
select @foreign_key_name = f.name
from sys.foreign_keys AS f
inner join sys.foreign_key_columns AS fc 
on  f.object_id = fc.constraint_object_id 
where  f.parent_object_id = object_id(N'[dbo].[DATA_OfflineUpdate]')
and  f.referenced_object_id = object_id(N'[dbo].[CNF_Workstation]')
and COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'WorkstationId';

--If found delete it
if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[DATA_OfflineUpdate] DROP CONSTRAINT [' + @foreign_key_name + ']';
  execute sp_executesql @dropstmt
end;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>declare @foreign_key_name nvarchar(max),
@dropstmt nvarchar(max);

--Search for the name of Foreign Key
select @foreign_key_name = f.name
from sys.foreign_keys AS f
inner join sys.foreign_key_columns AS fc 
on  f.object_id = fc.constraint_object_id 
where  f.parent_object_id = object_id(N'[dbo].[DATA_OfflineUpdate]')
and  f.referenced_object_id = object_id(N'[dbo].[CNF_User]')
and COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'UserId';

--If found delete it
if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[DATA_OfflineUpdate] DROP CONSTRAINT [' + @foreign_key_name + ']';
  execute sp_executesql @dropstmt
end;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Drop table DATA_OfflineUpdate
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [OFF_Update] (
	[UpdateId] Integer Identity(1,1) NOT NULL,
	[LastUpdate] Datetime NOT NULL,
	[WorkstationId] Integer NOT NULL,
	[UserId] Integer NOT NULL,
Primary Key  ([UpdateId])
) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [OFF_Update] add  foreign key([WorkstationId]) references [CNF_Workstation] ([WorkstationId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [OFF_Update] add  foreign key([UserId]) references [CNF_User] ([UserId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Drop table DATA_OfflineUpload
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [OFF_Upload] (
	[UploadId] Integer Identity(1,1) NOT NULL,
	[TableName] Varchar(100) NOT NULL,
	[FieldName] Varchar(100) NOT NULL,
	[LocalId] Integer NOT NULL,
	[MainId] Integer NOT NULL,
Primary Key  ([UploadId])
) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Drop table DATA_OfflineTicketUsage
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [OFF_TckValidity] (
	[TckValidityId] Integer Identity(1,1) NOT NULL,
	[IdentifierCode] Varchar(30) NOT NULL,
	[MatrixCellId] Integer NULL,
	[ValidityXML] Ntext NULL,
Primary Key  ([TckValidityId])
) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [OFF_TicketUsage] (
	[TicketUsageId] Integer Identity(1,1) NOT NULL,
	[TckValidityId] Integer NOT NULL,
	[AccessConfigurationId] Integer NOT NULL,
	[WorkstationId] Integer NOT NULL,
	[GateId] Integer NOT NULL,
	[PerformanceId] Integer NULL,
	[UsageDate] Datetime NOT NULL,
	[UsageType] Smallint NOT NULL,
	[ValidateResult] Smallint NOT NULL,
Primary Key  ([TicketUsageId])
) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> Alter table [OFF_TicketUsage] add  foreign key([TckValidityId]) references [OFF_TckValidity] ([TckValidityId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Saverio Pangallo</ADDEDBY>
			<SQLVERSION>1.341</SQLVERSION>
			<RMTRACKLINK>988</RMTRACKLINK>
			<REASON>FKs removed from Data_OfflineTicketUsage</REASON>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>declare @foreign_key_name nvarchar(max),
@dropstmt nvarchar(max);

--Search for the name of Foreign Key
select @foreign_key_name = f.name
from sys.foreign_keys AS f
inner join sys.foreign_key_columns AS fc 
on  f.object_id = fc.constraint_object_id 
where  f.parent_object_id = object_id(N'[dbo].[DATA_OfflineTicketUsage]')
and  f.referenced_object_id = object_id(N'[dbo].[ADM_Gate]')
and COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'GateId';

--If found delete it
if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[DATA_OfflineTicketUsage] DROP CONSTRAINT [' + @foreign_key_name + ']';
  execute sp_executesql @dropstmt
end;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>declare @foreign_key_name nvarchar(max),
@dropstmt nvarchar(max);

--Search for the name of Foreign Key
select @foreign_key_name = f.name
from sys.foreign_keys AS f
inner join sys.foreign_key_columns AS fc 
on  f.object_id = fc.constraint_object_id 
where  f.parent_object_id = object_id(N'[dbo].[DATA_OfflineTicketUsage]')
and  f.referenced_object_id = object_id(N'[dbo].[CNF_Workstation]')
and COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'WorkstationId';

--If found delete it
if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[DATA_OfflineTicketUsage] DROP CONSTRAINT [' + @foreign_key_name + ']';
  execute sp_executesql @dropstmt
end;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>declare @foreign_key_name nvarchar(max),
@dropstmt nvarchar(max);

--Ricerca del Nome della Foreign Key
select @foreign_key_name = f.name
from sys.foreign_keys AS f
inner join sys.foreign_key_columns AS fc 
on  f.object_id = fc.constraint_object_id 
where  f.parent_object_id = object_id(N'[dbo].[DATA_OfflineTicketUsage]')
and  f.referenced_object_id = object_id(N'[dbo].[ADM_AccessConfiguration]')
and COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'AccessConfigurationId';

--Se lo Trovo lo cancello
if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[DATA_OfflineTicketUsage] DROP CONSTRAINT [' + @foreign_key_name + ']';
  execute sp_executesql @dropstmt
end;
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.340</SQLVERSION>
			<RMTRACKLINK>940</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>DATA_Ticket=TicketId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>sp_rename 'Data_Ticket.TicketType', 'CreationType', 'COLUMN'
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>fabioradice</ADDEDBY>
			<SQLVERSION>1.339</SQLVERSION>
			<RMTRACKLINK>935</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>CNF_MATRIXCELL=matrixcellid</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table cnf_matrixcell add UseConfEntitlements smallint default 0 not null;
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Fabio</ADDEDBY>
			<SQLVERSION>1.338</SQLVERSION>
			<RMTRACKLINK>940</RMTRACKLINK>
			<REASON>Fix active from on existing external ticket generated from external range</REASON>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>update data_ticket
set activefrom = CAST(FLOOR(CAST(fencodedate AS float)) AS DateTime),
tickettype = 2
where 
saleitemid is null and
activefrom is null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Fabio</ADDEDBY>
			<SQLVERSION>1.337</SQLVERSION>
			<RMTRACKLINK>940</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>DATA_Ticket=TicketId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE Data_Ticket add TicketType smallint default 0 not null;
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Saverio Pangallo</ADDEDBY>
			<SQLVERSION>1.336</SQLVERSION>
			<RMTRACKLINK/>
			<REASON/>
			<TABLENAMES>DATA_OfflineTicketUsage=UsageId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [DATA_OfflineTicketUsage] (
	[UsageId] Integer Identity(1,1) NOT NULL,
	[AccessConfigurationId] Integer NOT NULL,
	[WorkstationId] Integer NOT NULL,
	[GateId] Integer NOT NULL,
	[PerformanceId] Integer NULL,
	[IdentifierCode] Varchar(100) NOT NULL,
	[UsageDate] Datetime NOT NULL,
	[UsageType] Smallint NOT NULL,
	[ValidateResult] Smallint NOT NULL,
Primary Key  ([UsageId])
) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_OfflineTicketUsage] add  foreign key([AccessConfigurationId]) references [ADM_AccessConfiguration] ([AccessConfigurationId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_OfflineTicketUsage] add  foreign key([WorkstationId]) references [CNF_Workstation] ([WorkstationId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_OfflineTicketUsage] add  foreign key([GateId]) references [ADM_Gate] ([GateId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.335</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add field</REASON>
			<TABLENAMES>DATA_TicketUsage=UsageId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT> alter table DATA_TicketUsage 
   add ValidationType Smallint Default 0 NOT NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.334</SQLVERSION>
			<RMTRACKLINK>1049</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>CNF_DmgCategory=DmgCategoryId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT> alter table CNF_DmgCategory 
   add DmgSubType smallInt null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>skhan</ADDEDBY>
			<SQLVERSION>1.333</SQLVERSION>
			<RMTRACKLINK>883</RMTRACKLINK>
			<REASON/>
			<TABLENAMES>CNF_SaleLimit=SaleLimitId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT> Create table [CNF_SaleLimit] (
	[SaleLimitId] Integer Identity(1,1) NOT NULL,
	[MatrixCellId] Integer NULL,
	[EntityID] Integer NOT NULL,
	[EntityTable] Smallint NOT NULL,
	[StartDateTime] Datetime NULL,
	[EndDateTime] Datetime NULL,
	[MaxAllowed] Integer NULL,
	[Used] Integer NULL,
	[Enabled] Smallint NULL,
Primary Key  ([SaleLimitId])
) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> Create UNIQUE Index [TicketAccount]  ON [CNF_SaleLimit] ([MatrixCellId] ,[EntityID] ,[EntityTable] ) 


				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.332</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>SIAE_Calendario
[0] create table

SIAE_Event
[1] set field Capacita null

SIAE_Category
[2] remove FK
[3] drop table
[4] recreate table
[5] add FK</REASON>
			<TABLENAMES>SIAE_Calendario=CalendarioId
SIAE_Event=EventId
SIAE_Category=SeatCategoryId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table SIAE_Calendario (
	CalendarioId Integer Identity(1,1) NOT NULL UNIQUE,
	Data Datetime NOT NULL,
Primary Key  (CalendarioId)
) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table SIAE_Event
  alter column capienza int null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>declare @foreign_key_name nvarchar(max),
@dropstmt nvarchar(max);

select @foreign_key_name = f.name
from sys.foreign_keys AS f
inner join sys.foreign_key_columns AS fc 
on  f.object_id = fc.constraint_object_id 
where  f.parent_object_id = object_id(N'[dbo].[SIAE_Category]')
and  f.referenced_object_id = object_id(N'[dbo].[CNF_Capacity]')
and COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = '[CapacityId]';

if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[SIAE_Category] DROP CONSTRAINT [' + @foreign_key_name + ']';
  execute sp_executesql @dropstmt
end;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Drop table SIAE_Category
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table SIAE_Category (
	Capienza Integer NULL,
	SeatCategoryId Integer NOT NULL UNIQUE,
	IvaOmaggiTitoli Float NOT NULL,
	LimiteOmaggi Integer NULL,
Primary Key  (SeatCategoryId)
) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table SIAE_Category 
add  foreign key(SeatCategoryId) references CNF_SeatCategory (SeatCategoryId) 
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.331</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>add table DATA_ShopCartItemSeat</REASON>
			<TABLENAMES>DATA_ShopCartItemSeat=ShopCartItemSeatId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [DATA_ShopCartItemSeat] (
	[ShopCartItemSeatId] Integer Identity(1,1) NOT NULL,
	[ShopCartItemId] Integer NOT NULL,
	[SeatId] Integer NOT NULL,
Primary Key  ([ShopCartItemSeatId])
) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_ShopCartItemSeat] add  foreign key([ShopCartItemId]) references [DATA_ShopCartItem] ([ShopCartItemId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_ShopCartItemSeat] add  foreign key([SeatId]) references [CNF_Seat] ([SeatId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.330</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>SIAE_Category
recreate a new table
[0] drop old table
[1] recreate old table
[2] add FK</REASON>
			<TABLENAMES>SIAE_Category=CapacityId
CNF_Capacity=CapacityId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Drop table SIAE_Category
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table SIAE_Category (
	OrdinePosto Integer NOT NULL,
	Capienza Integer,
	IvaOmaggiTitoli Float NOT NULL,
	CapacityId Integer NOT NULL UNIQUE,
	LimiteOmaggi Integer NULL,
Primary Key  (CapacityId)
) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table SIAE_Category 
add  foreign key(CapacityId) references CNF_Capacity (CapacityId)
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.329</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>- Add field CNF_Seat.CapacityId</REASON>
			<TABLENAMES>CNF_Seat=SeatId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Seat
add CapacityId int not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Seat] add  foreign key([CapacityId]) references [CNF_Capacity] ([CapacityId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.328</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>- Remove references to CNF_SeatCategory and CNF_SpaceStructure
- Add reference to CNF_Capacity
- Add fields: ReferenceTable and ReferenceId</REASON>
			<TABLENAMES>CNF_Seat=SeatId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>delete from CNF_Seat
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @foreign_key_name nvarchar(max);
DECLARE @dropstmt nvarchar(max);

SELECT  @foreign_key_name = f.name
  FROM sys.foreign_keys AS f
 INNER JOIN sys.foreign_key_columns AS fc 
    ON f.object_id = fc.constraint_object_id 
 WHERE f.parent_object_id = object_id(N'[dbo].[CNF_Seat]')
   AND f.referenced_object_id = object_id(N'[dbo].[CNF_SeatCategory]')
   AND COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'SeatCategoryId';

if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].CNF_Seat DROP CONSTRAINT [' + @foreign_key_name + ']';
  execute sp_executesql @dropstmt
end;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @foreign_key_name nvarchar(max);
DECLARE @dropstmt nvarchar(max);

SELECT  @foreign_key_name = f.name
  FROM sys.foreign_keys AS f
 INNER JOIN sys.foreign_key_columns AS fc 
    ON f.object_id = fc.constraint_object_id 
 WHERE f.parent_object_id = object_id(N'[dbo].[CNF_Seat]')
   AND f.referenced_object_id = object_id(N'[dbo].[CNF_SpaceStructure]')
   AND COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'SpaceStructureId';

if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].CNF_Seat DROP CONSTRAINT [' + @foreign_key_name + ']';
  execute sp_executesql @dropstmt
end;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Seat
drop column SeatCategoryId
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Seat
drop column SpaceStructureId
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Seat
add PerformanceId int null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Seat] add  foreign key([PerformanceId]) references [CNF_Performance] ([PerformanceId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Seat
add ReferenceTable smallint null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Seat
add ReferenceId int null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.327</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>SIAE_SiaeLog
[0] add Field IvaRateoIntrattenimento</REASON>
			<TABLENAMES>SIAE_SiaeLog=SiaeLogId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table SIAE_SiaeLog
  add IvaRateoIntrattenimenti float null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.326</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>SIAE_Riepiloghi
[0] add Field lastId </REASON>
			<TABLENAMES>SIAE_Riepiloghi=RiepilogoId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table SIAE_Riepiloghi
  add LastId integer null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Fabio</ADDEDBY>
			<SQLVERSION>1.325</SQLVERSION>
			<RMTRACKLINK>954</RMTRACKLINK>
			<REASON>GiftAid</REASON>
			<TABLENAMES>DATA_Sale=SaleId
DATA_SaleItem=SaleItemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter Table DATA_Sale add GiftAid smallint default 0;

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter Table DATA_SaleItem add GiftAid smallint default 0;
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Fabio</ADDEDBY>
			<SQLVERSION>1.324</SQLVERSION>
			<RMTRACKLINK>872</RMTRACKLINK>
			<REASON>PriceType added to matrix cell for manage variable price</REASON>
			<TABLENAMES>CNF_MatrixCell=matrixcellid</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_MatrixCell add PriceType smallint not null default 0;
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Fabio</ADDEDBY>
			<SQLVERSION>1.323</SQLVERSION>
			<RMTRACKLINK>926</RMTRACKLINK>
			<REASON>Translaction on matrix cell for Web</REASON>
			<TABLENAMES>CNF_MatrixCellTranslation=MatrixCellTranslationId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_MatrixCellTranslation] (
	[MatrixCellTranslationId] Integer Identity(1,1) NOT NULL,
	[LanguageId] Integer NOT NULL,
	[MatrixCellId] Integer NOT NULL,
	[ShortName] Varchar(50) NULL,
	[LongName] Varchar(250) NULL,
	[ShortDescription] Varchar(50) NULL,
	[LongDescription] Varchar(250) NULL,
Primary Key  ([MatrixCellTranslationId])  )


				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_MatrixCellTranslation] add  foreign key([MatrixCellId]) references [CNF_MatrixCell] ([MatrixCellId]) 


				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_MatrixCellTranslation] add  foreign key([LanguageId]) references [CNF_Language] ([LanguageId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.322</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>SIAE_SiaeLog</REASON>
			<TABLENAMES>SIAE_SiaeLog=SiaeLogId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT> Alter table SIAE_SiaeLog 
   add TipoSupporto int null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> Alter table SIAE_SiaeLog 
   drop column TipoSupporto 
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.321</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>SIAE_Supporti 
[0] drop old table
[1] create new table version

SIAE_SiaeLog
[2] add field smaterializzato

DATA_ExternalMediaType
[5] added new table
			</REASON>
			<TABLENAMES>SIAE_SiaeLog=SiaeLogId
CNF_ExternalMediaType=ExternalMediaTypeId
DATA_MediaIdentifier=MediaIdentifierId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>declare @foreign_key_name nvarchar(max),
@dropstmt nvarchar(max);

select @foreign_key_name = f.name
from sys.foreign_keys AS f
inner join sys.foreign_key_columns AS fc 
on  f.object_id = fc.constraint_object_id 
where  f.parent_object_id = object_id(N'[dbo].[SIAE_SiaeLog]')
and  f.referenced_object_id = object_id(N'[dbo].[SIAE_Supporti]')
and COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'SupportoId';

if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[SIAE_SiaeLog] DROP CONSTRAINT [' + @foreign_key_name + ']';
  execute sp_executesql @dropstmt
end;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>drop table SIAE_Supporti

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table SIAE_SiaeLog
  add Smaterializzato smallint null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update SIAE_SiaeLog
  set Smaterializzato = 0
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table SIAE_SiaeLog
  alter column Smaterializzato smallint not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table CNF_ExternalMediaType (
	ExternalMediaTypeId Integer Identity(1,1) NOT NULL,
	Code Nchar(8) not NULL,
        Name Nvarchar(50) not NULL,
Primary Key  (ExternalMediaTypeId)
) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table DATA_MediaIdentifier
  add ExternalMediaTypeId integer null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table DATA_MediaIdentifier 
  add  foreign key(ExternalMediaTypeId) references CNF_ExternalMediaType (ExternalMediaTypeId)
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table SIAE_SiaeLog
  drop column SupportoId  
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.320</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>SIAE_Supporti
Add table SIAE_Supporti</REASON>
			<TABLENAMES>SIAE_Supporti=SupportoId
SIAE_SiaeLog=SiaeLogId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table SIAE_Supporti (
	SupportoId Integer NOT NULL,
	SystemId Integer NOT NULL,
	Code Nchar(2) NOT NULL,
	Name Nvarchar(50) NOT NULL,
	ParentId Integer NOT NULL,
Primary Key  (SupportoId)
) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table SIAE_Supporti 
  add  foreign key(SystemId) references SIAE_System (SystemId) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter Table SIAE_SiaeLog
  add SupportoId integer null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table SIAE_SiaeLog
  add  foreign key(SupportoId) references SIAE_Supporti (SupportoId) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.319</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add field IsSeat to table ADM_AccessConfiguration</REASON>
			<TABLENAMES>ADM_AccessConfiguration=AccessConfigurationId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table ADM_AccessConfiguration
add IsSeat smallint null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update ADM_AccessConfiguration
set IsSeat=0
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table ADM_AccessConfiguration
alter column IsSeat smallint not null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.318</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add field Code to table CNF_SeatCategory</REASON>
			<TABLENAMES>CNF_SeatCategory=SeatCategoryId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_SeatCategory
add Code nvarchar(10) null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.317</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add field Code to table CNF_SpaceStructure</REASON>
			<TABLENAMES>CNF_SpaceStructure=SpaceStructureId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_SpaceStructure
add Code varchar(10) null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.316</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add field Enabled to table CNF_Seat</REASON>
			<TABLENAMES>CNF_Seat=SeatId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Seat
add Enabled smallint null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_Seat
set Enabled=1
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Seat
alter column Enabled smallint not null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.315</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>SIAE_System
[0] Added field CdCounter not null</REASON>
			<TABLENAMES>SIAE_System=SystemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table SIAE_System
  add CdCounter integer null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> update SIAE_System 
   set CdCounter = 0
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter Table SIAE_System
  alter column CdCounter integer not null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.314</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add table CNF_Seat and CNF_SeatPerformance</REASON>
			<TABLENAMES>CNF_Seat=SeatId
CNF_SeatPerformance=SeatPerformanceId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_Seat] (
	[SeatId] Integer Identity(1,1) NOT NULL,
	[SpaceStructureId] Integer NOT NULL,
	[SeatCategoryId] Integer NOT NULL,
	[EnvelopeId] Integer NOT NULL,
	[SeatMapId] Integer NOT NULL,
	[RowLabel] Nvarchar(30) NOT NULL,
	[ColLabel] Nvarchar(30) NOT NULL,
	[Weight] Integer NOT NULL,
	[FlagInfo] Smallint NOT NULL,
Primary Key  ([SeatId])
) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Seat] add  foreign key([SpaceStructureId]) references [CNF_SpaceStructure] ([SpaceStructureId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Seat] add  foreign key([SeatCategoryId]) references [CNF_SeatCategory] ([SeatCategoryId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Seat] add  foreign key([EnvelopeId]) references [CNF_Envelope] ([EnvelopeId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_SeatPerformance] (
	[SeatPerformanceId] Integer Identity(1,1) NOT NULL,
	[SeatId] Integer NOT NULL,
	[PerformanceId] Integer NOT NULL,
	[Status] Smallint NOT NULL,
Primary Key  ([SeatPerformanceId])
) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_SeatPerformance] add  foreign key([SeatId]) references [CNF_Seat] ([SeatId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_SeatPerformance] add  foreign key([PerformanceId]) references [CNF_Performance] ([PerformanceId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.313</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>SIAE_SiaeLog
[0] Add field IVA rateo null</REASON>
			<TABLENAMES>SIAE_SiaeLog=SiaeLogId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter Table SIAE_SiaeLog
  add IvaIntrattenimenti float null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.312</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>SIAE_SiaeLog
[0] add field DataEmissione date  null</REASON>
			<TABLENAMES>SIAE_SiaeLog=SiaeLogId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table SIAE_SiaeLog
  add DataEmissione datetime null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.311</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>SIAE_SiaeLog
[0] add field ProgressivoAbbonamento int</REASON>
			<TABLENAMES>SIAE_SiaeLog=SiaeLogId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table SIAE_SiaeLog
  add ProgressivoAbbonamento integer null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.310</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>[0] Remove Fk on SYstemIf SIAE_System
[1] reAdd Fk on SystemId CNF_System</REASON>
			<TABLENAMES>SIAE_Card=CardId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>declare @name nvarchar(32), 
@sql nvarchar(1000)

select @name = O.name 
from sysobjects AS O
left join sysobjects AS T
on O.parent_obj = T.id
where isnull(objectproperty(O.id,'IsMSShipped'),1) = 0
and O.name not like '%dtproper%'
and O.name not like 'dt[_]%'
and T.name = 'SIAE_Card'
and O.name like 'FK__SIAE_Card__Syste%'

if not @name is null
begin
select @sql = 'ALTER TABLE [SIAE_Card] DROP CONSTRAINT [' + @name + ']'
execute sp_executesql @sql
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [SIAE_Card] add  foreign key([SystemId]) references [CNF_System] ([SystemId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.309</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>SIAE_SiaeLog
[0] add field CodiceAbbonamento
[1] add field DataLimiteValidita</REASON>
			<TABLENAMES>SIAE_Siaelog=SiaeLogId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table SIAE_SiaeLog
  add CodiceAbbonamento varchar(8) null 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table SIAE_SiaeLog
  add DataLimiteValidita datetime null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.308</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>SIAE_Riepiloghi
[0] add field SystemId integer 
[1] set SystemIdValue 
[2] change SystemId in not null
[3] add FK on SIAE_System SystemId

SIAE_SiaeLog
[4] add field RateoIntrattenimenti float
[5] add field ImponibileIntrattenimenti float
			</REASON>
			<TABLENAMES>SIAE_Card=CardId
SIAE_Riepiloghi=RiepilogoId
SIAE_SiaeLog=SiaeLogId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table SIAE_Riepiloghi
  add SystemId integer null

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> Update SIAE_Riepiloghi
   set SystemId=(Select SystemId From SIAE_System) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table SIAE_Riepiloghi
  alter column SystemId integer not null  

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table SIAE_Riepiloghi 
  add  foreign key(SystemId) references SIAE_System (SystemId) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter Table SIAE_SiaeLog
  add RateoIntrattenimenti float
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter Table SIAE_SiaeLog
  add ImponibileIntrattenimenti float
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.307</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>SIAE_Log2Performance
  [0] set field PerformanceId as null

SIAE_System
  [2] remove PK constraint on SystemId
  [3] add field SystemId2
  [4] copy all values from SystemId to SystemId2
  [6] remove Uq constraint on SystemId
  [7] remove SystemId field
  [8] rename SystemId2 in SystemId
  [9] set SystemId not null
  [10] add Pk constaint on SystemId
 [11] add field InitializationDate
 [12] add field BackupEmail
 [13] add field ReportPath

SIAE_Producer
[134] add field SystemId null
[15] update SystemId value
[16] alter field SystemId not null
[17] add foreing key on systemId

SIAE_SiaeLog
[1] remove Fk on SystemId
[18] update SystemId field value
[19] add Fk on SystemId

SIAE_Card
[19] add field SystemId null
[20] set SystemId field value
[21] set field SystemId not null
[22] add FK on SystemId

SIAE_Event
[23] update EventType Field
[24] alter EventType field in smallint

			</REASON>
			<TABLENAMES>SIAE_Log2Performance=Log2PerformanceId
SIAE_System=SystemId
SIAE_Producer=ProducerId
SIAE_SiaeLog=SiaeLogId
SIAE_Event=EventId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table SIAE_Log2Performance
  alter column PerformanceId integer null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>declare @name nvarchar(32), 
@sql nvarchar(1000)

select @name = O.name 
from sysobjects AS O
left join sysobjects AS T
on O.parent_obj = T.id
where isnull(objectproperty(O.id,'IsMSShipped'),1) = 0
and O.name not like '%dtproper%'
and O.name not like 'dt[_]%'
and T.name = 'SIAE_SiaeLog'
and O.name like 'FK__SIAE_Siae__Syste%'

if not @name is null
begin
select @sql = 'ALTER TABLE [SIAE_SiaeLog] DROP CONSTRAINT [' + @name + ']'
execute sp_executesql @sql
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>declare @name nvarchar(32), 
@sql nvarchar(1000)

select @name = O.name 
from sysobjects AS O
left join sysobjects AS T
on O.parent_obj = T.id
where isnull(objectproperty(O.id,'IsMSShipped'),1) = 0
and O.name not like '%dtproper%'
and O.name not like 'dt[_]%'
and T.name = 'SIAE_System'
and O.name like 'PK__SIAE_Sys__%'

if not @name is null
begin
select @sql = 'ALTER TABLE SIAE_System DROP CONSTRAINT [' + @name + ']'
execute sp_executesql @sql
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table SIAE_System 
add SystemId2 int
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update SIAE_System
  set SystemID2 = (Select SystemId from CNF_System); 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>declare @name nvarchar(32), 
@sql nvarchar(1000)

select @name = O.name 
from sysobjects AS O
left join sysobjects AS T
on O.parent_obj = T.id
where isnull(objectproperty(O.id,'IsMSShipped'),1) = 0
and O.name not like '%dtproper%'
and O.name not like 'dt[_]%'
and T.name = 'SIAE_System'
and O.name like 'UQ__SIAE_Sys__%'

if not @name is null
begin
select @sql = 'ALTER TABLE [SIAE_System] DROP CONSTRAINT [' + @name + ']'
execute sp_executesql @sql
end

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table SIAE_System 
  drop column SystemId 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>EXEC sp_rename @objname = 'SIAE_System.SystemId2' 
    , @newname = 'SystemId' 
    , @objtype = 'COLUMN'; 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> alter table SIAE_System
alter column SystemId int NOT NULL; 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> ALTER TABLE SIAE_System 
  ADD PRIMARY KEY (SystemId);


				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table SIAE_System
  add InitializationDate varchar(100) null  
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> Alter table SIAE_System
  add backUpEmail Varchar(80) null  

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table SIAE_System
  add ReportPath varchar(100) null  
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table SIAE_Producer
  add SystemId integer null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> update SIAE_Producer
  set SystemId=(select SystemId from SIAE_System)
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table SIAE_Producer
  alter column SystemId integer not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table SIAE_Producer 
add  foreign key(SystemId) references SIAE_System (SystemId)
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>  update SIAE_SiaeLog
 set SystemId= (Select SystemId from SIAE_System)
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table SIAE_SiaeLog 
add  foreign key(SystemId) references SIAE_System (SystemId)
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> Alter table SIAE_Card
  add SystemId integer null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update SIAE_Card
  set SystemId=(select SystemId from CNF_System)
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table SIAE_Card
  alter column SystemId integer not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table SIAE_Card 
  add  foreign key(SystemId) references SIAE_System (SystemId) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Update SIAE_Event
  set EventType = (Select ItemId from CNF_Lookup  where LookuptableId=207 and LookUpCode=EventType)
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter Table SIAE_Event
  alter column EventType smallint not null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.306</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>SIAE_Log2Performance
0) added field EventId
1)Added FK on field EventId
Siae_Riepiloghi
1)Added Field Riepilogo not null</REASON>
			<TABLENAMES>SIAE_Riepiloghi=RiepilogoId
SIAE_Log2Performance=Log2PerformanceId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter Table SIAE_Log2Performance
  add EventId integer Null 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update SIAE_Log2Performance
  set EventId = (Select min(EventId) from SIAE_Event)

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter Table SIAE_Log2Performance
  alter column EventId integer not Null 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table SIAE_Log2Performance 
  add  foreign key([EventId]) references [SIAE_Event] ([EventId]) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table SIAE_Riepiloghi
  add Riepilogo Ntext null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update SIAE_Riepiloghi
  set Riepilogo = 'A'
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table SIAE_Riepiloghi
  alter column Riepilogo Ntext not null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.305</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Table SIAE_Riepiloghi
[0] add Field MailDisable</REASON>
			<TABLENAMES>SIAE_Riepiloghi=RiepilogoId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table SIAE_Riepiloghi
  add MailDisable smallint null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.304</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>[0] Added table SIAE_Riepiloghi</REASON>
			<TABLENAMES>SIAE_Riepiloghi=RiepilogoId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [SIAE_Riepiloghi] (
  [RiepilogoId] Integer Identity(1,1) NOT NULL UNIQUE,
  [Nome] Nvarchar(30) NOT NULL,
  [DataRiferimento] Datetime NULL,
  [Tipo] Smallint NOT NULL,
  [Stato] Smallint NOT NULL,
  [DataGenerazione] Datetime NOT NULL,
  [DataSalvataggio] Datetime NULL,
  [DataInvio] Datetime NULL,
  [Progressivo] Integer NOT NULL,
  [TipoFile] Smallint NOT NULL,
  [Sostituzione] Smallint NOT NULL,
Primary Key  ([RiepilogoId])
) 
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.303</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>[1] Create table SIAE_Log2Performance
[2] Add FK on SiaeLogId</REASON>
			<TABLENAMES>SIAE_Log2Performance=Log2PerformanceId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [SIAE_Log2Performance] (
	[Log2PerformanceId] Integer Identity(1,1) NOT NULL UNIQUE,
	[SiaeLogId] Integer NOT NULL,
	[PerformanceId] Integer NOT NULL,
Primary Key  ([Log2PerformanceId])
) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [SIAE_Log2Performance] add  foreign key([SiaeLogId]) references [SIAE_SiaeLog] ([SiaeLogId]) 
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>smcdonald</ADDEDBY>
			<SQLVERSION>1.302</SQLVERSION>
			<RMTRACKLINK>767</RMTRACKLINK>
			<REASON>Add the ability to record Controlled and Free Entry and Exit counts</REASON>
			<TABLENAMES>DATA_APTROTATIONCOUNT=AptRotationCountId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>exec sp_RENAME 'DATA_APTROTATIONCOUNT.EntryCount', 'ControlledEntriesCount', 'COLUMN'
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>exec sp_RENAME 'DATA_APTROTATIONCOUNT.ExitCount', 'ControlledExitsCount', 'COLUMN'

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE DATA_APTROTATIONCOUNT ADD FreeEntriesCount Integer
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> ALTER TABLE DATA_APTROTATIONCOUNT ADD FreeExitsCount Integer
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Update DATA_APTROTATIONCOUNT SET FreeEntriesCount = 0, FreeExitsCount = 0
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE DATA_APTROTATIONCOUNT ALTER COLUMN FreeEntriesCount Integer Not Null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE DATA_APTROTATIONCOUNT ALTER COLUMN FreeExitsCount Integer Not Null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.301</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Table SIAE_SiaeLog
[0-4] modify values from Char to Int according to Lk
[5] drop Constrain on field SIAE_SiaeLog
[6] alter table TipoTassazione in smallInt</REASON>
			<TABLENAMES>Siae_SiaeLog=SiaeLogId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>update SIAE_SiaeLog
  set TipoTassazione='0'
  where TipoTassazione='N' 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update SIAE_SiaeLog
  set TipoTassazione='1'
  where TipoTassazione='B' 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update SIAE_SiaeLog
  set TipoTassazione='2'
  where TipoTassazione='F' 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update SIAE_SiaeLog
  set TipoTassazione='3'
  where TipoTassazione='R' 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update SIAE_SiaeLog
  set TipoTassazione='0'
  where TipoTassazione not in ('R','N','F','B','0','1','2','3') 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>declare @name nvarchar(32), 
@sql nvarchar(1000)

SELECT  @name = O.name
  from sysobjects AS O
 left join sysobjects AS T 
    on O.parent_obj = T.id

 where isnull(objectproperty(O.id,'IsMSShipped'),1) = 0
and O.name not like '%dtproper%'
and O.name not like 'dt[_]%'
and T.name = 'Siae_SiaeLog'
and O.name like 'DF__Siae_Siae__TipoT%'


if not @name is null
begin
select @sql = 'ALTER TABLE [Siae_SiaeLog] DROP CONSTRAINT [' + @name + ']'
execute sp_executesql @sql
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> alter table Siae_SiaeLog
  alter column TipoTassazione smallint null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.300</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Table SIAE_SiaeLog
[0] field Operazione smallint
[1] field  OrdinePosto smallint
[2] field CausaleRiduziona smallint
[3] field TipoTitolo smallint</REASON>
			<TABLENAMES>Siae_SiaeLog=SiaeLogId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table Siae_SiaeLog
alter column Operazione smallint null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table Siae_SiaeLog
alter column OrdinePosto int null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table Siae_SiaeLog
alter column CausaleRiduzione smallint null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table Siae_SiaeLog
alter column TipoTitolo smallint null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.299</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add field SystemComponent to table CNF_AttributeTemplate</REASON>
			<TABLENAMES>CNF_AttributeTemplate=AttributeTemplateId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_AttributeTemplate
  add SystemComponent smallint null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_AttributeTemplate
set SystemComponent=0
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>
alter table CNF_AttributeTemplate
alter column SystemComponent smallint not null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.298</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>SIAE_SiaeLog
[0] Remove Foreign Key on ProducerId
[1] Set ProducerId field as null
[2] Remove Foreign Key on EventId
[3] Set EventId field as null
			</REASON>
			<TABLENAMES>SIAE_SiaeLog=SiaeLogId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT> DECLARE @foreign_key_name nvarchar(max);
DECLARE @dropstmt nvarchar(max);
SELECT @foreign_key_name = f.name
  FROM sys.foreign_keys AS f
 INNER JOIN sys.foreign_key_columns AS fc 
    ON f.object_id = fc.constraint_object_id 
 WHERE f.parent_object_id = object_id(N'[dbo].[SIAE_SiaeLog]')
   AND f.referenced_object_id = object_id(N'[dbo].[SIAE_Producer]')
   AND COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'ProducerId';

if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[SIAE_SiaeLog] DROP CONSTRAINT [' + @foreign_key_name + ']';
  execute sp_executesql @dropstmt
end;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter Table Siae_SiaeLog
  alter column ProducerId int null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @foreign_key_name nvarchar(max);
DECLARE @dropstmt nvarchar(max);
SELECT @foreign_key_name = f.name
  FROM sys.foreign_keys AS f
 INNER JOIN sys.foreign_key_columns AS fc 
    ON f.object_id = fc.constraint_object_id 
 WHERE f.parent_object_id = object_id(N'[dbo].[SIAE_SiaeLog]')
   AND f.referenced_object_id = object_id(N'[dbo].[SIAE_Event]')
   AND COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'EventId';

if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[SIAE_SiaeLog] DROP CONSTRAINT [' + @foreign_key_name + ']';
  execute sp_executesql @dropstmt
end;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter Table Siae_SiaeLog
  alter column EventId int null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.297</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>CNF_SYSTEM
[1] Add Field SiaeMode not null</REASON>
			<TABLENAMES>CNF_System=SystemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_System
  add SiaeMode smallint null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_System
set SiaeMode=0
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_System
alter column SiaeMode smallint not null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.296</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add fields RawPrice, ProductTaxType, TaxPackageId to table DATA_Ticket</REASON>
			<TABLENAMES>DATA_Ticket=TicketId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Ticket
add RawPrice float null, ProductTaxType smallint null, TaxPackageId int null 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_Ticket
set
  RawPrice=Price,  
  ProductTaxType=1 -- Tax Included    

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_Ticket
set TaxPackageId=TPId
from (
  select MatrixCellId as MCId, TaxPackageId as TPId  
  from CNF_MatrixCell
) XX
where MatrixCellId=MCId
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Ticket
alter column RawPrice float not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Ticket
alter column ProductTaxType smallint not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_Ticket] add  foreign key([TaxPackageId]) references [CNF_TaxPackage] ([TaxPackageId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.295</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add FieldRulesXML to CNF_DataMask</REASON>
			<TABLENAMES>CNF_DataMask=DataMaskId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>if col_length('CNF_DataMask','FieldRulesXML') is null
begin
  alter table CNF_DataMask
  add FieldRulesXML ntext
end
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.294</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>[0] Remove Index on DataOraEvento
[1] Remove Index on TicketId
[2] Remove field DataOraEvento
[3] Remove field TicketId Not Null
[4] Remove Index on FDataEmissione
[5] Remove field Codice Biglietto
[6] Remove field Capienza
[7] Remove field TipoGenere
[8] Remove index on IdSigillo
[9] Add field CardCounter Not Null
[10] Remove field CodiceCartaId
[11] Add  field VoidTicketId Null
[12] Remove field TitoloEventoId
[13] Remove field CFEmettitoreId
[14] Alter field Sigillo Not Null
[15] Alter field TipoTassazione Null
[16] Remove field ImpIntrattenimenti
[17] Remove field CausaleAnnullo
[18] Remove field Validita
[19] Remove field TipoEvento
[20] Remove field FDataEmissione
[21] Remove field IDSigillo
[22] Alter field FDataOraEmissione Not Null
			</REASON>
			<TABLENAMES>SIAE_SiaeLog=SiaeLogId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>drop index K_SLO_3 on SIAE_SiaeLog
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> drop index K_SLO_1 on SIAE_SiaeLog
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter Table SIAE_SiaeLog
  drop column DataOraEvento
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter Table SIAE_SiaeLog
  alter column TicketId int not Null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>drop index K_SLO_4 on SIAE_SiaeLog
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter Table SIAE_SiaeLog
  drop column CodiceBiglietto 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter Table SIAE_SiaeLog
  drop column Capienza
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter Table SIAE_SiaeLog
  drop column TipoGenere
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> drop index K_SLO_2 on SIAE_SiaeLog
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter Table SIAE_SiaeLog
  add CardCounter integer Not Null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter Table SIAE_SiaeLog
  drop column CodiceCartaId
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter Table SIAE_SiaeLog
  add VoidTicketId integer Null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter Table SIAE_SiaeLog
  drop column TitoloEventoId
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter Table SIAE_SiaeLog
  drop column CFEmettitoreId
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter Table SIAE_SiaeLog
  alter column Sigillo varchar(16) Not Null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter Table SIAE_SiaeLog
  alter column TipoTassazione char(1) Null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter Table SIAE_SiaeLog
  drop column ImpIntrattenimenti
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter Table SIAE_SiaeLog
  drop column CausaleAnnullo
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter Table SIAE_SiaeLog
  drop column Validita
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter Table SIAE_SiaeLog
  drop column TipoEvento
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter Table SIAE_SiaeLog
  drop column FDataEmissione
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter Table SIAE_SiaeLog
  drop column IdSigillo
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> Alter Table SIAE_SiaeLog
  alter column DataOraEmissione dateTime Not Null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.293</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>SIAE_Location
[0] modify field Denominazione
[1] modify field CodiceLocale
[2] modify field Indirizzo
[3] modify field Citta
[4] modify field Provincia
SIAE_Event
[5] modify field TipoGenere
[6] modify field Incidenza
[7] modify field EventType
[8] modify field TitoloEvento
[9] modify field Capienza
[10] modify field TipoCapienza
			</REASON>
			<TABLENAMES>SIAE_Location=LocationId
SIAE_Event=EventId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter Table SIAE_Location
  alter column Denominazione nvarChar(30) Not Null  

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter Table SIAE_Location
  alter column CodiceLocale nvarChar(13) Not Null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter Table SIAE_Location
  alter column Indirizzo nvarChar(100) Not Null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter Table SIAE_Location
  alter column Citta nvarChar(20) Not Null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter Table SIAE_Location
  alter column Provincia nvarChar(2) Not Null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter Table SIAE_Event
  alter column TipoGenere int Not Null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter Table SIAE_Event
  alter column Incidenza float Not Null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter Table SIAE_Event
  alter column EventType nvarChar(1) Not Null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter Table SIAE_Event
  alter column TitoloEvento nvarChar(100) Not Null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter Table SIAE_Event
  alter column Capienza int Not Null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter Table SIAE_Event
  alter column TipoCapienza smallInt Not Null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>lucafornaroli</ADDEDBY>
			<SQLVERSION>1.292</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>[1] field SystemCode Null (SIAE_CARD)
[2] remove foreign key on SIAE_SiaeLog
[3] drop SIAE_Producer
[4] create Table SIAE_Producer (New)
[5] recreate foreign key on SIAE_SiaeLog.
			</REASON>
			<TABLENAMES>SIAE_Card=CardId
SIAE_SiaeLog=SiaeLogId
SIAE_Producer=ProducerId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table SIAE_Card
Alter column SystemCode varchar(8) null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @foreign_key_name nvarchar(max);
DECLARE @dropstmt nvarchar(max);
SELECT @foreign_key_name = f.name
  FROM sys.foreign_keys AS f
 INNER JOIN sys.foreign_key_columns AS fc 
    ON f.object_id = fc.constraint_object_id 
 WHERE f.parent_object_id = object_id(N'[dbo].[SIAE_SiaeLog]')
   AND f.referenced_object_id = object_id(N'[dbo].[SIAE_Producer]')
   AND COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'ProducerId';

if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[SIAE_SiaeLog] DROP CONSTRAINT [' + @foreign_key_name + ']';
  execute sp_executesql @dropstmt
end;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>drop table SIAE_Producer
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [SIAE_Producer] (
	[ProducerId] Integer Identity(1,1) NOT NULL,
	[Description] Varchar(80) NULL,
	[CodiceFiscale] Varchar(16) NOT NULL,
	[ProducerType] Varchar(1) NOT NULL,
	[RagioneSociale] Varchar(50) NOT NULL,
	[Indirizzo] Varchar(80) NULL,
Primary Key  ([ProducerId])
) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>  Alter table [SIAE_SiaeLog] add  foreign key([ProducerId]) references [SIAE_Producer] ([ProducerId])
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.291</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>- Renames DrvEpsonOPOS.dll into DrvEpson.dll
- Renames DrvFerrariPark.dll into DrvFPK.dll</REASON>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_Driver
set DllName='DrvEpson.dll'
where DllName='DrvEpsonOPOS.dll'
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_Driver
set DllName='DrvFPK.dll'
where DllName='DrvFerrariPark.dll'
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.290</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>moves DrvRptViewers drivers into DrvCommon.dll</REASON>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_Driver
set DllName='DrvCommon.dll'
where DllName='DrvRptViewers.dll'
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.289</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Moves DrvPay* drivers into DrvCommon.dll</REASON>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_Driver
set DllName='DrvCommon.dll'
where DllName in ('DrvPayAuth.dll', 'DrvPayCommon.dll', 'DrvPayFlex.dll')
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.288</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>- [0] renames DrvDevCommon.dll into DrvCommon.dll
- [1] moves DrvJobCommon drivers into DrvCommon.dll</REASON>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_Driver
set DllName='DrvCommon.dll'
where DllName='DrvDevCommon.dll'
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_Driver
set DllName='DrvCommon.dll'
where DriverAK in ('TDrvJobInstallmentRenew', 'TDrvJobRegenerateEncryptionKeys', 'TDrvJobScheduledPayment', 'TDrvJobTicketExport')
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.287</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>- [0] Moves DrvJobAlta into DrvWDW
- [1] Renames TAptFocalPoint into TDrvAptFocalPoint</REASON>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_Driver
set DllName='DrvWDW.dll'
where DllName='DrvAlta.dll'
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_Driver
set DriverAK='TDrvAptFocalPoint'
where DriverAK='TAptFocalPoint'
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.286</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>move ObjType "ExternalCode1" to table DATA_Account</REASON>
			<TABLENAMES>DATA_Account=AccountId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Account
add ExternalCode1 nvarchar(30) null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_Account
set ExternalCode1=MaskData
from DATA_DmgData
where DmgType=1 and FKey=AccountId and ObjType=55
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>delete from DATA_DmgData
where DmgType=1 and ObjType=55
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create Index [IDX_Account_ExternalCode1]  ON [DATA_Account] ([ExternalCode1] ) 
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Saverio Pangallo</ADDEDBY>
			<SQLVERSION>1.285</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>- create table DATA_Biometric
-- add indexes to improve performace</REASON>
			<TABLENAMES>DATA_Biometric=BiometricId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table DATA_Biometric (
	BiometricId Integer Identity(1,1) NOT NULL,
	MediaId Integer NOT NULL,
	DriverId Integer NOT NULL,
	TransactionId Integer NOT NULL,
	EnrollmentDate Datetime NOT NULL,
	BiometricInfo Text NOT NULL,
Primary Key  (BiometricId))
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_Biometric] add  foreign key([MediaId]) references [DATA_Media] ([MediaId])

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_Biometric] add  foreign key([DriverId]) references [CNF_Driver] ([DriverId]) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create Index IDX_Biometric_Transaction  ON DATA_Biometric (TransactionId) 
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.284</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add field WorkstationId to table  SIAE_Card</REASON>
			<TABLENAMES>SIAE_Card=CardId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table SIAE_Card
add WorkstationId int null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [SIAE_Card] add  foreign key([WorkstationId]) references [CNF_Workstation] ([WorkstationId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.283</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>add field DATA_Counter.LastUpdateGuid</REASON>
			<TABLENAMES>DATA_Counter=CounterId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Counter
add LastUpdateGuid varchar(32) null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.282</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>add field DATA_PaymentFlex.Expiring</REASON>
			<TABLENAMES>DATA_PaymentFlex=PaymentId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_PaymentFlex
add Expiring smallint null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_PaymentFlex
set Expiring=0

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_PaymentFlex
alter column Expiring smallint not null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.281</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>removes driver DrvPrnEmail</REASON>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>delete from CNF_WorkstationDevice
where 
  DeviceId in (
    select DeviceId
    from CNF_Device
    where
      DriverId in (      
        select DriverId 
        from CNF_Driver        
        where FamilyType=138
      )  
  )

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>delete from CNF_DocTemplate2Device
where 
  DeviceId in (
    select DeviceId
    from CNF_Device
    where
      DriverId in (      
        select DriverId 
        from CNF_Driver        
        where FamilyType=138
      )  
  )
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>delete from CNF_Device
where 
  DriverId in (      
    select DriverId 
    from CNF_Driver        
    where FamilyType=138
  ) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>delete from CNF_Driver
where FamilyType=138

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.280</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>drop table DATA_DocBatch</REASON>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>insert into DATA_TriggerItem (
  TriggerItemStatus,
  TriggerType,
  EntityTable,
  EntityId,
  ListenerType,
  InsDateTime,
  InsWorkstationId,
  InsUserId,
  UpdDateTime,
  UpdWorkstationId,
  UpdUserId,
  CmpDateTime,
  CmpWorkstationId,
  CmpUserId,
  DocTemplateId
)
select
  (case BatchStatus          
    when 1 then 1    
    when 2 then 1    
    else 2    
  end) as TriggerItemStatus,  
  0 as TriggerType,  
  EntityTable,  
  EntityId,  
  1,  
  CreateDateTime,  
  CreateWorkstationId,  
  CreateUserId,
  ExecuteDateTime,  
  ExecuteWorkstationId,  
  ExecuteUserId,
  EndDateTime,  
  ExecuteWorkstationId,  
  ExecuteUserId,  
  DocTemplateId
from DATA_DocBatch
where BatchStatus&lt;=3
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>drop table DATA_DocBatch
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.279</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>drop table CNF_FlexCommunication and moves its records to CNF_Trigger</REASON>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>insert into CNF_Trigger (
  TriggerType,  
  ListenerType,  
  EntityTable,  
  EntityId,  
  DocTemplateId
)
select
  (FlexCommunicationEvent + 100) as TriggerType,
  1,
  165,
  FlexContractId,
  DocTemplateId  
from
  CNF_FlexCommunication
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>drop table CNF_FlexCommunication
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.278</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>- removes field ConfigXML from CNF_Trigger
- add field DocTemplateId to CNF_Trigger and DATA_TriggerItem</REASON>
			<TABLENAMES>CNF_Trigger=TriggerId
DATA_TriggerItem=TriggerItemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Trigger
drop column ConfigXML
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Trigger
add DocTemplateId int null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Trigger] add  foreign key([DocTemplateId]) references [CNF_DocTemplate] ([DocTemplateId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_TriggerItem
add DocTemplateId int null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_TriggerItem] add  foreign key([DocTemplateId]) references [CNF_DocTemplate] ([DocTemplateId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.277</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Clone SMTP rights to familytype=1</REASON>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_Right
set 
  SourceType=0,  
  SourceId=0
where
  RightId in (  
    select RightId    
    from CNF_Right    
    where FamilyType=138
  ) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_Right
set FamilyType=1  
where FamilyType=138
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.276</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>- add field CNF_FlexContract.ExpireDays
- add field DATA_PaymentFlex.ExpireDate</REASON>
			<TABLENAMES>CNF_FlexContract=FlexContractId
DATA_PaymentFlex=PaymentId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_FlexContract
add ExpireDays smallint null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_FlexContract
set ExpireDays=365
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_FlexContract
alter column ExpireDays smallint not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_PaymentFlex
add ExpireDate datetime null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_PaymentFlex
set ExpireDate=FPaymentDate+365
from (
  select   
    PaymentId as PID,
    FPaymentDate
  from  
    DATA_Payment       
  where  
    PaymentType=17
) P
where PaymentId=PID
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_PaymentFlex
alter column ExpireDate datetime not null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.275</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>remove field AutoExtend from tables CNF_FlexContract and DATA_PaymentFlex</REASON>
			<TABLENAMES>CNF_FlexContract=FlexContractId
DATA_PaymentFlex=PaymentId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_FlexContract 
drop column AutoExtend
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_PaymentFlex
drop column AutoExtend
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.274</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>add fields to table CNF_FlexContract
- AutoRenew
- RenewToFlexContractId
- AutoRenewCommDays

add fields to table DATA_PaymentFlex
- AutoRenew
- RenewFromPaymentId</REASON>
			<TABLENAMES>CNF_FlexContract=FlexContractId
DATA_PaymentFlex=PaymentId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_FlexContract
add AutoRenew smallint null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_FlexContract
add RenewToFlexContractId int null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_FlexContract
add AutoRenewCommDays smallint null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_FlexContract
set
  AutoRenew=0,  
  AutoRenewCommDays=0
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_FlexContract
alter column AutoRenew smallint not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_FlexContract
alter column AutoRenewCommDays smallint not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_FlexContract] add  foreign key([RenewToFlexContractId]) references [CNF_FlexContract] ([FlexContractId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_PaymentFlex
add AutoRenew smallint null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_PaymentFlex
add RenewFromPaymentId int null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_PaymentFlex
set AutoRenew=0
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_FlexContract
alter column AutoRenew smallint not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_PaymentFlex] add  foreign key([RenewFromPaymentId]) references [DATA_Payment] ([PaymentId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ettore Bottega</ADDEDBY>
			<SQLVERSION>1.273</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>-- create table DATA_MediaIdentifierBlackList
-- add indexes to improve performace</REASON>
			<TABLENAMES>DATA_MediaIdentifierBlackList=MediaBlackListId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table DATA_MediaIdentifierBlackList (
	MediaBlackListId Integer Identity(1,1) NOT NULL,
        IdentifierCode Nvarchar(100) NULL,
	DateFrom Datetime NULL,
	DateTo Datetime NULL,
	BlockCause Nvarchar(100) NULL
) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE NONCLUSTERED INDEX [IDX_BlackList_IdentifierCode] ON [dbo].[DATA_MediaIdentifierBlackList] ([IdentifierCode] ASC)
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Antonella Mura</ADDEDBY>
			<SQLVERSION>1.272</SQLVERSION>
			<RMTRACKLINK>154</RMTRACKLINK>
			<REASON>Update of CNF_Event's Store Procedures</REASON>
			<TABLENAMES>CNF_Event=EventId</TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ettore Bottega</ADDEDBY>
			<SQLVERSION>1.271</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add field EditLevel to CNF_DataMask</REASON>
			<TABLENAMES>CNF_DataMask=DataMaskId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_DataMask
  add EditLevel smallint
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Saverio Pangallo</ADDEDBY>
			<SQLVERSION>1.270</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>EX Update DATA_Transaction Revenue.... now 1.268</REASON>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Antonella Mura</ADDEDBY>
			<SQLVERSION>1.269</SQLVERSION>
			<RMTRACKLINK>154</RMTRACKLINK>
			<REASON>-Add field AccountId and the foreign key on CNF_Event
-Delete field ProducerId and the foreign key on CNF_Producer</REASON>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Event
add AccountId int null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Event] add  foreign key([AccountId]) references [DATA_Account] ([AccountId])
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @foreign_key_name nvarchar(max);
DECLARE @dropstmt nvarchar(max);

SELECT  @foreign_key_name = f.name
  FROM sys.foreign_keys AS f
 INNER JOIN sys.foreign_key_columns AS fc 
    ON f.object_id = fc.constraint_object_id 
 WHERE f.parent_object_id = object_id(N'[dbo].[CNF_Event]')
   AND f.referenced_object_id = object_id(N'[dbo].[CNF_Producer]')
   AND COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'ProducerId';

if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].CNF_Event DROP CONSTRAINT [' + @foreign_key_name + ']';
  execute sp_executesql @dropstmt
end;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> alter table CNF_event
drop column ProducerId
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ettore Bottega</ADDEDBY>
			<SQLVERSION>1.268</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Update DATA_Transaction Revenue</REASON>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_Transaction set Revenue=Revenue+Change
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.267</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Alter DATA_Ticket.SaleItemId to nullable</REASON>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Ticket
alter column SaleItemId int null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.266</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>add index IDX_Ledger_TransactionId</REASON>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[DATA_Ledger]') AND name = N'IDX_Ledger_TransactionId')
CREATE NONCLUSTERED INDEX [IDX_Ledger_TransactionId] ON [dbo].[DATA_Ledger] ([TransactionId] ASC)
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.265</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>- clean tables DATA_Lock and DATA_Session
- set all uncomleteted transaction to "2"
			</REASON>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>delete from DATA_Lock
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>delete from DATA_Session
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_Transaction
set Completed=2
where Completed=0
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.264</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>- remove index IDX_Ledger_TransactionId_LedgerType
- remove fields: SystemId, LedgerType, EntryQuantity, ReferenceAmount

from table DATA_Ledger</REASON>
			<TABLENAMES>DATA_Ledger=LedgerId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @foreign_key_name nvarchar(max);
DECLARE @dropstmt nvarchar(max);

SELECT @foreign_key_name = f.name
  FROM sys.foreign_keys AS f
 INNER JOIN sys.foreign_key_columns AS fc 
    ON f.object_id = fc.constraint_object_id 
 WHERE f.parent_object_id = object_id(N'[dbo].[DATA_Ledger]')
   AND f.referenced_object_id = object_id(N'[dbo].[CNF_System]')
   AND COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'SystemId';

if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[DATA_Ledger] DROP CONSTRAINT [' + @foreign_key_name + ']';
  execute sp_executesql @dropstmt
end;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DROP INDEX [IDX_Ledger_TransactionId_LedgerType] ON [dbo].[DATA_Ledger] 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Ledger
drop column SystemId
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Ledger
drop column LedgerType
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Ledger
drop column EntryQuantity
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Ledger
drop column ReferenceAmount
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.263</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Change DATA_Note.NoteType to LK[35]</REASON>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_Note
set 
  NoteType=
    (case NoteType
      when 1 then 161 -- sale
      when 3 then 160 -- trans
      when 4 then 159 -- ticket
      when 5 then 115 -- event
      when 6 then 126 -- perf
      when 7 then 197 -- account
      when 8 then 156 -- box
      when 9 then 170 -- flex
      when 10 then 186 -- voucher
      when 11 then 150 -- wks              
      else NoteType
    end)

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.262</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>- drops unique index on column CNF_MaskTableItem.ItemCode
- create unique index on fields MaskTableId+ItemCode</REASON>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CNF_MaskTableItem]') AND name = N'UQ__CNF_MaskTableIte__0A338187')
ALTER TABLE [dbo].[CNF_MaskTableItem] DROP CONSTRAINT [UQ__CNF_MaskTableIte__0A338187]
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create UNIQUE Index [UQ_MaskTableItem_Code]  ON [CNF_MaskTableItem] ([MaskTableId] ,[ItemCode] ) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.261</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>create table DATA_OfflineUpload</REASON>
			<TABLENAMES>DATA_OfflineUpload=OfflineUploadId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [DATA_OfflineUpload] (
	[OfflineUploadId] Integer Identity(1,1) NOT NULL,
	[TableName] Varchar(100) NOT NULL,
	[FieldName] Varchar(100) NOT NULL,
	[LocalId] Integer NOT NULL,
	[MainId] Integer NOT NULL,
Primary Key  ([OfflineUploadId])
) 
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.260</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>create DATA_OfflineUpdate table</REASON>
			<TABLENAMES>DATA_OfflineUpdate=OfflineUpdateId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [DATA_OfflineUpdate] (
	[OfflineUpdateId] Integer Identity(1,1) NOT NULL,
	[LastUpdate] Datetime NOT NULL,
	[WorkstationId] Integer NOT NULL,
	[UserId] Integer NOT NULL,
Primary Key  ([OfflineUpdateId])
) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_OfflineUpdate] add  foreign key([UserId]) references [CNF_User] ([UserId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_OfflineUpdate] add  foreign key([WorkstationId]) references [CNF_Workstation] ([WorkstationId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.259</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add field CNF_System.OffllineMode</REASON>
			<TABLENAMES>CNF_System=SystemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_System
add OfflineMode smallint null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_System
set OfflineMode=0
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_System
alter column OfflineMode smallint not null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Saverio Pangallo</ADDEDBY>
			<SQLVERSION>1.258</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add table DATA_AptRotationCount</REASON>
			<TABLENAMES>DATA_AptRotationCount=AptRotationCountId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [DATA_AptRotationCount] (
	[AptRotationCountId] Integer Identity(1,1) NOT NULL,
	[WorkstationId] Integer NOT NULL,
	[GateId] Integer NOT NULL,
	[SaveDateTime] Datetime NOT NULL,
	[EntryCount] Integer NOT NULL,
	[ExitCount] Integer NOT NULL,
Primary Key  ([AptRotationCountId])
) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_AptRotationCount] add  foreign key([GateId]) references [ADM_Gate] ([GateId])
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_AptRotationCount] add  foreign key([WorkstationId]) references [CNF_Workstation] ([WorkstationId])
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.257</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add optimization indexes</REASON>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE NONCLUSTERED INDEX [IDX_Ticket2Media_MediaId] ON [dbo].[DATA_Ticket2Media] ([MediaId] ASC)
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE NONCLUSTERED INDEX [IDX_SaleItem_SaleId] ON [dbo].[DATA_SaleItem] ([SaleId] ASC)
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE NONCLUSTERED INDEX [IDX_Ledger_TransactionId_LedgerType] ON [dbo].[DATA_Ledger] ([TransactionId] ASC, [LedgerType] ASC)
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.256</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add field DATA_Ticket.SaleItemId</REASON>
			<TABLENAMES>DATA_Ticket=TicketId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Ticket
add SaleItemId int null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_Ticket
set SaleItemId=SaleItem_Id
from 
  (  
    select 
      TicketId as Ticket_Id, 
      SaleItemId as SaleItem_Id    
    from DATA_SaleItem2Ticket     
    where OperationType=1
  ) SI2T                    
where TicketId=Ticket_Id
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_Ticket
set SaleItemId=SaleItem_Id
from
  (  
    select top 1 SaleItemId as SaleItem_Id    
    from DATA_SaleItem
  ) SI                    
where SaleItemId is null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Ticket
alter column SaleItemId int not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_Ticket] add  foreign key([SaleItemId]) references [DATA_SaleItem] ([SaleItemId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Saverio Pangallo</ADDEDBY>
			<SQLVERSION>1.255</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>UpdateDriversAK</REASON>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>update 
  CNF_Driver 
set 
  DriverAk='TDspDemo' 
where 
  DriverAk='DspDemo'
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update 
  CNF_Driver 
set 
  DriverAk='TDspEpsonSerial' 
where 
  DriverAk='DspEpson'
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update 
  CNF_Driver 
set 
  DriverAk='TDspEpsonOPOS' 
where 
  DriverAk='DspEpsonOPOS'
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update 
  CNF_Driver 
set 
  DriverAk='TDspFutaba' 
where 
  DriverAk='DspFutaba'
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update 
  CNF_Driver 
set 
  DriverAk='TPrnTckDemo' 
where 
  DriverAk='PrnTckDemo'
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update 
  CNF_Driver 
set 
  DriverAk='TPrnRecDemo' 
where 
  DriverAk='PrnRecDemo'
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update 
  CNF_Driver 
set 
  DriverAk='TPrnEpsonSerial' 
where 
  DriverAk='PrnEpsonSerial'
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update 
  CNF_Driver 
set 
  DriverAk='TPrnEpsonOPOS' 
where 
  DriverAk='PrnEpsonOPOS'
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update 
  CNF_Driver 
set 
  DriverAk='TPrnBocaSerial' 
where 
  DriverAk='PrnBocaSerial'
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update 
  CNF_Driver 
set 
  DriverAk='TPrnDataCard' 
where 
  DriverAk='PrnDataCard'
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update 
  CNF_Driver 
set 
  DriverAk='TEndEpsonSerial' 
where 
  DriverAk='EndEpsonSerial'
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update 
  CNF_Driver 
set 
  DriverAk='TEndorserEpsonOPOS' 
where 
  DriverAk='EndEpsonOPOS'
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update 
  CNF_Driver 
set 
  DriverAk='TDrvDLDragon' 
where 
  DriverAk='IoDLDragon'
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update 
  CNF_Driver 
set 
  DriverAk='TOtnVideoCapture' 
where 
  DriverAk='IoVideoCapture'
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update 
  CNF_Driver 
set 
  DriverAk='TDrvMOXA' 
where 
  DriverAk='IoMOXA'
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update 
  CNF_Driver 
set 
  DriverAk='TDrvAxessGCM' 
where 
  DriverAk='IoAxessGCM'
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update 
  CNF_Driver 
set 
  DriverAk='TRptViewHtml' 
where 
  DriverAk='RptViewHtml'
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update 
  CNF_Driver 
set 
  DriverAk='TRptViewPdf' 
where 
  DriverAk='RptViewPdf'
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update 
  CNF_Driver 
set 
  DriverAk='TRptViewWord' 
where 
  DriverAk='RptViewWord'
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update 
  CNF_Driver 
set 
  DriverAk='TRptViewDecisionCube' 
where 
  DriverAk='RptViewDecisionCube'
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update 
  CNF_Driver 
set 
  DriverAk='TRptHtmlBrowser' 
where 
  DriverAk='RptHtmlBrowser'
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update 
  CNF_Driver 
set 
  DriverAk='TMailSendMapi' 
where 
  DriverAk='MAPIMailSend'
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update 
  CNF_Driver 
set 
  DriverAk='TPayTpCash' 
where 
  DriverAk='Cash'
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update 
  CNF_Driver 
set 
  DriverAk='TPayTpCheque' 
where 
  DriverAk='Check'
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update 
  CNF_Driver 
set 
  DriverAk='TPayTpForeignCurr' 
where 
  DriverAk='ForeignCurr'
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update 
  CNF_Driver 
set 
  DriverAk='TPayTpTravellerCheque' 
where 
  DriverAk='TravelersCheck'
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update 
  CNF_Driver 
set 
  DriverAk='TPayTpVoucher' 
where 
  DriverAk='Voucher'
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update 
  CNF_Driver 
set 
  DriverAk='TPayTpAuth' 
where 
  DriverAk='CardsAuthorizator'
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update 
  CNF_Driver 
set 
  DriverAk='TPayTpFlex' 
where 
  DriverAk='Flex'
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update 
  CNF_Driver 
set 
  DriverAk='TPayTpMoneyCard' 
where 
  DriverAk='MoneyCard'
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update 
  CNF_Driver 
set 
  DriverAk='TPayTpCredit' 
where 
  DriverAk='Credit'
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.254</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Fix the "Credit" payment DriverAk</REASON>
			<TABLENAMES>CNF_Driver=DriverId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>declare @WrongDriverId int;
declare @RightDriverId int;

select @WrongDriverId=DriverId
from CNF_Driver
where DriverAK='Credit';

select @RightDriverId=DriverId
from CNF_Driver
where DriverAK='TPayTpCredit';

if (@WrongDriverId is not null) and (@RightDriverId is not null)
begin 
  update CNF_PaymentMethod
  set DriverId=@RightDriverId
  where DriverId=@WrongDriverId;

  delete from CNF_Driver
  where DriverId=@WrongDriverId;  
end;

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.253</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add field CNF_PaymentMethod.ReservationOnly</REASON>
			<TABLENAMES>CNF_PaymentMethod=PaymentMethodId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_PaymentMethod
add ReservationOnly smallint null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_PaymentMethod
set ReservationOnly=0
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_PaymentMethod
alter column ReservationOnly smallint not null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.252</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Replace MatrixCellId with TicketId in table DATA_MediaStoredValue</REASON>
			<TABLENAMES>DATA_MediaStoredValue=MediaStoredValueId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @foreign_key_name nvarchar(max);
DECLARE @dropstmt nvarchar(max);

SELECT @foreign_key_name = f.name
  FROM sys.foreign_keys AS f
 INNER JOIN sys.foreign_key_columns AS fc 
    ON f.object_id = fc.constraint_object_id 
 WHERE f.parent_object_id = object_id(N'[dbo].[DATA_MediaStoredValue]')
   AND f.referenced_object_id = object_id(N'[dbo].[CNF_MatrixCell]')
   AND COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'MatrixCellId';

if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[DATA_MediaStoredValue] DROP CONSTRAINT [' + @foreign_key_name + ']';
  execute sp_executesql @dropstmt
end;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_MediaStoredValue
drop column MatrixCellId
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>delete from DATA_MediaStoredValue
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_MediaStoredValue
add TicketId int not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_MediaStoredValue] add  foreign key([TicketId]) references [DATA_Ticket] ([TicketId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Saverio Pangallo</ADDEDBY>
			<SQLVERSION>1.251</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Alter column ParentWorkstationId nullable on table ADM_AccessPoint</REASON>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table ADM_AccessPoint
      alter column ParentWorkstationId Int null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.250</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add field MatrixCellId to table DATA_MediaStoredValue</REASON>
			<TABLENAMES>DATA_MediaStoredValue=MediaStoredValueId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>delete from DATA_MediaStoredValue
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_MediaStoredValue
add MatrixCellId int not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_MediaStoredValue] add  foreign key([MatrixCellId]) references [CNF_MatrixCell] ([MatrixCellId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Saverio Pangallo</ADDEDBY>
			<SQLVERSION>1.249</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Alter column AptNum to Varchar(10) on table ADM_AccessPoint</REASON>
			<TABLENAMES>ADM_AccessPoint=WorkstationId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table ADM_AccessPoint
      alter column AptNum Varchar(10) null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.248</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>replace ADM_AccessPoint.DriverId with DeviceId </REASON>
			<TABLENAMES>ADM_AccessPoint=WorkstationId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>insert into CNF_Device (
  DriverId,
  DeviceAk,
  Description,
  Enabled,
  SystemId,
  DefaultLevel
)
select
  DriverId,  
  cast(replace(newid(), '-', '') as varchar(32)),  
  Description,  
  1,  
  SystemId,  
  0
from CNF_Driver
where
  IconType=8 and DriverType=4
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table ADM_AccessPoint
add DeviceId int null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update ADM_AccessPoint
set DeviceId = DevId
from 
  (  
    select     
      DeviceId as DevId,      
      DriverId as DrvId      
    from CNF_Device 
  ) cii        
where DriverId=DrvId
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table ADM_AccessPoint
alter column DeviceId int not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @foreign_key_name nvarchar(max);
DECLARE @dropstmt nvarchar(max);

SELECT @foreign_key_name = f.name
  FROM sys.foreign_keys AS f
 INNER JOIN sys.foreign_key_columns AS fc 
    ON f.object_id = fc.constraint_object_id 
 WHERE f.parent_object_id = object_id(N'[dbo].[ADM_AccessPoint]')
   AND f.referenced_object_id = object_id(N'[dbo].[CNF_Driver]')
   AND COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'DriverId';

if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[ADM_AccessPoint] DROP CONSTRAINT [' + @foreign_key_name + ']';
  execute sp_executesql @dropstmt
end;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table ADM_AccessPoint
drop column DriverId
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [ADM_AccessPoint] add  foreign key([DeviceId]) references [CNF_Device] ([DeviceId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.247</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Alter field CNF_Producer.DmgCategoryId to nullable</REASON>
			<TABLENAMES>CNF_Producer=ProducerId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Producer
alter column DmgCategoryId int null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.246</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Alter field CNF_Location.DmgCategoryId to nullable</REASON>
			<TABLENAMES>CNF_Location=LocationId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Location
alter column DmgCategoryId int null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Antonella Mura</ADDEDBY>
			<SQLVERSION>1.245</SQLVERSION>
			<RMTRACKLINK>71</RMTRACKLINK>
			<REASON>table CNF_Location
- drop field City</REASON>
			<TABLENAMES>CNF_Location=LocationId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT> alter table CNF_Location
drop column City
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.244</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>rename field "SpaceStructureStatus" in "Enabled" in table CNF_SpaceStructure</REASON>
			<TABLENAMES>CNF_SpaceStructure=SpaceStructureId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_SpaceStructure
drop column SpaceStructureStatus
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_SpaceStructure
add Enabled smallint null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_SpaceStructure
set Enabled=1
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_SpaceStructure
alter column Enabled smallint not null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.243</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add field SpaceStructureStatus to table CNF_SpaceStructure</REASON>
			<TABLENAMES>CNF_SpaceStructure=SpaceStructureId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_SpaceStructure
add SpaceStructureStatus smallint null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_SpaceStructure
set SpaceStructureStatus=1
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_SpaceStructure
alter column SpaceStructureStatus smallint not null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ettore Bottega</ADDEDBY>
			<SQLVERSION>1.242</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>CNF_Scheduler.LastReference altered to ntext</REASON>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Scheduler
      alter column LastReference ntext
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Saverio Pangallo</ADDEDBY>
			<SQLVERSION>1.241</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>DATA_PaymentCard modified</REASON>
			<TABLENAMES>DATA_PaymentCard=PaymentId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_PaymentCard
drop column IssueNumber
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_PaymentCard
drop column CVV
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_PaymentCard
drop column CVVResultCode
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_PaymentCard
drop column SignatureMode
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_PaymentCard
drop column Holder
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_PaymentCard
add CHVerificationMode Smallint
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_PaymentCard
add SequenceNumber Int
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_PaymentCard
add RetrivialReference Varchar(15)
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_PaymentCard
add DevResponseCode Varchar(5)
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_PaymentCard
add DevRespMessage Varchar(30)
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Saverio Pangallo</ADDEDBY>
			<SQLVERSION>1.240</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Columnt Default level added to CNF_PaymentCard</REASON>
			<TABLENAMES>CNF_PaymentCard=PaymentCardId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_PaymentCard
add DefaultLevel int
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_PaymentCard
set DefaultLevel=0
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_PaymentCard
alter column DefaultLevel smallint not null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Saverio Pangallo</ADDEDBY>
			<SQLVERSION>1.239</SQLVERSION>
			<RMTRACKLINK/>
			<REASON/>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_Driver
set FamilyType=147
where DriverAk='TAptAxessGCM'
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.238</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add field SaveStoredValue to table DATA_Media</REASON>
			<TABLENAMES>DATA_Media=MediaId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Media
add SaveStoredValue smallint null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_Media
set SaveStoredValue=0
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Media
alter column SaveStoredValue smallint not null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Saverio Pangallo</ADDEDBY>
			<SQLVERSION>1.237</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>- Drop table DATA_MediaStoredValue
- Create table DATA_MediaStoredValue</REASON>
			<TABLENAMES>DATA_MediaStoredValue=MediaStoredValueId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>drop table DATA_MediaStoredValue
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [DATA_MediaStoredValue] (
	[MediaStoredValueId] Integer Identity(1,1) NOT NULL,
	[TransactionId] Integer NOT NULL,
	[MediaId] Integer NOT NULL,
	[Status] Smallint NOT NULL,
	[DeltaAmount] Float NOT NULL,
	[CompletionTS] Datetime NULL,
Primary Key  ([MediaStoredValueId])
)
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_MediaStoredValue] add  foreign key([TransactionId]) references [DATA_Transaction] ([TransactionId]) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_MediaStoredValue] add  foreign key([MediaId]) references [DATA_Media] ([MediaId]) 
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.236</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>table DATA_SaleItem
- drop field ParentId
- add field TicketId
- add field ItemTicketId</REASON>
			<TABLENAMES>DATA_SaleItem=SaleItemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @foreign_key_name nvarchar(max);
DECLARE @dropstmt nvarchar(max);

SELECT @foreign_key_name = f.name
  FROM sys.foreign_keys AS f
 INNER JOIN sys.foreign_key_columns AS fc 
    ON f.object_id = fc.constraint_object_id 
 WHERE f.parent_object_id = object_id(N'[dbo].[DATA_SaleItem]')
   AND f.referenced_object_id = object_id(N'[dbo].[DATA_SaleItem]')
   AND COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'SaleItemId';

if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[DATA_SaleItem] DROP CONSTRAINT [' + @foreign_key_name + ']';
  execute sp_executesql @dropstmt
end;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_SaleItem
drop column ParentId
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_SaleItem
add TicketId int null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_SaleItem
add ItemTicketId int null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_SaleItem] add  foreign key([TicketId]) references [DATA_Ticket] ([TicketId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_SaleItem] add  foreign key([ItemTicketId]) references [DATA_Ticket] ([TicketId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Saverio Pangallo</ADDEDBY>
			<SQLVERSION>1.235</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>- Create table DATA_MediaStoredValue</REASON>
			<TABLENAMES>DATA_MediaStoredValue=MediaStoredValueId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [DATA_MediaStoredValue] (
	[MediaStoredValueId] Integer NOT NULL,
	[TransactionId] Integer NOT NULL,
	[MediaId] Integer NOT NULL,
	[Status] Smallint NOT NULL,
	[DeltaAmount] Float NOT NULL,
	[CompletionTS] Datetime NULL,
Primary Key  ([MediaStoredValueId])
) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_MediaStoredValue] add  foreign key([TransactionId]) references [DATA_Transaction] ([TransactionId]) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_MediaStoredValue] add  foreign key([MediaId]) references [DATA_Media] ([MediaId]) 
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.234</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Rebuild indexes on table CNF_Right</REASON>
			<TABLENAMES>CNF_Right=RightId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>drop index Idx_Sort on CNF_Right
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>drop index Idx2 on CNF_Right
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create Index [IDX_CNF_Right_SortOrder]  ON [CNF_Right] ([SortOrder] ) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create UNIQUE Index [IDX_CNF_Right_RightAK]  ON [CNF_Right] ([FamilyType] ,[RightAK] ) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.233</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add field PrintOption to table DATA_SaleItem</REASON>
			<TABLENAMES>DATA_SaleItem=SaleItemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_SaleItem
add PrintOption smallint null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_SaleItem
set PrintOption=1
where ProductType=1
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_SaleItem
set PrintOption=4
where PrintOption is null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_SaleItem
alter column PrintOption smallint not null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.232</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Table DATA_Media
- Add field ExternalMedia
- Set field DocTemplateId to nullable

Table DATA_SaleItem
- Add field MediaId</REASON>
			<TABLENAMES>DATA_Media=MediaId
DATA_SaleItem=SaleItemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Media
add ExternalMedia smallint null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_Media
set ExternalMedia=0
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Media
alter column ExternalMedia smallint not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Media
alter column DocTemplateId int null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_SaleItem
add MediaId int null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_SaleItem] add  foreign key([MediaId]) references [DATA_Media] ([MediaId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.231</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add field DefaultMedia to table DATA_Ticket2Media</REASON>
			<TABLENAMES>DATA_Ticket2Media=Ticket2MediaId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Ticket2Media
add DefaultMedia smallint null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_Ticket2Media
set DefaultMedia=1
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Ticket2Media
alter column DefaultMedia smallint not null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.230</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>- drops field DATA_Ticket.Active
- modify VoidType codes for encoded tickets and medias</REASON>
			<TABLENAMES>DATA_Ticket=TicketId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_Ticket
set VoidType=VoidType+100
where VoidType&gt;0
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_Ticket
set VoidType=1
where VoidType=0 and Active=0
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Ticket
drop column Active
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_Media
set VoidType=VoidType+100
where VoidType&gt;0
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.229</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add fields 
- DATA_SaleItem.UnitRecharge
- DATA_TransactionItem.UnitRecharge</REASON>
			<TABLENAMES>DATA_SaleItem=SaleItemId
DATA_TransactionItem=ItemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_SaleItem
add UnitRecharge float null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_SaleItem
set UnitRecharge=0
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_SaleItem
alter column UnitRecharge float not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_TransactionItem
add UnitRecharge float null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_TransactionItem
set UnitRecharge=0
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_TransactionItem
alter column UnitRecharge float not null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.228</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add field DATA_AccountFinancial.AutoPayCredits</REASON>
			<TABLENAMES>DATA_AccountFinancial=AccountId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_AccountFinancial
add AutoPayCredits smallint null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_AccountFinancial
set AutoPayCredits=1
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_AccountFinancial
alter column AutoPayCredits smallint not null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.227</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Removes field Attrib3, FamilyType, DataType from table DATA_Right
Rename "Attrib1" in "DestId"
Rename "Attrib2" in "SourceId"</REASON>
			<TABLENAMES>DATA_Right=DataRightId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>drop index Idx1 on DATA_Right
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Right
drop column FamilyType
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Right
drop column Attrib3
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Right
drop column DataType
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Right
add SourceId int null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Right
add DestId int null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_Right
set SourceId=Attrib2, DestId=Attrib1  
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Right
drop column Attrib1
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Right
drop column Attrib2
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Right
alter column DestId int not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Right
alter column SourceId int not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create UNIQUE Index [IDX_DATA_Right]  ON [DATA_Right] ([RightId] ,[SourceType] ,[SourceId] ,[DestType] ,[DestId] ) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.226</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Makes the DATA_MediaIdentifier.IdentifierCode unique</REASON>
			<TABLENAMES>DATA_MediaIdentifier=MediaIdentifierId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_MediaIdentifier
set IdentifierCode='REPLACED_' + cast(MediaIdentifierId as varchar(max))
where 
  IdentifierCode in (
	select IdentifierCode
    from DATA_MediaIdentifier
    group by IdentifierCode
    having Count(*) &gt; 1
  ) and
  MediaIdentifierId not in (
	select Min(MediaIdentifierId)
    from DATA_MediaIdentifier
    group by IdentifierCode
    having Count(*) &gt; 1
  )
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>drop index IDX_MediaIdentifierCode on DATA_MediaIdentifier
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create UNIQUE Index [IDX_MediaIdentifierCode]  ON [DATA_MediaIdentifier] ([IdentifierCode] ) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.225</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Table DATA_Media
- Drop fields WalletKey, TableId
- Create field PrintDateTime

Table DATA_Transaction2Media
- Create field OperationType</REASON>
			<TABLENAMES>DATA_Media=MediaId
DATA_Transaction2Media=Transaction2MediaId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[DATA_Media]') AND name = N'IDX_MediaIdentifier_WalletKey')
drop index IDX_MediaIdentifier_WalletKey on DATA_Media
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Media
drop column WalletKey
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Media
drop column TableId
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Media
add PrintDateTime datetime null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Transaction2Media
add OperationType smallint null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_Transaction2Media
set OperationType=1
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Transaction2Media
alter column OperationType smallint not null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.224</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Change DATA_TicketUsage.WorkstationId foreign key, it used to refer to ADM_AccessPoint and is now changed to CNF_Workstation</REASON>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @foreign_key_name nvarchar(max);
DECLARE @dropstmt nvarchar(max);

SELECT @foreign_key_name = f.name
  FROM sys.foreign_keys AS f
 INNER JOIN sys.foreign_key_columns AS fc 
    ON f.object_id = fc.constraint_object_id 
 WHERE f.parent_object_id = object_id(N'[dbo].[DATA_TicketUsage]')
   AND f.referenced_object_id = object_id(N'[dbo].[ADM_AccessPoint]')
   AND COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'WorkstationId';

if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[DATA_TicketUsage] DROP CONSTRAINT [' + @foreign_key_name + ']';
  execute sp_executesql @dropstmt
end;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_TicketUsage] add  foreign key([WorkstationId]) references [CNF_Workstation] ([WorkstationId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.223</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>- Drop table DATA_TicketUsageExtError
- Creates table DATA_TicketUsageOption
- Drop fields (NumEntries, UsageAmount, TransactionId) from table DATA_TicketUsage
- Set fields (PerformanceId, GateId, AccessConfigurationId) to nullable on table DATA_TicketUsage</REASON>
			<TABLENAMES>DATA_TicketUsage=UsageId
DATA_TicketUsageOption=TicketUsageOptionId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>drop table DATA_TicketUsageExtError
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [DATA_TicketUsageOption] (
	[TicketUsageOptionId] Integer Identity(1,1) NOT NULL,
	[UsageId] Integer NOT NULL,
	[OptionType] Smallint NOT NULL,
	[OptionValue] Nvarchar(200) NOT NULL,
Primary Key  ([TicketUsageOptionId])
) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_TicketUsageOption] add  foreign key([UsageId]) references [DATA_TicketUsage] ([UsageId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @foreign_key_name nvarchar(max);
DECLARE @dropstmt nvarchar(max);

SELECT @foreign_key_name = f.name
  FROM sys.foreign_keys AS f
 INNER JOIN sys.foreign_key_columns AS fc 
    ON f.object_id = fc.constraint_object_id 
 WHERE f.parent_object_id = object_id(N'[dbo].[DATA_TicketUsage]')
   AND f.referenced_object_id = object_id(N'[dbo].[DATA_Transaction]')
   AND COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'TransactionId';

if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[DATA_TicketUsage] DROP CONSTRAINT [' + @foreign_key_name + ']';
  execute sp_executesql @dropstmt
end;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_TicketUsage
drop column NumEntries, UsageAmount, TransactionId
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_TicketUsage
alter column PerformanceId int null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_TicketUsage
alter column GateId int null  

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_TicketUsage
alter column AccessConfigurationId int null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Saverio Pangallo</ADDEDBY>
			<SQLVERSION>1.222</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Update Boca driver name</REASON>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_Driver
set DriverAk='TPrnBoca'
where DriverAk='TPrnBocaSerial'
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_Driver
set DllName='DrvPrnBoca.dll'
where DllName='DrvPrnBocaSerial.dll'
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.221</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>- Add field CNF_Performance.PerformanceCode
- Add table DATA_TicketUsageExtError</REASON>
			<TABLENAMES>CNF_Performance=PerformanceId
DATA_TicketUsageExtError=UsageId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Performance
add PerformanceCode nvarchar(100) null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [DATA_TicketUsageExtError] (
	[UsageId] Integer NOT NULL,
	[ErrorMessage] Nvarchar(100) NOT NULL,
Primary Key  ([UsageId])
) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_TicketUsageExtError] add  foreign key([UsageId]) references [DATA_TicketUsage] ([UsageId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.220</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add field DATA_Voucher.CreateDate</REASON>
			<TABLENAMES>DATA_Voucher=VoucherId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Voucher
add CreateDate datetime null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_Voucher
set CreateDate=GetDate()
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Voucher
alter column CreateDate datetime not null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.219</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add field DATA_PaymentCredit.EntityTable</REASON>
			<TABLENAMES>DATA_PaymentCredit=PaymentId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_PaymentCredit
add EntityTable smallint null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_PaymentCredit
set EntityTable=186
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_PaymentCredit
alter column EntityTable smallint not null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.218</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>- Add field AccountId to table DATA_PaymentCredit</REASON>
			<TABLENAMES>DATA_PaymentCredit=PaymentId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>delete from DATA_PaymentCredit
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_PaymentCredit
add AccountId int null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_PaymentCredit] add  foreign key([AccountId]) references [DATA_Account] ([AccountId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_PaymentCredit
alter column AccountId int not null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.217</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>- Drops table DATA_PaymentVoucher
- Create table DATA_PaymentCredit</REASON>
			<TABLENAMES>DATA_PaymentCredit=PaymentId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>drop table DATA_PaymentVoucher
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [DATA_PaymentCredit] (
	[PaymentId] Integer NOT NULL,
	[EntityId] Integer NOT NULL,
	[CreditStatus] Smallint NOT NULL,
	[DueDate] Datetime NULL,
	[SettleTransactionId] Integer NULL,
Primary Key  ([PaymentId])
) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_PaymentCredit] add  foreign key([PaymentId]) references [DATA_Payment] ([PaymentId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_PaymentCredit] add  foreign key([SettleTransactionId]) references [DATA_Transaction] ([TransactionId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.216</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add field DATA_PaymentVoucher.VoucherId</REASON>
			<TABLENAMES>DATA_PaymentVoucher=PaymentId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>delete from DATA_PaymentVoucher
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_PaymentVoucher
add VoucherId int not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_PaymentVoucher] add  foreign key([VoucherId]) references [DATA_Voucher] ([VoucherId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.215</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add field DATA_SaleItem.VoucherId</REASON>
			<TABLENAMES>DATA_SaleItem=SaleItemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_SaleItem
add VoucherId integer null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_SaleItem] add  foreign key([VoucherId]) references [DATA_Voucher] ([VoucherId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create Index [IDX_Voucher_VoucherCode]  ON [DATA_Voucher] ([VoucherCode] ) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.214</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>- removes field DATA_Account.PriceListId from </REASON>
			<TABLENAMES>DATA_Account=AccountId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>insert into DATA_AccountFinancial (
  AccountId,
  PriceListId
)
select 
  AccountId,
  PriceListId
from DATA_Account
where PriceListId is not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @foreign_key_name nvarchar(max);
DECLARE @dropstmt nvarchar(max);

SELECT @foreign_key_name = f.name
  FROM sys.foreign_keys AS f
 INNER JOIN sys.foreign_key_columns AS fc 
    ON f.object_id = fc.constraint_object_id 
 WHERE f.parent_object_id = object_id(N'[dbo].[DATA_Account]')
   AND f.referenced_object_id = object_id(N'[dbo].[CNF_PriceList]')
   AND COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'PriceListId';

if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[DATA_Account] DROP CONSTRAINT [' + @foreign_key_name + ']';
  execute sp_executesql @dropstmt
end;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Account
drop column PriceListId
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.213</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>- add table DATA_AccountFinancial</REASON>
			<TABLENAMES>DATA_AccountFinancial=AccountId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [DATA_AccountFinancial] (
	[AccountId] Integer NOT NULL,
	[PriceListId] Integer NULL,
	[TotalCreditAmount] Float NULL,
	[CreditDays] Smallint NULL,
	[CreditAmountPerTransaction] Float NULL,
	[CreditItemsPerTransaction] Smallint NULL,
Primary Key  ([AccountId])
) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_AccountFinancial] add  foreign key([AccountId]) references [DATA_Account] ([AccountId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_AccountFinancial] add  foreign key([PriceListId]) references [CNF_PriceList] ([PriceListId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.212</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>- Drop table CNF_VoucherTemplate
- Drop table DATA_IndividualVoucherItem
- Drop table DATA_IndividualVoucher
- Add table DATA_Voucher
- Add table DATA_VoucherItem</REASON>
			<TABLENAMES>DATA_Voucher=VoucherId
DATA_VoucherItem=VoucherItemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>drop table CNF_VoucherTemplate
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>drop table DATA_IndividualVoucherItem
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @foreign_key_name nvarchar(max);
DECLARE @dropstmt nvarchar(max);

SELECT @foreign_key_name = f.name
  FROM sys.foreign_keys AS f
 INNER JOIN sys.foreign_key_columns AS fc 
    ON f.object_id = fc.constraint_object_id 
 WHERE f.parent_object_id = object_id(N'[dbo].[DATA_PaymentVoucher]')
   AND f.referenced_object_id = object_id(N'[dbo].[DATA_IndividualVoucher]')
   AND COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'IndividualVoucherId';

if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[DATA_PaymentVoucher] DROP CONSTRAINT [' + @foreign_key_name + ']';
  execute sp_executesql @dropstmt
end;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_PaymentVoucher
drop column IndividualVoucherId
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>drop table DATA_IndividualVoucher
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [DATA_Voucher] (
	[VoucherId] Integer Identity(1,1) NOT NULL,
	[AccountId] Integer NOT NULL,
	[ParentVoucherId] Integer NULL,
	[VoucherType] Smallint NOT NULL,
	[VoucherStatus] Smallint NOT NULL,
	[VoucherCode] Nvarchar(10) NOT NULL,
	[VoucherName] Nvarchar(50) NOT NULL,
	[StartDate] Datetime NULL,
	[EndDate] Datetime NULL,
	[MaxItems] Smallint NULL,
Primary Key  ([VoucherId])
) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_Voucher] add  foreign key([ParentVoucherId]) references [DATA_Voucher] ([VoucherId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_Voucher] add  foreign key([AccountId]) references [DATA_Account] ([AccountId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [DATA_VoucherItem] (
	[VoucherItemId] Integer Identity(1,1) NOT NULL,
	[VoucherId] Integer NOT NULL,
	[MatrixCellId] Integer NOT NULL,
	[MinQuantity] Smallint NOT NULL,
	[MaxQuantity] Smallint NULL,
Primary Key  ([VoucherItemId])
) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_VoucherItem] add  foreign key([VoucherId]) references [DATA_Voucher] ([VoucherId]) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_VoucherItem] add  foreign key([MatrixCellId]) references [CNF_MatrixCell] ([MatrixCellId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.211</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>- Removes table CNF_Voucher
- Add table CNF_VoucherTemplate</REASON>
			<TABLENAMES>CNF_VoucherTemplate=VoucherTemplateId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @foreign_key_name nvarchar(max);
DECLARE @dropstmt nvarchar(max);

SELECT @foreign_key_name = f.name
  FROM sys.foreign_keys AS f
 INNER JOIN sys.foreign_key_columns AS fc 
    ON f.object_id = fc.constraint_object_id 
 WHERE f.parent_object_id = object_id(N'[dbo].[DATA_IndividualVoucher]')
   AND f.referenced_object_id = object_id(N'[dbo].[CNF_Voucher]')
   AND COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'ProductId';

if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[DATA_IndividualVoucher] DROP CONSTRAINT [' + @foreign_key_name + ']';
  execute sp_executesql @dropstmt
end;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>drop table CNF_Voucher

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_VoucherTemplate] (
	[VoucherTemplateId] Integer Identity(1,1) NOT NULL,
	[AccountId] Integer NOT NULL,
	[VoucherCode] Nvarchar(10) NOT NULL,
	[VoucherName] Nvarchar(50) NOT NULL,
	[StartDate] Datetime NULL,
	[EndDate] Datetime NULL,
	[MaxItems] Smallint NULL,
	[Enabled] Smallint NOT NULL,
Primary Key  ([VoucherTemplateId])
)
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_VoucherTemplate] add  foreign key([AccountId]) references [DATA_Account] ([AccountId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Antonella Mura</ADDEDBY>
			<SQLVERSION>1.210</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>0. Delete index IDX_FORMNAME_LANGID] on CNF_MultiLanguage
1. Rename LangId field on CNF_MultiLanguage into LanguageId
2. Create CNF_Language table
3. Create foreign Key between CNF_MultiLanguage and CNF_Language
4. Recreate index IDX_FORMNAME_LANGID] on CNF_MultiLanguage</REASON>
			<TABLENAMES>CNF_MultiLanguage=MultiLanguageId
CNF_Language=LanguageId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>drop Index IDX_FORMNAME_LANGID ON CNF_MultiLanguage
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_MultiLanguage
drop column LangId
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_MultiLanguage
add LanguageId int null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>UPDATE CNF_MultiLanguage
SET LanguageId=0

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_MultiLanguage
alter column LanguageId int not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_Language] (
	[LanguageId] Integer Identity(1,1) NOT NULL,
	[LangCode] NVarchar(10) NOT NULL UNIQUE,
	[LangDescription] Nvarchar(30) NOT NULL,
Primary Key  ([LanguageId])
)
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_MultiLanguage] add  foreign key([LanguageId]) references [CNF_Language] ([LanguageId])
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create Index [IDX_FORMNAME_LANGID]  ON [CNF_MultiLanguage] ([FormName] ,[LanguageId])
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Antonella Mura</ADDEDBY>
			<SQLVERSION>1.209</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>0. Create table CNF_Multilanguage
1. Create index on FormName and LangId
			</REASON>
			<TABLENAMES>CNF_MultiLanguage=MultiLanguageId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_MultiLanguage] (
	[MultiLanguageId] Integer Identity(1,1) NOT NULL,
	[FormName] NVarchar(50) NOT NULL,
	[ComponentName] Nvarchar(50) NOT NULL,
	[PropertyName] Nvarchar(30) NOT NULL,
	[LangId] NVarchar(10) NOT NULL,
	[Translation] NText NOT NULL,
Primary Key  ([MultiLanguageId])
) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create Index [IDX_FORMNAME_LANGID] ON [CNF_MultiLanguage] ([FormName] ,[LangId])
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Antonella Mura</ADDEDBY>
			<SQLVERSION>1.208</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Table: DATA_DmgData
Fields: MaskData

from nvarchar(50) to nvarchar(100)</REASON>
			<TABLENAMES>DATA_DmgData=DmgDataId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_DmgData
alter column MaskData nvarchar(100) not null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.207</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Table: DATA_Account
Fields: CompanyName, Address1, EmailAddress1

from nvarchar(30) to nvarchar(50)</REASON>
			<TABLENAMES>DATA_Account=AccountId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Account
alter column CompanyName nvarchar(50) null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Account
alter column Address1 nvarchar(50) null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Account
alter column EmailAddress1 nvarchar(50) null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.206</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add fields MachineName and MachineUser to table DATA_DBUpdateLog</REASON>
			<TABLENAMES>DATA_DBUpdateLog=DBUpdateLogId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_DBUpdateLog
add MachineName nvarchar(50)
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_DBUpdateLog
add MachineUser nvarchar(50)
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.205</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>alter table CNF_MaskTable
- Removes fields MaskTableAK and MaskTableDescription
- Add field MaskTableCode</REASON>
			<TABLENAMES>CNF_MaskTable=MaskTableId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_MaskTable
drop column MaskTableAK
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_MaskTable
drop column MaskTableDescription
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_MaskTable
add MaskTableCode varchar(32) null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_MaskTable
set MaskTableCode=replace(cast(newid() as varchar(max)), '-', '')
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_MaskTable
alter column MaskTableCode varchar(32) not null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.204</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>CNF_MaskTableItem.ItemDescription from nvarchar(30) to nvarchar(100)</REASON>
			<TABLENAMES>CNF_MaskTableItem=MaskTableItemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_MaskTableItem
alter column ItemDescription nvarchar(100) not null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.203</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>- Remove field FilterType from table CNF_AccessFilter
- Add field AccessFilterType to table ADM_Gate
- Add field AccessFilterType to table ADM_AccessPoint</REASON>
			<TABLENAMES>CNF_AccessFilter=AccessFilterId
ADM_Gate=GateId
ADM_AccessPoint=WorkstationId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_AccessFilter
drop column FilterType
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table ADM_Gate
add AccessFilterType smallint null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update ADM_Gate
set AccessFilterType=2
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table ADM_Gate
alter column AccessFilterType smallint not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table ADM_AccessPoint
add AccessFilterType smallint null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update ADM_AccessPoint
set AccessFilterType=2
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table ADM_AccessPoint
alter column AccessFilterType smallint not null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.202</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>add field ProirityOrder to table CNF_MaskTableItem</REASON>
			<TABLENAMES>CNF_MaskTableItem=MaskTableItemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_MaskTableItem
add PriorityOrder smallint null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_MaskTableItem
set PriorityOrder=0

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_MaskTableItem
alter column PriorityOrder smallint not null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Saverio Pangallo</ADDEDBY>
			<SQLVERSION>1.201</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>alter table CNF_ExternalTicketRange
alter column ToNumber
alter column FromNumber</REASON>
			<TABLENAMES>CNF_ExternalTicketRange=ExternalTicketRangeId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_ExternalTicketRange
alter column ToNumber varchar(50) not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_ExternalTicketRange
alter column FromNumber varchar(50) not null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.200</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Removes field MatchSubType from CNF_ImportMatch</REASON>
			<TABLENAMES>CNF_ImportMatch=ImportMatchId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_ImportMatch
drop column MatchSubType
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.199</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add field Options to table CNF_ImportMatch</REASON>
			<TABLENAMES>CNF_ImportMatch=ImportMatchId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_ImportMatch
add Options ntext null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.198</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>#0 - Add table CNF_ImportMatch
#1 - Clean DATA_Note table due to old enhacements to DATA_Dmg</REASON>
			<TABLENAMES>CNF_ImportMatch=ImportMatchId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT> Create table [CNF_ImportMatch] (
	[ImportMatchId] Integer Identity(1,1) NOT NULL,
	[EntityTable] Smallint NOT NULL,
	[ExternalFieldName] Nvarchar(50) NOT NULL,
	[MatchType] Smallint NOT NULL,
	[MatchSubType] Smallint NULL,
Primary Key  ([ImportMatchId])
) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>delete from DATA_Note
where NoteType=7 and NoteKey &gt; (select Max(AccountId) from DATA_Account)
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.197</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>- Add field DmgCategoryId to table DATA_SaleItem2Dmg
- Add field DmgCategoryId to table DATA_Ticket
- Add table DATA_DBUpdateLog</REASON>
			<TABLENAMES>DATA_SaleItem2Dmg=SaleItem2DmgId
DATA_Ticket=TicketId
DATA_DBUpdateLog=DBUpdateLogId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>delete from DATA_SaleItem2Dmg
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_SaleItem2Dmg
add DmgCategoryId int not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_SaleItem2Dmg] add  foreign key([DmgCategoryId]) references [CNF_DmgCategory] ([DmgCategoryId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Ticket
add DmgCategoryId int null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_Ticket] add  foreign key([DmgCategoryId]) references [CNF_DmgCategory] ([DmgCategoryId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [DATA_DBUpdateLog] (
	[DBUpdateLogId] Integer Identity(1,1) NOT NULL,
	[LogDateTime] Datetime NOT NULL,
	[UserId] Integer NOT NULL,
	[WorkstationId] Integer NOT NULL,
	[ClientName] Nvarchar(30) NOT NULL,
	[ClientVersion] Nvarchar(30) NOT NULL,
Primary Key  ([DBUpdateLogId])
)
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_DBUpdateLog] add  foreign key([UserId]) references [CNF_User] ([UserId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_DBUpdateLog] add  foreign key([WorkstationId]) references [CNF_Workstation] ([WorkstationId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.196</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add table DATA_SaleItem2Dmg</REASON>
			<TABLENAMES>DATA_SaleItem2Dmg=SaleItem2DmgId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [DATA_SaleItem2Dmg] (
	[SaleItem2DmgId] Integer Identity(1,1) NOT NULL,
	[SaleItemId] Integer NULL,
	[InsDateTime] Datetime NOT NULL,
Primary Key  ([SaleItem2DmgId])
) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_SaleItem2Dmg] add  foreign key([SaleItemId]) references [DATA_SaleItem] ([SaleItemId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.195</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>- DATA_TransactionItem
  - Remove field AttributeSetId

- DATA_SaleItem
  - Add field MatrixCellId
  - Remove field AttributeSetId
  - Remove field PriceListId
  - Remove field PriceTableId
  - Remove field EventId

- DATA_Ticket
  - Add field MatrixCellId
  - Remove field AttributeSetId
  - Remove field PriceListId
  - Remove field PriceTableId
  - Remove field EventId
			</REASON>
			<TABLENAMES>DATA_TransactionItem=ItemId
DATA_SaleItem=SaleItemId
DATA_Ticket=TicketId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @foreign_key_name nvarchar(max);
DECLARE @dropstmt nvarchar(max);

SELECT @foreign_key_name = f.name
  FROM sys.foreign_keys AS f
 INNER JOIN sys.foreign_key_columns AS fc 
    ON f.object_id = fc.constraint_object_id 
 WHERE f.parent_object_id = object_id(N'[dbo].[DATA_TransactionItem]')
   AND f.referenced_object_id = object_id(N'[dbo].[CNF_AttributeSet]')
   AND COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'AttributeSetId';

if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[DATA_TransactionItem] DROP CONSTRAINT [' + @foreign_key_name + ']';
  execute sp_executesql @dropstmt
end;

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_TransactionItem
drop column AttributeSetId
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_SaleItem
add MatrixCellId int null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_SaleItem
set MatrixCellId=MCId
from 
  (
    select 
      MC.MatrixCellId as MCId,      
      MC.PriceListId as PLId,      
      MC.PriceTableId as PTId,      
      MC.AttributeSetId as ASId,      
      MS.EventId as EId        
    from    
      CNF_MatrixCell MC inner join      
      CNF_MatrixSheet MS on MS.MatrixSheetId=MC.MatrixSheetId
  ) ciii                                                            
where
  PriceListId=PLId and  
  PriceTableId=PTId and  
  AttributeSetId=ASId and  
  EventId=EId
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_SaleItem
set MatrixCellId=MCId
from (select top 1 MatrixCellId as MCId from CNF_MatrixCell) ciii
where MatrixCellId is null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @foreign_key_name nvarchar(max);
DECLARE @dropstmt nvarchar(max);

SELECT @foreign_key_name = f.name
  FROM sys.foreign_keys AS f
 INNER JOIN sys.foreign_key_columns AS fc 
    ON f.object_id = fc.constraint_object_id 
 WHERE f.parent_object_id = object_id(N'[dbo].[DATA_SaleItem]')
   AND f.referenced_object_id = object_id(N'[dbo].[CNF_AttributeSet]')
   AND COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'AttributeSetId';

if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[DATA_SaleItem] DROP CONSTRAINT [' + @foreign_key_name + ']';
  execute sp_executesql @dropstmt
end;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_SaleItem
drop column AttributeSetId
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @foreign_key_name nvarchar(max);
DECLARE @dropstmt nvarchar(max);

SELECT @foreign_key_name = f.name
  FROM sys.foreign_keys AS f
 INNER JOIN sys.foreign_key_columns AS fc 
    ON f.object_id = fc.constraint_object_id 
 WHERE f.parent_object_id = object_id(N'[dbo].[DATA_SaleItem]')
   AND f.referenced_object_id = object_id(N'[dbo].[CNF_PriceList]')
   AND COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'PriceListId';

if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[DATA_SaleItem] DROP CONSTRAINT [' + @foreign_key_name + ']';
  execute sp_executesql @dropstmt
end;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_SaleItem
drop column PriceListId
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @foreign_key_name nvarchar(max);
DECLARE @dropstmt nvarchar(max);

SELECT @foreign_key_name = f.name
  FROM sys.foreign_keys AS f
 INNER JOIN sys.foreign_key_columns AS fc 
    ON f.object_id = fc.constraint_object_id 
 WHERE f.parent_object_id = object_id(N'[dbo].[DATA_SaleItem]')
   AND f.referenced_object_id = object_id(N'[dbo].[CNF_PriceTable]')
   AND COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'PriceTableId';

if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[DATA_SaleItem] DROP CONSTRAINT [' + @foreign_key_name + ']';
  execute sp_executesql @dropstmt
end;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_SaleItem
drop column PriceTableId
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @foreign_key_name nvarchar(max);
DECLARE @dropstmt nvarchar(max);

SELECT @foreign_key_name = f.name
  FROM sys.foreign_keys AS f
 INNER JOIN sys.foreign_key_columns AS fc 
    ON f.object_id = fc.constraint_object_id 
 WHERE f.parent_object_id = object_id(N'[dbo].[DATA_SaleItem]')
   AND f.referenced_object_id = object_id(N'[dbo].[CNF_Event]')
   AND COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'EventId';

if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[DATA_SaleItem] DROP CONSTRAINT [' + @foreign_key_name + ']';
  execute sp_executesql @dropstmt
end;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_SaleItem
drop column EventId
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Ticket
add MatrixCellId int null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_Ticket
set MatrixCellId=MCId
from 
  (
    select 
      MC.MatrixCellId as MCId,      
      MC.PriceListId as PLId,      
      MC.PriceTableId as PTId,      
      MC.AttributeSetId as ASId,      
      MS.EventId as EId        
    from    
      CNF_MatrixCell MC inner join      
      CNF_MatrixSheet MS on MS.MatrixSheetId=MC.MatrixSheetId
  ) ciii                                                            
where
  PriceListId=PLId and  
  PriceTableId=PTId and  
  AttributeSetId=ASId and  
  EventId=EId
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_Ticket
set MatrixCellId=MCId
from (select top 1 MatrixCellId as MCId from CNF_MatrixCell) ciii
where MatrixCellId is null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @foreign_key_name nvarchar(max);
DECLARE @dropstmt nvarchar(max);

SELECT @foreign_key_name = f.name
  FROM sys.foreign_keys AS f
 INNER JOIN sys.foreign_key_columns AS fc 
    ON f.object_id = fc.constraint_object_id 
 WHERE f.parent_object_id = object_id(N'[dbo].[DATA_Ticket]')
   AND f.referenced_object_id = object_id(N'[dbo].[CNF_AttributeSet]')
   AND COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'AttributeSetId';

if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[DATA_Ticket] DROP CONSTRAINT [' + @foreign_key_name + ']';
  execute sp_executesql @dropstmt
end;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Ticket
drop column AttributeSetId
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @foreign_key_name nvarchar(max);
DECLARE @dropstmt nvarchar(max);

SELECT @foreign_key_name = f.name
  FROM sys.foreign_keys AS f
 INNER JOIN sys.foreign_key_columns AS fc 
    ON f.object_id = fc.constraint_object_id 
 WHERE f.parent_object_id = object_id(N'[dbo].[DATA_Ticket]')
   AND f.referenced_object_id = object_id(N'[dbo].[CNF_PriceList]')
   AND COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'PriceListId';

if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[DATA_Ticket] DROP CONSTRAINT [' + @foreign_key_name + ']';
  execute sp_executesql @dropstmt
end;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Ticket
drop column PriceListId
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @foreign_key_name nvarchar(max);
DECLARE @dropstmt nvarchar(max);

SELECT @foreign_key_name = f.name
  FROM sys.foreign_keys AS f
 INNER JOIN sys.foreign_key_columns AS fc 
    ON f.object_id = fc.constraint_object_id 
 WHERE f.parent_object_id = object_id(N'[dbo].[DATA_Ticket]')
   AND f.referenced_object_id = object_id(N'[dbo].[CNF_PriceTable]')
   AND COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'PriceTableId';

if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[DATA_Ticket] DROP CONSTRAINT [' + @foreign_key_name + ']';
  execute sp_executesql @dropstmt
end;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Ticket
drop column PriceTableId
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @foreign_key_name nvarchar(max);
DECLARE @dropstmt nvarchar(max);

SELECT @foreign_key_name = f.name
  FROM sys.foreign_keys AS f
 INNER JOIN sys.foreign_key_columns AS fc 
    ON f.object_id = fc.constraint_object_id 
 WHERE f.parent_object_id = object_id(N'[dbo].[DATA_Ticket]')
   AND f.referenced_object_id = object_id(N'[dbo].[CNF_Event]')
   AND COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'EventId';

if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[DATA_Ticket] DROP CONSTRAINT [' + @foreign_key_name + ']';
  execute sp_executesql @dropstmt
end;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Ticket
drop column EventId
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_SaleItem
set MatrixCellId=MCId
from (
  select top 1 MatrixCellId MCId from CNF_MatrixCell
) cii
where MatrixCellId is null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_SaleItem
alter column MatrixCellId int not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Ticket
alter column MatrixCellId int not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_SaleItem] add  foreign key([MatrixCellId]) references [CNF_MatrixCell] ([MatrixCellId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_Ticket] add  foreign key([MatrixCellId]) references [CNF_MatrixCell] ([MatrixCellId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.194</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add field Enabled to table CNF_MatrixCell</REASON>
			<TABLENAMES>CNF_MatrixCell=MatrixCellId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_MatrixCell
add Enabled smallint null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_MatrixCell
set Enabled=1
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_MatrixCell
alter column Enabled smallint not null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Antonella Mura</ADDEDBY>
			<SQLVERSION>1.193</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>0. Delete table DATA_DmgRelation
1. Add Fields FKey and DmgType on DATA_DmgData
2. Update new Fields FKey e DmgType from DATA_Dmg
3. foreign key dropped DATA_DmgData --&gt; DmgId
4. foreign key dropped CNF_Voucher --&gt; DmgId
5. Delete field DATA_DmgData.DmgId
6. Delete table DATA_Dmg
7. Create Index IDX_DmgData_DmgTypeFKey
8. Add field DmgCategoryId to CNF_User
9. Add foreign key on CNF_User.DmgCategoryId</REASON>
			<TABLENAMES>DATA_DmgData=DmgDataId
CNF_User=UserId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>drop table DATA_DmgRelation;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_DmgData
add 
  DmgType smallint null,
  FKey integer null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update 
  DATA_DmgData
set 
    DATA_DmgData.FKey = DATA_Dmg.FKey,
    DATA_DmgData.DmgType = DATA_Dmg.DmgType
  from DATA_Dmg 
  Inner join 
    DATA_DmgData 
  on (DATA_Dmg.DmgId=DATA_DmgData.DmgId)
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @foreign_key_name nvarchar(max);
DECLARE @dropstmt nvarchar(max);

SELECT  @foreign_key_name = f.name
  FROM sys.foreign_keys AS f
 INNER JOIN sys.foreign_key_columns AS fc 
    ON f.object_id = fc.constraint_object_id 
 WHERE f.parent_object_id = object_id(N'[dbo].[DATA_DmgData]')
   AND f.referenced_object_id = object_id(N'[dbo].[DATA_Dmg]')
   AND COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'DmgId';

if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].DATA_DmgData DROP CONSTRAINT [' + @foreign_key_name + ']';
  execute sp_executesql @dropstmt
end;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @foreign_key_name nvarchar(max);
DECLARE @dropstmt nvarchar(max);

SELECT  @foreign_key_name = f.name
  FROM sys.foreign_keys AS f
 INNER JOIN sys.foreign_key_columns AS fc 
    ON f.object_id = fc.constraint_object_id 
 WHERE f.parent_object_id = object_id(N'[dbo].[CNF_Voucher]')
   AND f.referenced_object_id = object_id(N'[dbo].[DATA_Dmg]')
   AND COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'DmgId';

if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].CNF_Voucher DROP CONSTRAINT [' + @foreign_key_name + ']';
  execute sp_executesql @dropstmt
end;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_DmgData
drop column DmgId;  
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>drop table DATA_Dmg;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create Index [IDX_DmgData_DmgTypeFkey]  ON [DATA_DmgData] ([DmgType] ,[FKey])
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table [CNF_User] add [DmgCategoryId] integer;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table [CNF_User] add foreign key([DmgCategoryId]) references [CNF_DmgCategory] ([DmgCategoryId]);
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Saverio Pangallo</ADDEDBY>
			<SQLVERSION>1.192</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>drops tables:
- ADM_ValidFilter
- ADM_FilterAttribute
- ADM_AccessFilter

Add table CNF_AccessFilter</REASON>
			<TABLENAMES>CNF_AccessFilter=AccessFilterId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>drop table ADM_ValidFilter
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>drop table ADM_FilterAttribute
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>drop table ADM_AccessFilter
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_AccessFilter] (
	[AccessFilterId] Integer Identity(1,1) NOT NULL,
	[EntityTable] Smallint NOT NULL,
	[EntityId] Integer NOT NULL,
	[AttributeId] Integer NOT NULL,
	[FilterType] Smallint NOT NULL,
	[Enabled] Smallint NOT NULL,
Primary Key  ([AccessFilterId])
)
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_AccessFilter] add  foreign key([AttributeId]) references [CNF_Attribute] ([AttributeId]) 
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ettore Bottega</ADDEDBY>
			<SQLVERSION>1.191</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>- Add field SystemPackage to CNF_BoardPackage
- adjust  BoardPackageAk value for SystemPackage
- Add field SystemTemplate to CNF_DocTemplate</REASON>
			<TABLENAMES>CNF_BoardPackage=BoardPackageId
CNF_DocTemplate=DocTemplateId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_BoardPackage
  add SystemPackage smallint null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_BoardPackage
   set SystemPackage = 0   

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_BoardPackage
   set SystemPackage = 1
 where BoardPackageAk in ('SystemPackage', 'StandardPackage') 


				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_BoardPackage
   set BoardPackageAk = 'LayoutPackage'
 where BoardPackageAk = 'SystemPackage'   


				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_BoardPackage
alter column SystemPackage smallint not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_DocTemplate
  add SystemTemplate smallint null  

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_DocTemplate
   set SystemTemplate = 0

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_DocTemplate
alter column SystemTemplate smallint not null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.190</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>drops tables:
- CNF_Event2Performance
- CNF_Shift
- CNF_Subscription2Event
- CNF_Subscription</REASON>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>drop table CNF_Event2Performance
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>drop table CNF_Shift
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>drop table CNF_Subscription2Event
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>drop table CNF_Subscription
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.189</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>- Add fields InsDateTime and UpdDateTime to table DATA_Account
- Add tables CNF_Tag and CNF_Tag2Entity</REASON>
			<TABLENAMES>DATA_Account=AccountId
CNF_Tag=TagId
CNF_Tag2Entity=Tag2EntityId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Account
add 
  InsDateTime datetime null,  
  UpdDateTime datetime null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_Account
set
  InsDateTime=GetDate(),  
  UpdDateTime=GetDate()
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Account
alter column InsDateTime datetime not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Account
alter column UpdDateTime datetime not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_Tag] (
	[TagId] Integer Identity(1,1) NOT NULL,
	[TagName] Nvarchar(50) NOT NULL,
	[EntityTableFilter] Smallint NULL,
	[InsDateTime] Datetime NOT NULL,
	[WorkstationId] Integer NOT NULL,
	[UserId] Integer NOT NULL,
Primary Key  ([TagId])
) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Tag] add  foreign key([UserId]) references [CNF_User] ([UserId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Tag] add  foreign key([WorkstationId]) references [CNF_Workstation] ([WorkstationId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_Tag2Entity] (
	[Tag2EntityId] Integer Identity(1,1) NOT NULL,
	[TagId] Integer NOT NULL,
	[EntityTable] Smallint NOT NULL,
	[EntityId] Integer NOT NULL,
	[InsDateTime] Datetime NOT NULL,
	[WorkstationId] Integer NOT NULL,
	[UserId] Integer NOT NULL,
Primary Key  ([Tag2EntityId])
) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create Index [IDX_Tag2Entity_Entity]  ON [CNF_Tag2Entity] ([EntityTable] ,[EntityId] ) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create UNIQUE Index [UQ_Tag2Entity_Entity]  ON [CNF_Tag2Entity] ([TagId] ,[EntityTable] ,[EntityId] ) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Tag2Entity] add  foreign key([TagId]) references [CNF_Tag] ([TagId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Tag2Entity] add  foreign key([UserId]) references [CNF_User] ([UserId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Tag2Entity] add  foreign key([WorkstationId]) references [CNF_Workstation] ([WorkstationId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.188</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Just updates the store procedures because I forgot it in patch 1.187</REASON>
			<TABLENAMES>ADM_Gate2AccessConfiguration=Gate2AccessConfigurationId</TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.187</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Removes table ADM_AccessArea</REASON>
			<TABLENAMES>ADM_Gate2AccessConfiguration=Gate2AccessConfigurationId
DATA_TicketUsage=UsageId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [ADM_Gate2AccessConfiguration] (
	[Gate2AccessConfigurationId] Integer Identity(1,1) NOT NULL,
	[AccessConfigurationId] Integer NOT NULL,
	[GateId] Integer NOT NULL,
Primary Key  ([Gate2AccessConfigurationId])
) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [ADM_Gate2AccessConfiguration] add  foreign key([AccessConfigurationId]) references [ADM_AccessConfiguration] ([AccessConfigurationId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [ADM_Gate2AccessConfiguration] add  foreign key([GateId]) references [ADM_Gate] ([GateId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>insert into ADM_Gate2AccessConfiguration (
  GateId,  
  AccessConfigurationId  
) 
select distinct
  G2AA.GateId,  
  AA.AccessConfigurationId
from
  ADM_Gate2AccessArea G2AA inner join  
  ADM_AccessArea AA on G2AA.AccessAreaId=AA.AccessAreaId
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_TicketUsage
add AccessConfigurationId int null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_TicketUsage] add  foreign key([AccessConfigurationId]) references [ADM_AccessConfiguration] ([AccessConfigurationId]) 



				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_TicketUsage
set AccessConfigurationId=ACId
from 
  (  
    select 
      AccessAreaId as AAId, 
      AccessConfigurationId as ACId   
    from 
      ADM_AccessArea
  ) AA  
where 
  AAId=AccessAreaId
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_TicketUsage
alter column AccessConfigurationId int not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @foreign_key_name nvarchar(max);
DECLARE @dropstmt nvarchar(max);

SELECT @foreign_key_name = f.name
  FROM sys.foreign_keys AS f
 INNER JOIN sys.foreign_key_columns AS fc 
    ON f.object_id = fc.constraint_object_id 
 WHERE f.parent_object_id = object_id(N'[dbo].[DATA_TicketUsage]')
   AND f.referenced_object_id = object_id(N'[dbo].[ADM_AccessArea]')
   AND COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'AccessAreaId';

if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[DATA_TicketUsage] DROP CONSTRAINT [' + @foreign_key_name + ']';
  execute sp_executesql @dropstmt
end;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_TicketUsage
drop column AccessAreaId
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>drop table ADM_ValidCategory
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>drop table ADM_Gate2AccessArea
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>drop table ADM_AccessArea
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Saverio Pangallo</ADDEDBY>
			<SQLVERSION>1.186</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>alter table CNF_ExternalTicketRange
alter column ToNumber
alter column FromNumber</REASON>
			<TABLENAMES>CNF_ExternalTicketRange=ExternalTicketRangeId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_ExternalTicketRange
alter column ToNumber varchar(20) not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_ExternalTicketRange
alter column FromNumber varchar(20) not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>UPDATE CNF_PaymentCardRange SET FromNumber = Replace(FromNumber, 'X', '0')
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>UPDATE CNF_PaymentCardRange SET ToNumber = Replace(ToNumber, 'X', '9')
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Saverio Pangallo</ADDEDBY>
			<SQLVERSION>1.185</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add table CNF_ExternalTicketRange</REASON>
			<TABLENAMES>CNF_ExternalTicketRange=ExternalTicketRangeId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_ExternalTicketRange] (
	[ExternalTicketRangeId] Integer Identity(1,1) NOT NULL UNIQUE,
	[MatrixCellId] Integer NOT NULL,
	[FromNumber] Integer NOT NULL,
	[ToNumber] Integer NOT NULL,
	[PriorityOrder] Smallint NOT NULL,
Primary Key  ([ExternalTicketRangeId])
)
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>        create procedure [dbo].[sp_ui_CNF_ExternalTicketRange_insert]	
                @ExternalTicketRangeId Integer output,
		@MatrixCellId Integer,
		@FromNumber Integer,
		@ToNumber Integer,
		@PriorityOrder SmallInt
	as
	begin
		insert into CNF_ExternalTicketRange
			(MatrixCellId, FromNumber, ToNumber, PriorityOrder)
		values 	
			(@MatrixCellId,@FromNumber,@ToNumber,@PriorityOrder)

	select @ExternalTicketRangeId= SCOPE_IDENTITY() 		

	end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>	create procedure [dbo].[sp_ui_CNF_ExternalTicketRange_update]	
		@ExternalTicketRangeID Integer,
		@MatrixCellId Integer,
		@FromNumber Integer,
		@ToNumber Integer,
		@PriorityOrder SmallInt
	as
	begin
		update	CNF_ExternalTicketRange
		set	MatrixCellId=@MatrixCellId,
			FromNumber=@FromNumber,
			ToNumber=@ToNumber,
			PriorityOrder=@PriorityOrder
		where	ExternalTicketRangeId=@ExternalTicketRangeID

	end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>        create procedure [dbo].[sp_ui_CNF_ExternalTicketRange_delete]	
		@ExternalTicketRangeId Integer	
	as
	begin
		delete from	CNF_ExternalTicketRange
		where	ExternalTicketRangeId=@ExternalTicketRangeId

	end
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.184</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>add field CNF_MaskTableItem.AttributeId</REASON>
			<TABLENAMES>CNF_MaskTableItem=MaskTableItemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_MaskTableItem
add AttributeId int null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_MaskTableItem] add  foreign key([AttributeId]) references [CNF_Attribute] ([AttributeId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.183</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add field DATA_Ticket.TransactionSerial</REASON>
			<TABLENAMES>DATA_Ticket=TicketId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Ticket
add TransactionSerial int null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_Ticket
set TransactionSerial=TrnSerial
from 
  (  
    select                                                       
      T2T.TicketId as TckId,
      T.Serial as TrnSerial   
    from 
      DATA_Transaction2Ticket T2T inner join      
      DATA_Transaction T on T.TransactionId=T2T.TransactionId      
    where    
      T2T.OperationType=1      
  ) cii 
where
  TicketId=TckId

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_Ticket
set TransactionSerial=0
where TransactionSerial is null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Ticket
alter column TransactionSerial int not null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.182</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>drop CNF_Product n2n tables</REASON>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>drop table CNF_Product2Attribute
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>drop table CNF_Product2CostCenter
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>drop table CNF_Product2Family
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>drop table CNF_Product2Product
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>drop table CNF_Product2StatisticalGroup
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>drop table CNF_Product2TimeSlot
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>drop table CNF_Product2UpSale
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.181</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>- drop column DATA_PaymentFlex.Description
- add column DATA_PaymentFlex.InfoXML (ntext)</REASON>
			<TABLENAMES>DATA_PaymentFlex=PaymentId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_PaymentFlex
drop column Description
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_PaymentFlex
add InfoXML ntext null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.180</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>add field ParentAccountId to table DATA_Account</REASON>
			<TABLENAMES>DATA_Account=AccountId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Account
add ParentAccountId int null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_Account] add  foreign key([ParentAccountId]) references [DATA_Account] ([AccountId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Antonella Mura</ADDEDBY>
			<SQLVERSION>1.179</SQLVERSION>
			<RMTRACKLINK>577</RMTRACKLINK>
			<REASON>Remove Unique index of CNF_MaskTableItem on ItemCode field</REASON>
			<TABLENAMES>CNF_MaskTableItem=MaskTableItemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>drop Index UQ_CNF_MaskTableItem_ItemCode ON CNF_MaskTableItem
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ettore Bottega</ADDEDBY>
			<SQLVERSION>1.178</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Added category management through DmgCategory for entities: DocTemplate, Event, Location, Performance, Producer

0 - transfer data from CNF_EventCategory to CNF_DmgCategory
1 - update the values for column CNF_Event.DmgCategoryId
2 - foreign key dropped CNF_DocTemplate --&gt; DocCategoryId
3 - drop column CNF_DocTemplate.DocCategoryId
4 - add column CNF_DocTemplate.DmgCategoryId
5 - add column CNF_Location.DmgCategoryId
6 - add column CNF_Producer.DmgCategoryId
7 - add column CNF_Performance.DmgCategoryId
8 - create foreign key CNF_DocTemplate.DmgCategoryId --&gt; CNF_DmgCategory.CategoryId
9 - create foreign key CNF_Location.DmgCategoryId --&gt; CNF_DmgCategory.CategoryId
10 - create foreign key CNF_Producer.DmgCategoryId --&gt; CNF_DmgCategory.CategoryId
11 - create foreign key CNF_Performance.DmgCategoryId --&gt; CNF_DmgCategory.CategoryId
12 - drop column CNF_Event.EventCategory
13 - drop table CNF_EventCategory
14 - drop table CNF_DocCategory
15 - drop procedure CNF_EventCategory delete
16 - drop procedure CNF_EventCategory insert
17 - drop procedure CNF_EventCategory update
18 - drop procedure CNF_DocCategory delete
19 - drop procedure CNF_DocCategory insert
20 - drop procedure CNF_DocCategory update
			</REASON>
			<TABLENAMES>CNF_Event=EventId
CNF_Location=LocationId
CNF_Producer=ProducerId
CNF_Performance=PerformanceId
CNF_DocTemplate=DocTemplateId
			</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>with UsedEventCategories (ParentId, DmgType, EventCategoryAK, Name) 
  as (
    SELECT distinct 
           (select DmgCategoryId from CNF_DmgCategory where DmgType = 7 and DmgParentId is null) as ParentId,
           7 as DmgType,
           ec.EventCategoryAK,
           ec.Name
      FROM CNF_EventCategory ec
     INNER JOIN CNF_Event e on (ec.EventCategoryId = e.EventCategory)
  )
insert into CNF_DmgCategory 
  (DmgParentId, DmgType, DmgCategoryAK, Description)
select ParentId, DmgType, EventCategoryAK, Name 
  from UsedEventCategories

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_Event 
   set DmgCategoryId = (
     select DmgCategoryId 
       from CNF_DmgCategory c 
      inner join CNF_EventCategory ec on (c.DmgCategoryAk = ec.EventCategoryAk and EventCategory = ec.EventCategoryId)
   )

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @foreign_key_name nvarchar(max);
DECLARE @dropstmt nvarchar(max);

SELECT @foreign_key_name = f.name
  FROM sys.foreign_keys AS f
 INNER JOIN sys.foreign_key_columns AS fc 
    ON f.object_id = fc.constraint_object_id 
 WHERE f.parent_object_id = object_id(N'[dbo].[CNF_DocTemplate]')
   AND f.referenced_object_id = object_id(N'[dbo].[CNF_DocCategory]')
   AND COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'DocCategoryId';

if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[CNF_DocTemplate] DROP CONSTRAINT [' + @foreign_key_name + ']';
  execute sp_executesql @dropstmt
end;

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_DocTemplate
 drop column DocCategoryId;

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table [CNF_DocTemplate] add [DmgCategoryId] integer;

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table [CNF_Location] add [DmgCategoryId] integer;

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table [CNF_Producer] add [DmgCategoryId] integer;

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table [CNF_Performance] add [DmgCategoryId] integer;

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table [CNF_DocTemplate] add foreign key([DmgCategoryId]) references [CNF_DmgCategory] ([DmgCategoryId]);

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table [CNF_Location] add foreign key([DmgCategoryId]) references [CNF_DmgCategory] ([DmgCategoryId]);

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table [CNF_Producer] add foreign key([DmgCategoryId]) references [CNF_DmgCategory] ([DmgCategoryId]);

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table [CNF_Performance] add foreign key([DmgCategoryId]) references [CNF_DmgCategory] ([DmgCategoryId]);

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Event
 drop column EventCategory;

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>drop table CNF_EventCategory;

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>drop table CNF_DocCategory;

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if  exists (select * from sys.objects where object_id = object_id(N'[dbo].[sp_ui_CNF_EventCategory_delete]') and type in (N'p', N'pc'))
  drop procedure [dbo].[sp_ui_CNF_EventCategory_delete];

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if  exists (select * from sys.objects where object_id = object_id(N'[dbo].[sp_ui_CNF_EventCategory_insert]') and type in (N'p', N'pc'))
  drop procedure [dbo].[sp_ui_CNF_EventCategory_insert];

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if  exists (select * from sys.objects where object_id = object_id(N'[dbo].[sp_ui_CNF_EventCategory_update]') and type in (N'p', N'pc'))
  drop procedure [dbo].[sp_ui_CNF_EventCategory_update];

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if  exists (select * from sys.objects where object_id = object_id(N'[dbo].[sp_ui_CNF_DocCategory_delete]') and type in (N'p', N'pc'))
  drop procedure [dbo].[sp_ui_CNF_DocCategory_delete];

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if  exists (select * from sys.objects where object_id = object_id(N'[dbo].[sp_ui_CNF_DocCategory_insert]') and type in (N'p', N'pc'))
  drop procedure [dbo].[sp_ui_CNF_DocCategory_insert];

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>if  exists (select * from sys.objects where object_id = object_id(N'[dbo].[sp_ui_CNF_DocCategory_update]') and type in (N'p', N'pc'))
  drop procedure [dbo].[sp_ui_CNF_DocCategory_update];

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.177</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add table CNF_BoardFav</REASON>
			<TABLENAMES>CNF_BoardFav=BoardFavId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_BoardFav] (
	[BoardFavId] Integer Identity(1,1) NOT NULL,
	[UserId] Integer NOT NULL,
	[Button] Ntext NOT NULL,
	[PriorityOrder] Smallint NOT NULL,
Primary Key  ([BoardFavId])
) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_BoardFav] add  foreign key([UserId]) references [CNF_User] ([UserId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.176</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>add field Color to table CNF_PaymentMethod</REASON>
			<TABLENAMES>CNF_PaymentMethod=PaymentMethodId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_PaymentMethod
add Color varchar(10) null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.175</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>add field Color to table CNF_Event</REASON>
			<TABLENAMES>CNF_Event=EventId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Event
add Color varchar(10) null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.174</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>drop column CNF_Product.ProductGroupId

Drops tables
- CNF_ProductCat2Template
- CNF_ProductGroup


in tables modified it lists CNF_Event because it was forgotten in patch 1.172</REASON>
			<TABLENAMES>CNF_Event=EventId
CNF_Product=ProductId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @foreign_key_name nvarchar(max);
DECLARE @dropstmt nvarchar(max);

SELECT @foreign_key_name = f.name
  FROM sys.foreign_keys AS f
 INNER JOIN sys.foreign_key_columns AS fc 
    ON f.object_id = fc.constraint_object_id 
 WHERE f.parent_object_id = object_id(N'[dbo].[CNF_Product]')
   AND f.referenced_object_id = object_id(N'[dbo].[CNF_ProductGroup]')
   AND COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'ProductGroupId';

if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[CNF_Product] DROP CONSTRAINT [' + @foreign_key_name + ']';
  execute sp_executesql @dropstmt
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Product
drop column ProductGroupId
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>drop table CNF_ProductCat2Template
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>drop table CNF_ProductGroup
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.173</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Drops tables 
- CNF_ProductMatrixOption
- CNF_ProductMatrix</REASON>
			<TABLENAMES>CNF_MatrixCell=MatrixCellId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>drop table CNF_ProductMatrixOption
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>drop table CNF_ProductMatrix
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Antonella Mura</ADDEDBY>
			<SQLVERSION>1.172</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Creates new field "DmgCategoryId" into CNF_Event and create Foreign-key</REASON>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Event 
add DmgCategoryId integer
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Event] add foreign key([DmgCategoryId]) references [CNF_DmgCategory] ([DmgCategoryId])
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Antonella Mura</ADDEDBY>
			<SQLVERSION>1.171</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Creates new field "AttributeTemplateId" into CNF_DataMask and create Foreign-key</REASON>
			<TABLENAMES>CNF_DataMask=DataMaskId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_DataMask 
add AttributeTemplateId integer
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_DataMask] add foreign key([AttributeTemplateId]) references [CNF_AttributeTemplate] ([AttributeTemplateId])
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.170</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Removes fields TransactionItemAK and ProductId from DATA_TransactionItem</REASON>
			<TABLENAMES>DATA_TransactionItem=ItemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>declare @unique_key_name nvarchar(max);
declare @dropstmt nvarchar(max);

select @unique_key_name = CONSTRAINT_NAME
from INFORMATION_SCHEMA.TABLE_CONSTRAINTS
where CONSTRAINT_TYPE='UNIQUE' and TABLE_NAME='DATA_TransactionItem'

if (len(@unique_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[DATA_TransactionItem] DROP CONSTRAINT [' + @unique_key_name + ']';
  execute sp_executesql @dropstmt
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_TransactionItem
drop column TransactionItemAK
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @foreign_key_name nvarchar(max);
DECLARE @dropstmt nvarchar(max);

SELECT @foreign_key_name = f.name
  FROM sys.foreign_keys AS f
 INNER JOIN sys.foreign_key_columns AS fc 
    ON f.object_id = fc.constraint_object_id 
 WHERE f.parent_object_id = object_id(N'[dbo].[DATA_TransactionItem]')
   AND f.referenced_object_id = object_id(N'[dbo].[CNF_Product]')
   AND COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'ProductId';

if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[DATA_TransactionItem] DROP CONSTRAINT [' + @foreign_key_name + ']';
  execute sp_executesql @dropstmt
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_TransactionItem
drop column ProductId
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.169</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>alter table DATA_SaleItem

- Add field EventId
- Removes field ProductId
- Removes field SaleItemAK</REASON>
			<TABLENAMES>DATA_SaleItem=SaleItemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_SaleItem
add EventId int null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_SaleItem
set EventId=StoreId
from 
  (
    select    
      ProductId PrdId,      
      Key1 as StoreId      
    from    
      CNF_Product
  ) dummy  
where ProductId=PrdId
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_SaleItem
alter column EventId int not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_SaleItem] add  foreign key([EventId]) references [CNF_Event] ([EventId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_SaleItem
drop column ProductId
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>declare @unique_key_name nvarchar(max);
declare @dropstmt nvarchar(max);

select @unique_key_name = CONSTRAINT_NAME
from INFORMATION_SCHEMA.TABLE_CONSTRAINTS
where CONSTRAINT_TYPE='UNIQUE' and TABLE_NAME='DATA_SaleItem'

if (len(@unique_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[DATA_SaleItem] DROP CONSTRAINT [' + @unique_key_name + ']';
  execute sp_executesql @dropstmt
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_SaleItem
drop column SaleItemAK
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.168</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Changes to DATA_Ticket table</REASON>
			<TABLENAMES>DATA_Ticket=TicketId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>declare @unique_key_name nvarchar(max);
declare @dropstmt nvarchar(max);

select @unique_key_name = CONSTRAINT_NAME
from INFORMATION_SCHEMA.TABLE_CONSTRAINTS
where CONSTRAINT_TYPE='UNIQUE' and TABLE_NAME='DATA_Ticket'

if (len(@unique_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[DATA_Ticket] DROP CONSTRAINT [' + @unique_key_name + ']';
  execute sp_executesql @dropstmt
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Ticket
add 
  FEncodeDate datetime null,
  PrintDateTime datetime null,  
  SiteId smallint null,  
  WorkstationCode smallint null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_Ticket
set 
  FEncodeDate=getdate(),  
  SiteId=0,  
  WorkstationCode=0
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_Ticket
set
  FEncodeDate=FDate,  
  PrintDateTime=EncodingDateTime, 
  SiteId=Site,  
  WorkstationCode=Code  
from 
  (
    select       
      T2T.TicketId as TckId,      
      T.FTransactionDate as FDate,
      W.SiteId as Site, 
      W.WorkstationCode as Code 
    from              
      DATA_Transaction2Ticket T2T left outer join      
      DATA_Transaction T on T.TransactionId=T2T.TransactionId left outer join
      CNF_Workstation W on W.WorkstationId=T.WorkstationId      
    where    
      T2T.OperationType=1
  ) dummy
where TicketId=TckId


				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Ticket
alter column FEncodeDate datetime not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Ticket
alter column SiteId smallint not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Ticket
alter column WorkstationCode smallint not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DROP INDEX [IDX_Ticket_EncodingDateTime] ON [dbo].[DATA_Ticket]
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Ticket
drop column 
  TicketAK,  
  Encoded,  
  EncodingType,  
  ElementType,  
  ExtType,  
  WalletKey,  
  EncodingDateTime
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create UNIQUE Index [IDX_Ticket_WalletKey]  ON [DATA_Ticket] ([FEncodeDate] ,[SiteId] ,[WorkstationCode] ,[Serial] ) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.167</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Modify table DATA_Ticket
- add field EventId
- add field PriceListId
- add field PriceTableId
- removes field ProducId</REASON>
			<TABLENAMES>DATA_Ticket=TicketId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT> alter table DATA_Ticket 
 add EventId int null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_Ticket
set EventId=StoreId
from (select Key1 as StoreId, ProductId as PrdId from CNF_Product) Dummy
where ProductId=PrdId

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Ticket
alter column EventId int not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_Ticket] add  foreign key([EventId]) references [CNF_Event] ([EventId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Ticket
add PriceListId int null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_Ticket
set PriceListId=(select top 1 PriceListId from CNF_PriceList)
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Ticket
alter column PriceListId int not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_Ticket] add  foreign key([PriceListId]) references [CNF_PriceList] ([PriceListId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Ticket
add PriceTableId int null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_Ticket
set PriceTableId=(select top 1 PriceTableId from CNF_PriceTable)
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Ticket
alter column PriceTableId int not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_Ticket] add  foreign key([PriceTableId]) references [CNF_PriceTable] ([PriceTableId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Ticket
drop column ProductId
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.166</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add fields TaxPackageId and TaxType to table CNF_MatrixCell</REASON>
			<TABLENAMES>CNF_MatrixCell=MatrixCellId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_MatrixCell
add TaxPackageId int null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_MatrixCell
add TaxType smallint null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_MatrixCell] add  foreign key([TaxPackageId]) references [CNF_TaxPackage] ([TaxPackageId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.165</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Removes field AttributeTemplateType from CNF_AttributeTemplate</REASON>
			<TABLENAMES>CNF_AttributeTemplate=AttributeTemplateId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_AttributeTemplate
drop column AttributeTemplateType
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.164</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>add field FilterItemId to CNF_MatrixDimension</REASON>
			<TABLENAMES>CNF_MatrixDimension=MatrixDimensionId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_MatrixDimension
add FilterItemId int null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.163</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>add table CNF_MatrixCellOption</REASON>
			<TABLENAMES>CNF_MatrixCellOption=MatrixCellOptionId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_MatrixCellOption] (
	[MatrixCellOptionId] Integer Identity(1,1) NOT NULL,
	[MatrixCellId] Integer NOT NULL,
	[OptionType] Smallint NOT NULL,
	[OptionValue] Nvarchar(100) NOT NULL,
Primary Key  ([MatrixCellOptionId])
) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create UNIQUE Index [IDX_MatrixCellOption_UniqueType]  ON [CNF_MatrixCellOption] ([MatrixCellId] ,[OptionType] ) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_MatrixCellOption] add  foreign key([MatrixCellId]) references [CNF_MatrixCell] ([MatrixCellId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.162</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add tables:
- CNF_Trigger
- DATA_TriggerItem
- DATA_TriggerItemLog</REASON>
			<TABLENAMES>CNF_Trigger=TriggerId
DATA_TriggerItem=TriggerItemId
DATA_TriggerItemLog=TriggerItemLogId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_Trigger] (
	[TriggerId] Integer Identity(1,1) NOT NULL,
	[TriggerType] Smallint NOT NULL,
	[ListenerType] Smallint NOT NULL,
	[EntityTable] Smallint NULL,
	[EntityId] Integer NULL,
	[ConfigXML] Ntext NULL,
Primary Key  ([TriggerId])
) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [DATA_TriggerItem] (
	[TriggerItemId] Integer Identity(1,1) NOT NULL,
	[TriggerItemStatus] Smallint NOT NULL,
	[TriggerType] Smallint NOT NULL,
	[EntityTable] Smallint NOT NULL,
	[EntityId] Integer NOT NULL,
	[ListenerType] Smallint NOT NULL,
	[InsDateTime] Datetime NOT NULL,
	[InsWorkstationId] Integer NOT NULL,
	[InsUserId] Integer NOT NULL,
	[UpdDateTime] Datetime NULL,
	[UpdWorkstationId] Integer NULL,
	[UpdUserId] Integer NULL,
	[CmpDateTime] Datetime NULL,
	[CmpUserId] Integer NULL,
	[CmpWorkstationId] Integer NULL,
Primary Key  ([TriggerItemId])
) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_TriggerItem] add  foreign key([InsUserId]) references [CNF_User] ([UserId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_TriggerItem] add  foreign key([UpdUserId]) references [CNF_User] ([UserId])
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_TriggerItem] add  foreign key([CmpUserId]) references [CNF_User] ([UserId])
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_TriggerItem] add  foreign key([InsWorkstationId]) references [CNF_Workstation] ([WorkstationId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_TriggerItem] add  foreign key([UpdWorkstationId]) references [CNF_Workstation] ([WorkstationId])
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_TriggerItem] add  foreign key([CmpWorkstationId]) references [CNF_Workstation] ([WorkstationId])
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [DATA_TriggerItemLog] (
	[TriggerItemLogId] Integer Identity(1,1) NOT NULL,
	[TriggerItemId] Integer NOT NULL,
	[WorkstationId] Integer NOT NULL,
	[UserId] Integer NOT NULL,
	[LogDateTime] Datetime NOT NULL,
	[LogMessage] Ntext NOT NULL,
Primary Key  ([TriggerItemLogId])
) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_TriggerItemLog] add  foreign key([TriggerItemId]) references [DATA_TriggerItem] ([TriggerItemId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_TriggerItemLog] add  foreign key([UserId]) references [CNF_User] ([UserId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_TriggerItemLog] add  foreign key([WorkstationId]) references [CNF_Workstation] ([WorkstationId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.161</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add field LogNote to table DATA_HistoryLog</REASON>
			<TABLENAMES>DATA_HistoryLog=HistoryLogId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_HistoryLog
add LogNote nvarchar(100) null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.160</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>CNF_FlexContract.PaymentCycleValue becomes nullable</REASON>
			<TABLENAMES>CNF_FlexContract=FlexContractId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_FlexContract
alter column PaymentCycleValue int null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.159</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>- Drop tables CNF_MatrixSheet2PriceList, CNF_MatrixSheet2PriceTable, CNF_MatrixSheet2Attribute
- Add table CNF_MatrixDimension</REASON>
			<TABLENAMES>CNF_MatrixDimension=MatrixDimensionId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>drop table CNF_MatrixSheet2PriceList
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>drop table CNF_MatrixSheet2PriceTable
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>drop table CNF_MatrixSheet2Attribute
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_MatrixDimension] (
	[MatrixDimensionId] Integer Identity(1,1) NOT NULL,
	[MatrixSheetId] Integer NOT NULL,
	[PriceTableId] Integer NULL,
	[PriceListId] Integer NULL,
	[AttributeId] Integer NULL,
	[PriorityOrder] Smallint NOT NULL,
	[DimensionKind] Smallint NOT NULL,
	[Size] Smallint NULL,
Primary Key  ([MatrixDimensionId])
) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create UNIQUE Index [IDX_MatrixDimension]  ON [CNF_MatrixDimension] ([MatrixSheetId] ,[PriceTableId] ,[PriceListId] ,[AttributeId] ) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_MatrixDimension] add  foreign key([MatrixSheetId]) references [CNF_MatrixSheet] ([MatrixSheetId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_MatrixDimension] add  foreign key([PriceListId]) references [CNF_PriceList] ([PriceListId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_MatrixDimension] add  foreign key([PriceTableId]) references [CNF_PriceTable] ([PriceTableId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_MatrixDimension] add  foreign key([AttributeId]) references [CNF_Attribute] ([AttributeId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.158</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add table CNF_MatrixCell</REASON>
			<TABLENAMES>CNF_MatrixCell=MatrixCellId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_MatrixCell] (
	[MatrixCellId] Integer Identity(1,1) NOT NULL,
	[MatrixSheetId] Integer NOT NULL,
	[PriceListId] Integer NOT NULL,
	[PriceTableId] Integer NOT NULL,
	[AttributeSetId] Integer NOT NULL,
	[Price] Float NULL,
Primary Key  ([MatrixCellId])
) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_MatrixCell] add  foreign key([MatrixSheetId]) references [CNF_MatrixSheet] ([MatrixSheetId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_MatrixCell] add  foreign key([PriceListId]) references [CNF_PriceList] ([PriceListId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_MatrixCell] add  foreign key([PriceTableId]) references [CNF_PriceTable] ([PriceTableId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_MatrixCell] add  foreign key([AttributeSetId]) references [CNF_AttributeSet] ([AttributeSetId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.157</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add tables:
- CNF_MatrixSheet2PriceList
- CNF_MatrixSheet2PriceTable</REASON>
			<TABLENAMES>CNF_MatrixSheet2PriceList=MatrixSheet2PriceListId
CNF_MatrixSheet2PriceTable=MatrixSheet2PriceTableId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_MatrixSheet2PriceList] (
	[MatrixSheet2PriceListId] Integer Identity(1,1) NOT NULL,
	[MatrixSheetId] Integer NOT NULL,
	[PriceListId] Integer NOT NULL,
Primary Key  ([MatrixSheet2PriceListId])
) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_MatrixSheet2PriceList] add  foreign key([PriceListId]) references [CNF_PriceList] ([PriceListId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_MatrixSheet2PriceList] add  foreign key([MatrixSheetId]) references [CNF_MatrixSheet] ([MatrixSheetId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_MatrixSheet2PriceTable] (
	[MatrixSheet2PriceTableId] Integer Identity(1,1) NOT NULL,
	[MatrixSheetId] Integer NOT NULL,
	[PriceTableId] Integer NOT NULL,
Primary Key  ([MatrixSheet2PriceTableId])
) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_MatrixSheet2PriceTable] add  foreign key([PriceTableId]) references [CNF_PriceTable] ([PriceTableId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_MatrixSheet2PriceTable] add  foreign key([MatrixSheetId]) references [CNF_MatrixSheet] ([MatrixSheetId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Antonella Mura</ADDEDBY>
			<SQLVERSION>1.156</SQLVERSION>
			<RMTRACKLINK>602</RMTRACKLINK>
			<REASON>Rename field 'SuccessedCount' into 'SucceededCount'  in DATA_SchedulerLog.</REASON>
			<TABLENAMES>DATA_SchedulerLog=SchedulerLogId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_SchedulerLog
add SucceededCount int null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_SchedulerLog
set SucceededCount=SuccessedCount
from DATA_SchedulerLog
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_SchedulerLog
alter column SucceededCount int not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_SchedulerLog
drop column SuccessedCount
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.155</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add field ErrorMessage to table DATA_DocBatch</REASON>
			<TABLENAMES>DATA_DocBatch=DocBatchId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_DocBatch
add ErrorMessage ntext null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.154</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>CNF_User.UserPassword becomes varchar(100)</REASON>
			<TABLENAMES>CNF_User=UserId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_User
alter column UserPassword varchar(100)
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ettore Bottega</ADDEDBY>
			<SQLVERSION>1.153</SQLVERSION>
			<RMTRACKLINK>586</RMTRACKLINK>
			<REASON>drop field ReportSupport from table CNF_Driver</REASON>
			<TABLENAMES>CNF_Driver=DriverId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Driver 
 drop column ReportSupport 
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.152</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add field PaymentAccountRecap to table DATA_PaymentAccount</REASON>
			<TABLENAMES>DATA_PaymentAccount=PaymentAccountId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_PaymentAccount
add PaymentAccountRecap nvarchar(30) null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.151</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add table DATA_PaymentPlanLog</REASON>
			<TABLENAMES>DATA_PaymentPlanLog=PaymentPlanLogId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [DATA_PaymentPlanLog] (
	[PaymentPlanLogId] Integer Identity(1,1) NOT NULL,
	[PaymentPlanId] Integer NOT NULL,
	[LogDateTime] Datetime NOT NULL,
	[Message] Ntext NULL,
Primary Key  ([PaymentPlanLogId])
) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_PaymentPlanLog] add  foreign key([PaymentPlanId]) references [DATA_PaymentPlan] ([PaymentPlanId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.150</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add field Enabled to table DATA_Account</REASON>
			<TABLENAMES>DATA_Account=AccountId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Account
add Enabled smallint null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_Account
set Enabled=1
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Account
alter column Enabled smallint not null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.149</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>drop tables CNF_EncryptionKey and CNF_MasterKey</REASON>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>drop table CNF_EncryptionKey
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>drop table CNF_MasterKey
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.148</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Drop table DATA_DmgBase</REASON>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>drop table DATA_DmgBase
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.147</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>- Removes DATA_Sale.DmgId
- Add DATA_Reservation.AccountId</REASON>
			<TABLENAMES>DATA_Reservation=SaleId
DATA_Sale=SaleId
DATA_PaymentFlex=PaymentId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Reservation
add AccountId int null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_Reservation] add  foreign key([AccountId]) references [DATA_Account] ([AccountId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_Reservation
set AccountId=FKey
from
  DATA_Sale S inner join
  DATA_Dmg D on S.DmgId=D.DmgId  
where
  S.SaleId=DATA_Reservation.SaleId and  
  D.DmgType=1

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_Reservation
set AccountId=ID
from (select top 1 AccountId as ID from DATA_Account) dummy
where AccountId is null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Reservation
alter column AccountId int not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @foreign_key_name nvarchar(max);
DECLARE @dropstmt nvarchar(max);

SELECT @foreign_key_name = f.name
  FROM sys.foreign_keys AS f
 INNER JOIN sys.foreign_key_columns AS fc 
    ON f.object_id = fc.constraint_object_id 
 WHERE f.parent_object_id = object_id(N'[dbo].[DATA_Sale]')
   AND f.referenced_object_id = object_id(N'[dbo].[DATA_Dmg]')
   AND COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'DmgId';

if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[DATA_Sale] DROP CONSTRAINT [' + @foreign_key_name + ']';
  execute sp_executesql @dropstmt
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Sale
drop column DmgId
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.146</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add table DATA_SaleItem2Account and removes DATA_Sale2Dmg</REASON>
			<TABLENAMES>DATA_SaleItem2Account=SaleItem2AccountId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [DATA_SaleItem2Account] (
	[SaleItem2AccountId] Integer Identity(1,1) NOT NULL,
	[SaleItemId] Integer NOT NULL,
	[AccountId] Integer NOT NULL
Primary Key  ([SaleItem2AccountId])
) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_SaleItem2Account] add  foreign key([SaleItemId]) references [DATA_SaleItem] ([SaleItemId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_SaleItem2Account] add  foreign key([AccountId]) references [DATA_Account] ([AccountId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>insert into DATA_SaleItem2Account (
  SaleItemId,  
  AccountId  
)
select
  S2D.SaleItemId,
  D.FKey
from
  DATA_Sale2Dmg S2D inner join
  DATA_Dmg D on D.DmgId=S2D.DmgId  
where
  S2D.SaleItemId is not null and
  D.DmgType=1
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>drop table DATA_Sale2Dmg
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.145</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add field AccountId to table DATA_Ticket</REASON>
			<TABLENAMES>DATA_Ticket=TicketId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Ticket
add AccountId int null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_Ticket] add  foreign key([AccountId]) references [DATA_Account] ([AccountId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_Ticket
set AccountId=FKey
from 
  DATA_DmgRelation DR inner join  
  DATA_Dmg D on D.DmgId=DR.DmgId
where 
  DR.ChildTable=159 and 
  DR.ChildId=TicketId and  
  D.DmgType=1
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.144</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>- Replace DmgId with AccountId in table DATA_PaymentFlex</REASON>
			<TABLENAMES>DATA_PaymentFlex=PaymentId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @foreign_key_name nvarchar(max);
DECLARE @dropstmt nvarchar(max);

SELECT @foreign_key_name = f.name
  FROM sys.foreign_keys AS f
 INNER JOIN sys.foreign_key_columns AS fc 
    ON f.object_id = fc.constraint_object_id 
 WHERE f.parent_object_id = object_id(N'[dbo].[DATA_PaymentFlex]')
   AND f.referenced_object_id = object_id(N'[dbo].[DATA_Dmg]')
   AND COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'DmgId';

if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[DATA_PaymentFlex] DROP CONSTRAINT [' + @foreign_key_name + ']';
  execute sp_executesql @dropstmt
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_PaymentFlex
add AccountId int null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_PaymentFlex
set AccountId=FKey
from DATA_Dmg
where DmgType=1 and DATA_Dmg.DmgId=DATA_PaymentFlex.DmgId
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_PaymentFlex
alter column AccountId int not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_PaymentFlex] add  foreign key([AccountId]) references [DATA_Account] ([AccountId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_PaymentFlex
drop column DmgId
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.143</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Create indexes:
- IDX_Account_DisplayName
- IDX_DmgData_MaskData</REASON>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>Create Index [IDX_Account_DisplayName]  ON [DATA_Account] ([DisplayName] ) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create Index [IDX_DmgData_MaskData]  ON [DATA_DmgData] ([MaskData] ) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.142</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>- Create table DATA_Account and populate from DATA_DmgBase</REASON>
			<TABLENAMES>DATA_Account=AccountId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [DATA_Account] (
	[AccountId] Integer Identity(1,1) NOT NULL,
	[AccountAK] varchar(32) NOT NULL,
	[AccountType] Smallint NOT NULL,
	[DmgCategoryId] Integer NOT NULL,
	[PriceListId] Integer NULL,
	[DisplayName] Nvarchar(50) NOT NULL,
	[TempDmgId] Integer NULL,
	[FirstName] Nvarchar(30) NULL,
	[SurName] Nvarchar(30) NULL,
	[CompanyName] Nvarchar(30) NULL,
	[Address1] Nvarchar(30) NULL,
	[ZipCode] Nvarchar(30) NULL,
	[City] Nvarchar(30) NULL,
	[State] Nvarchar(30) NULL,
	[Country] Nvarchar(30) NULL,
	[HomePhone] Nvarchar(30) NULL,
	[BusinessPhone] Nvarchar(30) NULL,
	[Fax] Nvarchar(30) NULL,
	[MobilePhone] Nvarchar(30) NULL,
	[EmailAddress1] Nvarchar(30) NULL,
Primary Key  ([AccountId])
) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create UNIQUE Index [IDX_Account_AccountAK]  ON [DATA_Account] ([AccountAK] ) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_Account] add  foreign key([DmgCategoryId]) references [CNF_DmgCategory] ([DmgCategoryId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_Account] add  foreign key([PriceListId]) references [CNF_PriceList] ([PriceListId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>insert into DATA_Account (
	AccountAK,
	AccountType,
	DmgCategoryId,
	PriceListId,
	DisplayName,
	TempDmgId,
	FirstName,
	SurName,
	CompanyName,
	Address1,
	ZipCode,
	City,
	State,
	Country,
	HomePhone,
	BusinessPhone,
	Fax,
	MobilePhone,
	EmailAddress1
 ) 
 select 
	D.DmgAK,
	(case when D.DmgSubType is null then 1 else D.DmgSubType end),
	D.DmgCategoryId,
	D.PriceListId,
	(case D.DmgSubType   
          when 1 then IsNull(DB.CompanyName,LTrim(IsNull(DB.SurName,'') + ' ' + IsNull(DB.FirstName,'')))   
          else LTrim(IsNull(DB.SurName,'') + ' ' + IsNull(DB.FirstName,'')) 
 	end),
	D.DmgId,
	DB.FirstName,
	DB.SurName,
	DB.CompanyName,
	DB.Address1,
	DB.ZipCode,
	DB.City,
	DB.State,
	DB.Country,
	DB.HomePhone,
	DB.BusinessPhone,
	DB.Fax,
	DB.MobilePhone,
	DB.EmailAddress1
 from 
   DATA_Dmg D inner join   
   DATA_DmgBase DB on D.DmgId=DB.DmgId and D.DmgType=1

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_Dmg
set FKey=AccountId
from DATA_Account
where DmgId=TempDmgId
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Account
drop column TempDmgId
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.141</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add field PaymentDate to table DATA_PaymentPlan</REASON>
			<TABLENAMES>DATA_PaymentPlan=PaymentPlanId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_PaymentPlan
add PaymentDate datetime null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.140</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>DATA_PaymentPlan:
- PaymentNumber turns Smallint (nullable)
- Added PriorityOrder </REASON>
			<TABLENAMES>DATA_PaymentPlan=PaymentPlanId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>DROP INDEX DATA_PaymentPlan.IDX_PaymentNumber

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_PaymentPlan
alter column PaymentNumber smallint null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_PaymentPlan
add PriorityOrder smallint null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_PaymentPlan
set PriorityOrder=0
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_PaymentPlan
alter column PriorityOrder smallint not null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.139</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>DATA_PaymentPlan:
- PaymentMethodId turns nullable
- Added Field PaymentActivityType</REASON>
			<TABLENAMES>DATA_PaymentPlan=PaymentPlanId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_PaymentPlan
alter column PaymentMethodId int null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_PaymentPlan
add PaymentActivityType smallint null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_PaymentPlan
set PaymentActivityType=1
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_PaymentPlan
alter column PaymentActivityType smallint not null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.138</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>rename TGenSerialReader driver</REASON>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_Driver
set 
  DriverAK='TDrvGenSerialReader', 
  DllName='DrvDevCommon.dll'
where DriverAK='TGenSerialReader'
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.137</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>rename TOtnVideoCapture driver</REASON>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_Driver
set 
  DriverAK='TDrvVideoCapture', 
  DllName='DrvDevCommon.dll'
where DriverAK='TOtnVideoCapture'
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.136</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add field DocTemplateId to table DATA_DocBatch</REASON>
			<TABLENAMES>DATA_DocBatch=DocBatchId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_DocBatch
add DocTemplateId int not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_DocBatch] add  foreign key([DocTemplateId]) references [CNF_DocTemplate] ([DocTemplateId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.135</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Create table CNF_FlexCommunication</REASON>
			<TABLENAMES>CNF_FlexCommunication=FlexCommunicationId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_FlexCommunication] (
	[FlexCommunicationId] Integer Identity(1,1) NOT NULL,
	[FlexContractId] Integer NOT NULL,
	[DocTemplateId] Integer NOT NULL,
	[FlexCommunicationEvent] Smallint NOT NULL,
Primary Key  ([FlexCommunicationId])
) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_FlexCommunication] add  foreign key([FlexContractId]) references [CNF_FlexContract] ([FlexContractId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_FlexCommunication] add  foreign key([DocTemplateId]) references [CNF_DocTemplate] ([DocTemplateId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.134</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Create table DATA_DocBatch</REASON>
			<TABLENAMES>DATA_DocBatch=DocBatchId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [DATA_DocBatch] (
	[DocBatchId] Integer Identity(1,1) NOT NULL,
	[BatchStatus] Smallint NOT NULL,
	[EntityTable] Smallint NOT NULL,
	[EntityId] Integer NOT NULL,
	[CreateDateTime] Datetime NOT NULL,
	[CreateWorkstationId] Integer NOT NULL,
	[CreateUserId] Integer NOT NULL,
	[ExecuteDateTime] Datetime NULL,
	[ExecuteUserId] Integer NULL,
	[ExecuteWorkstationId] Integer NULL,
	[EndDateTime] Datetime NULL,
	[ReportProcessXML] Ntext NOT NULL,
Primary Key  ([DocBatchId])
) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_DocBatch] add  foreign key([CreateUserId]) references [CNF_User] ([UserId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_DocBatch] add  foreign key([ExecuteUserId]) references [CNF_User] ([UserId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_DocBatch] add  foreign key([CreateWorkstationId]) references [CNF_Workstation] ([WorkstationId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_DocBatch] add  foreign key([ExecuteWorkstationId]) references [CNF_Workstation] ([WorkstationId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create Index [IDX_DocBatch_Entity]  ON [DATA_DocBatch] ([EntityTable] ,[EntityId] ) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create Index [IDX_DocBatch_Status]  ON [DATA_DocBatch] ([BatchStatus] ) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.133</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add tables:
- CNF_MatrixSheet
- CNF_MatrixSheet2Attribute</REASON>
			<TABLENAMES>CNF_MatrixSheet=MatrixSheetId
CNF_MatrixSheet2Attribute=MatrixSheet2AttributeId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_MatrixSheet] (
	[MatrixSheetId] Integer Identity(1,1) NOT NULL,
	[EventId] Integer NOT NULL,
	[MatrixSheetName] Nvarchar(30) NOT NULL,
	[ProductType] Smallint NOT NULL,
	[Color] Varchar(7) NULL,
	[Position] Smallint NOT NULL,
Primary Key  ([MatrixSheetId])
) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_MatrixSheet] add  foreign key([EventId]) references [CNF_Event] ([EventId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_MatrixSheet2Attribute] (
	[MatrixSheet2AttributeId] Integer Identity(1,1) NOT NULL,
	[MatrixSheetId] Integer NOT NULL,
	[AttributeId] Integer NOT NULL,
Primary Key  ([MatrixSheet2AttributeId])
) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_MatrixSheet2Attribute] add  foreign key([MatrixSheetId]) references [CNF_MatrixSheet] ([MatrixSheetId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_MatrixSheet2Attribute] add  foreign key([AttributeId]) references [CNF_Attribute] ([AttributeId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.132</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Removes tables CNF_Event2Attribute and CNF_Event2PriceList</REASON>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>drop table CNF_Event2Attribute
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>drop table CNF_Event2PriceList
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.131</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>drop field AttributeAK and index Key1 from table CNF_Attribute</REASON>
			<TABLENAMES>CNF_Attribute=AttributeId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>DROP INDEX CNF_Attribute.Key1
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Attribute
drop column AttributeAK
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.130</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add field EventId to table CNF_AttributeTemplate</REASON>
			<TABLENAMES>CNF_AttributeTemplate=AttributeTemplateId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_AttributeTemplate
add EventId int null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_AttributeTemplate] add  foreign key([EventId]) references [CNF_Event] ([EventId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.129</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add field ParentId to table CNF_AttributeTemplate</REASON>
			<TABLENAMES>CNF_AttributeTemplate=AttributeTemplateId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_AttributeTemplate
add ParentId int null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_AttributeTemplate] add  foreign key([ParentId]) references [CNF_AttributeTemplate] ([AttributeTemplateId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.128</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add fields FromStatus, Approved and ApprovalDateTime to table CNF_ApprovalEntity</REASON>
			<TABLENAMES>CNF_ApprovalEntity=ApprovalEntityId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_ApprovalEntity
add FromStatus smallint null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_ApprovalEntity
add Approved smallint null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_ApprovalEntity
set Approved=0, FromStatus=0
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_ApprovalEntity
alter column Approved smallint not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_ApprovalEntity
alter column FromStatus smallint not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_ApprovalEntity
add ApprovalDateTime datetime null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.127</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add tables:

- CNF_ApprovalEntity
- CNF_ApprovalFlag
			</REASON>
			<TABLENAMES>CNF_ApprovalEntity=ApprovalEntityId
CNF_ApprovalFlag=ApprovalFlagId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_ApprovalEntity] (
	[ApprovalEntityId] Integer Identity(1,1) NOT NULL,
	[EntityTable] Smallint NOT NULL,
	[EntityId] Integer NOT NULL,
	[TargetStatus] Smallint NOT NULL,
	[ApprovalFlowId] Integer NOT NULL,
Primary Key  ([ApprovalEntityId])
) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_ApprovalEntity] add  foreign key([ApprovalFlowId]) references [CNF_ApprovalFlow] ([ApprovalFlowId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_ApprovalFlag] (
	[ApprovalFlagId] Integer Identity(1,1) NOT NULL,
	[ApprovalEntityId] Integer NOT NULL,
	[UserGroupId] Integer NOT NULL,
	[Approved] Smallint NOT NULL,
	[UserId] Integer NULL,
	[WorkstationId] Integer NULL,
	[ApprovalDateTime] Datetime NULL,
Primary Key  ([ApprovalFlagId])
) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_ApprovalFlag] add  foreign key([ApprovalEntityId]) references [CNF_ApprovalEntity] ([ApprovalEntityId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_ApprovalFlag] add  foreign key([WorkstationId]) references [CNF_Workstation] ([WorkstationId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_ApprovalFlag] add  foreign key([UserGroupId]) references [CNF_UserGroup] ([UserGroupId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_ApprovalFlag] add  foreign key([UserId]) references [CNF_User] ([UserId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.126</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add field Enabled to table CNF_ApprovalFlow</REASON>
			<TABLENAMES>CNF_ApprovalFlow=ApprovalFlowId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_ApprovalFlow
add Enabled smallint null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_ApprovalFlow
set Enabled=1
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_ApprovalFlow
alter column Enabled smallint not null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.125</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Updates the Product Status field value</REASON>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_Product
set ProductStatus=3
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.124</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add tables
- CNF_ApprovalFlow
- CNF_ApprovalFlow2UserGroup</REASON>
			<TABLENAMES>CNF_ApprovalFlow=ApprovalFlowId
CNF_ApprovalFlow2UserGroup=ApprovalFlow2UserGroupId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_ApprovalFlow] (
	[ApprovalFlowId] Integer Identity(1,1) NOT NULL,
	[ApprovalFlowCode] Nvarchar(10) NOT NULL,
	[ApprovalFlowName] Nvarchar(50) NOT NULL,
	[Description] Ntext NULL,
Primary Key  ([ApprovalFlowId])
) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_ApprovalFlow2UserGroup] (
	[ApprovalFlow2UserGroupId] Integer Identity(1,1) NOT NULL,
	[ApprovalFlowId] Integer NOT NULL,
	[UserGroupId] Integer NOT NULL,
Primary Key  ([ApprovalFlow2UserGroupId])
) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_ApprovalFlow2UserGroup] add  foreign key([UserGroupId]) references [CNF_UserGroup] ([UserGroupId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_ApprovalFlow2UserGroup] add  foreign key([ApprovalFlowId]) references [CNF_ApprovalFlow] ([ApprovalFlowId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.123</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add field UserGroupType to table CNF_UserGroup</REASON>
			<TABLENAMES>CNF_UserGroup=UserGroupId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_UserGroup
add UserGroupType smallint null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_UserGroup
set UserGroupType=1
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_UserGroup
alter column UserGroupType smallint not null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Saverio Pangallo</ADDEDBY>
			<SQLVERSION>1.122</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>DeviceId and WorkstationId nullable</REASON>
			<TABLENAMES>DATA_PaymentCard=PaymentId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_PaymentCard
alter column DeviceId int null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_PaymentCard
alter column WorkstationId int null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Saverio Pangallo</ADDEDBY>
			<SQLVERSION>1.121</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add default to CNF_Device and foreign key nullable form CNF_PaymentCard to CNF_Device</REASON>
			<TABLENAMES>CNF_Device=DeviceId
CNF_PaymentCard=PaymentCardId
DATA_PaymentCard=PaymentId
			</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Device
add DefaultLevel smallint null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_PaymentCard
add DeviceId int null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_PaymentCard] add foreign key([DeviceId]) references [CNF_Device] ([DeviceId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>delete DATA_PaymentCard
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_PaymentCard
alter column PaymentCardId int not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_PaymentCard
add DeviceId int not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_PaymentCard
add WorkstationId int not null

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_PaymentCard] add foreign key([DeviceId]) references [CNF_Device] ([DeviceId])
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_PaymentCard] add foreign key([WorkstationId]) references [CNF_Workstation] ([WorkstationId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.120</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add table DATA_HistoryLog</REASON>
			<TABLENAMES>DATA_HistoryLog=HistoryLogId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [DATA_HistoryLog] (
	[HistoryLogId] Integer Identity(1,1) NOT NULL,
	[EntityTable] Smallint NOT NULL,
	[EntityId] Integer NOT NULL,
	[LogDateTime] Datetime NOT NULL,
	[WorkstationId] Integer NOT NULL,
	[UserId] Integer NOT NULL,
	[DataXML] Ntext NULL,
Primary Key  ([HistoryLogId])
) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create Index [IDX_HistoryLog_Entity]  ON [DATA_HistoryLog] ([EntityTable] ,[EntityId] ) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_HistoryLog] add  foreign key([UserId]) references [CNF_User] ([UserId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_HistoryLog] add  foreign key([WorkstationId]) references [CNF_Workstation] ([WorkstationId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Saverio Pangallo</ADDEDBY>
			<SQLVERSION>1.119</SQLVERSION>
			<RMTRACKLINK/>
			<REASON/>
			<TABLENAMES>ADM_AccessPoint=WorkstationId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table ADM_AccessPoint
add AptNum smallint null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.118</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Alter table CNF_Scheduler
- alter SchedulerNotes from ntext to nvarchar(250)
- add Configuration ntext
- add LastReference varchar(20)</REASON>
			<TABLENAMES>CNF_Scheduler=SchedulerId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Scheduler
alter column SchedulerNotes nvarchar(250) null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Scheduler
add Configuration NText null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Scheduler
add LastReference varchar(20) null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Saverio Pangallo</ADDEDBY>
			<SQLVERSION>1.117</SQLVERSION>
			<RMTRACKLINK/>
			<REASON/>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_Driver
set
  IconType=8  
where
  DriverType=4

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.116</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add field Status to table DATA_PaymentFlex</REASON>
			<TABLENAMES>DATA_PaymentFlex=PaymentId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_PaymentFlex
add Status smallint null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_PaymentFlex
set Status=1
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_PaymentFlex
alter column Status smallint not null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.115</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add fields to CNF_FlexContract

- MaxAttemptCount
- RetryAfterDays
- Enabled
- FirstInstallmentOffset
- MinItems
- MaxItems
			</REASON>
			<TABLENAMES>CNF_FlexContract=FlexContractId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_FlexContract
add
  MaxAttemptCount Smallint NULL,
  RetryAfterDays Smallint NULL,
  Enabled Smallint NULL,
  FirstInstallmentOffset Smallint NULL,
  MinItems Smallint NULL,
  MaxItems Smallint NULL

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_FlexContract
set
  MaxAttemptCount=3,
  RetryAfterDays=3,
  Enabled=1,
  MinItems=1
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_FlexContract
alter column MaxAttemptCount Smallint NOT NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_FlexContract
alter column RetryAfterDays Smallint NOT NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_FlexContract
alter column Enabled Smallint NOT NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_FlexContract
alter column MinItems Smallint NOT NULL
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.114</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add field RecursiveName to table CNF_DmgCategory</REASON>
			<TABLENAMES>CNF_DmgCategory=DmgCategoryId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_DmgCategory
add RecursiveName nvarchar(200) null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.113</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>- Add fields SuccessedCount, WarningCount, FailedCount to DATA_SchedulerLog
- Regenerates scripts for CNF_AttributeTemplate, CNF_Attribute</REASON>
			<TABLENAMES>DATA_SchedulerLog=SchedulerLogId
CNF_AttributeTemplate=AttributeTemplateId
CNF_Attribute=AttributeId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_SchedulerLog
add 
  SuccessedCount int null, 
  WarningCount int null, 
  FailedCount int null

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_SchedulerLog
set
  SuccessedCount=0,
  WarningCount=0,
  FailedCount=0

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_SchedulerLog
alter column SuccessedCount int not null

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_SchedulerLog
alter column WarningCount int not null

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_SchedulerLog
alter column FailedCount int not null

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.112</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Rename index Idx1 to IDX_Sale2Dmg_Unique and add the field SaleDmgType to it</REASON>
			<TABLENAMES>DATA_Sale2Dmg=Sale2DmgId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>drop index Idx1 on DATA_Sale2Dmg
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create UNIQUE Index [IDX_Sale2Dmg_Unique]  ON [DATA_Sale2Dmg] ([SaleId] ,[DmgId] ,[SaleDmgType] ) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.111</SQLVERSION>
			<RMTRACKLINK>474</RMTRACKLINK>
			<REASON>Add field DATA_Sale.Serial</REASON>
			<TABLENAMES>DATA_Sale=SaleId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Sale
add Serial int null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_Sale
set Serial=0
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Sale
alter column Serial int not null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.110</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Change field CNF_SeatCategory.Category from "not nullable" to "nullable"</REASON>
			<TABLENAMES>CNF_SeatCategory=SeatCategoryId
ADM_AccessConfiguration=AccessConfigurationId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_SeatCategory
alter column Category int null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.109</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Rename rights:
- DmgCategoryId  --&gt;  TicketDmgCategoryId
- DmgMandatoryOnSale  --&gt;  TicketDmgMandatoryOnSale</REASON>
			<TABLENAMES>CNF_Right=RightId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_Right
set RightAK='TicketDmgCategoryId'
where RightAK='DmgCategoryId'
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_Right
set RightAK='TicketDmgMandatoryOnSale'
where RightAK='DmgMandatoryOnSale'
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Antonella Mura</ADDEDBY>
			<SQLVERSION>1.108</SQLVERSION>
			<RMTRACKLINK>460</RMTRACKLINK>
			<REASON>Rename words 'Cheque' and 'Travellers Cheque' into 'Check' and 'Traveler's Check' in CNF_Driver's fields.</REASON>
			<TABLENAMES>CNF_Driver=DriverId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>UPDATE CNF_Driver
SET DriverAk = REPLACE(DriverAk, 'Cheque', 'Check'),
    Description = REPLACE(Description, 'Cheque', 'Check')
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>UPDATE CNF_Driver
SET DriverAk = REPLACE(DriverAk, 'Traveller', 'Travelers'),
    Description = REPLACE(Description, 'Travellers', 'Traveler''s')
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.107</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>table CNF_EnvelopeCapacity field RedundedRelQuantity renamed into RefundedRelQuantity</REASON>
			<TABLENAMES>CNF_EnvelopeCapacity=EnvelopeCapacityId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_EnvelopeCapacity
drop column RedundedRelQuantity
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_EnvelopeCapacity
add RefundedRelQuantity int null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_EnvelopeCapacity
set RefundedRelQuantity=0 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_EnvelopeCapacity
alter column RefundedRelQuantity int not null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.106</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add MaxQuantity to CNF_Capacity</REASON>
			<TABLENAMES>CNF_Capacity=CapacityId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Capacity
add MaxQuantity int null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.105</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Remove fields ProductId and AttributeSetId to table DATA_ShopCartItem</REASON>
			<TABLENAMES>DATA_ShopCartItem=ShopCartItemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @foreign_key_name nvarchar(max);
DECLARE @dropstmt nvarchar(max);

SELECT @foreign_key_name = f.name
  FROM sys.foreign_keys AS f
 INNER JOIN sys.foreign_key_columns AS fc 
    ON f.object_id = fc.constraint_object_id 
 WHERE f.parent_object_id = object_id(N'[dbo].[DATA_ShopCartItem]')
   AND f.referenced_object_id = object_id(N'[dbo].[CNF_Product]')
   AND COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'ProductId';

if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[DATA_ShopCartItem] DROP CONSTRAINT [' + @foreign_key_name + ']';
  execute sp_executesql @dropstmt
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @foreign_key_name nvarchar(max);
DECLARE @dropstmt nvarchar(max);

SELECT @foreign_key_name = f.name
  FROM sys.foreign_keys AS f
 INNER JOIN sys.foreign_key_columns AS fc 
    ON f.object_id = fc.constraint_object_id 
 WHERE f.parent_object_id = object_id(N'[dbo].[DATA_ShopCartItem]')
   AND f.referenced_object_id = object_id(N'[dbo].[CNF_AttributeSet]')
   AND COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'AttributeSetId';

if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[DATA_ShopCartItem] DROP CONSTRAINT [' + @foreign_key_name + ']';
  execute sp_executesql @dropstmt
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_ShopCartItem
drop column ProductId
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_ShopCartItem
drop column AttributeSetId
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.104</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add fields ProductId and AttributeSetId to table DATA_ShopCartItem</REASON>
			<TABLENAMES>DATA_ShopCartItem=ShopCartItemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_ShopCartItem
add ProductId int not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_ShopCartItem] add  foreign key([ProductId]) references [CNF_Product] ([ProductId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_ShopCartItem
add AttributeSetId int not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_ShopCartItem] add  foreign key([AttributeSetId]) references [CNF_AttributeSet] ([AttributeSetId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.103</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>DATA_SaleItem2Performance: remove field CapacityId and add field EnvelopeCapacityId

Create unique index on CNF_EnvelopeCapacity</REASON>
			<TABLENAMES>DATA_SaleItem2Performance=SaleItem2PerformanceId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @foreign_key_name nvarchar(max);
DECLARE @dropstmt nvarchar(max);

SELECT @foreign_key_name = f.name
  FROM sys.foreign_keys AS f
 INNER JOIN sys.foreign_key_columns AS fc 
    ON f.object_id = fc.constraint_object_id 
 WHERE f.parent_object_id = object_id(N'[dbo].[DATA_SaleItem2Performance]')
   AND f.referenced_object_id = object_id(N'[dbo].[CNF_Capacity]')
   AND COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'CapacityId';

if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[DATA_SaleItem2Performance] DROP CONSTRAINT [' + @foreign_key_name + ']';
  execute sp_executesql @dropstmt
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_SaleItem2Performance
drop column CapacityId
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_SaleItem2Performance
add EnvelopeCapacityId int null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_SaleItem2Performance] add  foreign key([EnvelopeCapacityId]) references [CNF_EnvelopeCapacity] ([EnvelopeCapacityId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create UNIQUE Index [IDX_EnvelopeCapacity_Unique]  ON [CNF_EnvelopeCapacity] ([CapacityId] ,[EnvelopeId] ) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.102</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>[0..5] alter CNF_Capacity (drop EnvelopeId, QuantityType, Quantity) add (MaxQuantity, all stats counters)
[6..8] add table CNF_EnvelopeCapacity
[9] add field EnvelopeCapactyId to table DATA_ShopCartItem</REASON>
			<TABLENAMES>CNF_Capacity=CapacityId
CNF_EnvelopeCapacity=EnvelopeCapacityId
DATA_ShopCartItem=ShopCartItemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>delete from CNF_Capacity
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DROP INDEX IDX_Capacity_Unique ON CNF_Capacity
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @foreign_key_name nvarchar(max);
DECLARE @dropstmt nvarchar(max);

SELECT @foreign_key_name = f.name
  FROM sys.foreign_keys AS f
 INNER JOIN sys.foreign_key_columns AS fc 
    ON f.object_id = fc.constraint_object_id 
 WHERE f.parent_object_id = object_id(N'[dbo].[CNF_Capacity]')
   AND f.referenced_object_id = object_id(N'[dbo].[CNF_Envelope]')
   AND COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'EnvelopeId';

if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[CNF_Capacity] DROP CONSTRAINT [' + @foreign_key_name + ']';
  execute sp_executesql @dropstmt
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Capacity
drop column EnvelopeId
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Capacity
drop column QuantityType
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Capacity
drop column Quantity
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_EnvelopeCapacity] (
	[EnvelopeCapacityId] Integer Identity(1,1) NOT NULL,
	[CapacityId] Integer NOT NULL,
	[EnvelopeId] Integer NOT NULL,
	[QuantityType] Smallint NOT NULL,
	[Quantity] Integer NOT NULL,
	[InUseQuantity] Integer NOT NULL,
	[BookedQuantity] Integer NOT NULL,
	[PaidQuantity] Integer NOT NULL,
	[PrintedQuantity] Integer NOT NULL,
	[VoidedQuantity] Integer NOT NULL,
	[RefundedQuantity] Integer NOT NULL,
	[RedundedRelQuantity] Integer NOT NULL,
Primary Key  ([EnvelopeCapacityId])
) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_EnvelopeCapacity] add  foreign key([CapacityId]) references [CNF_Capacity] ([CapacityId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_EnvelopeCapacity] add  foreign key([EnvelopeId]) references [CNF_Envelope] ([EnvelopeId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_ShopCartItem
add EnvelopeCapacityId int not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_ShopCartItem] add  foreign key([EnvelopeCapacityId]) references [CNF_EnvelopeCapacity] ([EnvelopeCapacityId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.101</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>- Add field Quantity to DATA_ShopCartItem
- Add fields CapacityId to DATA_SaleItem2Performance
			</REASON>
			<TABLENAMES>DATA_ShopCartItem=ShopCartItemId
DATA_SaleItem2Performance=SaleItem2PerformanceId
			</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_ShopCartItem
add Quantity int not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_SaleItem2Performance 
add  CapacityId int null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_SaleItem2Performance] add  foreign key([CapacityId]) references [CNF_Capacity] ([CapacityId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.100</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Creates table DATA_ShopCartItem</REASON>
			<TABLENAMES>DATA_ShopCartItem=ShopCartItemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [DATA_ShopCartItem] (
	[ShopCartItemId] Integer Identity(1,1) NOT NULL,
	[WorkstationId] Integer NOT NULL,
	[UserId] Integer NOT NULL,
	[OperationDateTime] Datetime NOT NULL,
	[ItemGuid] Varchar(38) NOT NULL,
Primary Key  ([ShopCartItemId])
) 
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.99</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Removes tables CNF_Menu and CNF_Function</REASON>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @foreign_key_name nvarchar(max);
DECLARE @dropstmt nvarchar(max);

SELECT @foreign_key_name = f.name
  FROM sys.foreign_keys AS f
 INNER JOIN sys.foreign_key_columns AS fc 
    ON f.object_id = fc.constraint_object_id 
 WHERE f.parent_object_id = object_id(N'[dbo].[CNF_Menu]')
   AND f.referenced_object_id = object_id(N'[dbo].[CNF_Menu]')
   AND COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'MenuId';

if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[CNF_Menu] DROP CONSTRAINT [' + @foreign_key_name + ']';
  execute sp_executesql @dropstmt
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @foreign_key_name nvarchar(max);
DECLARE @dropstmt nvarchar(max);

SELECT @foreign_key_name = f.name
  FROM sys.foreign_keys AS f
 INNER JOIN sys.foreign_key_columns AS fc 
    ON f.object_id = fc.constraint_object_id 
 WHERE f.parent_object_id = object_id(N'[dbo].[CNF_Menu]')
   AND f.referenced_object_id = object_id(N'[dbo].[CNF_Function]')
   AND COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'FunctionId';

if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[CNF_Menu] DROP CONSTRAINT [' + @foreign_key_name + ']';
  execute sp_executesql @dropstmt
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT> drop table CNF_Menu
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>drop table CNF_Function
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.98</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add tables DATA_CapacityCounter and DATA_CapacityCounterRef</REASON>
			<TABLENAMES>DATA_CapacityCounter=CapacityCounterId
DATA_CapacityCounterRef=CapacityCounterRefId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [DATA_CapacityCounter] (
	[CapacityCounterId] Integer Identity(1,1) NOT NULL UNIQUE,
	[CapacityId] Integer NOT NULL,
	[CapacityCounterType] Smallint NOT NULL,
	[Quantity] Integer NOT NULL,
Primary Key  ([CapacityCounterId])
) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_CapacityCounter] add  foreign key([CapacityId]) references [CNF_Capacity] ([CapacityId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [DATA_CapacityCounterRef] (
	[CapacityCounterRefId] Integer Identity(1,1) NOT NULL,
	[CapacityCounterId] Integer NOT NULL,
	[EntityTable] Smallint NOT NULL,
	[EntityId] Integer NOT NULL,
Primary Key  ([CapacityCounterRefId])
) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_CapacityCounterRef] add  foreign key([CapacityCounterId]) references [DATA_CapacityCounter] ([CapacityCounterId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.97</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Field LocationId removed from CNF_Performance</REASON>
			<TABLENAMES>CNF_Performance=PerformanceId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @foreign_key_name nvarchar(max);
DECLARE @dropstmt nvarchar(max);

SELECT @foreign_key_name = f.name
  FROM sys.foreign_keys AS f
 INNER JOIN sys.foreign_key_columns AS fc 
    ON f.object_id = fc.constraint_object_id 
 WHERE f.parent_object_id = object_id(N'[dbo].[CNF_Performance]')
   AND f.referenced_object_id = object_id(N'[dbo].[CNF_Location]')
   AND COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'LocationId';

if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[CNF_Performance] DROP CONSTRAINT [' + @foreign_key_name + ']';
  execute sp_executesql @dropstmt
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Performance
drop column LocationId
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.96</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>DATA_DmgData:
- DataMaskId from (not null) to (nullable)
- Cleans some data</REASON>
			<TABLENAMES>DATA_DmgData=DmgDataId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_DmgData
alter column DataMaskId int null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_DmgData
set ObjType=Null
where ObjType=0
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_DmgData
set DataMaskId=Null
where ObjType is not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>delete from DATA_DmgData
where (DataMaskId is null) and (ObjType is null)
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.95</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add CNF_Event.LocationId</REASON>
			<TABLENAMES>CNF_Event=EventId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Event
add LocationId int null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Event] add  foreign key([LocationId]) references [CNF_Location] ([LocationId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.94</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add CNF_Event.AccessConfigurationId</REASON>
			<TABLENAMES>CNF_Event=EventId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Event
add AccessConfigurationId int null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Event] add  foreign key([AccessConfigurationId]) references [ADM_AccessConfiguration] ([AccessConfigurationId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.93</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>- Add tables CNF_SpaceStructure and CNF_Capacity</REASON>
			<TABLENAMES>CNF_SpaceStructure=SpaceStructureId
CNF_Capacity=CapacityId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_SpaceStructure] (
	[SpaceStructureId] Integer Identity(1,1) NOT NULL,
	[AccessConfigurationId] Integer NOT NULL,
	[ParentId] Integer NULL,
	[PriorityOrder] Smallint NOT NULL,
	[SpaceStructureType] Smallint NOT NULL,
	[Name] Nvarchar(50) NOT NULL,
	[QuantityMin] Integer NULL,
	[QuantityMax] Integer NULL,
Primary Key  ([SpaceStructureId])
) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_SpaceStructure] add  foreign key([AccessConfigurationId]) references [ADM_AccessConfiguration] ([AccessConfigurationId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_SpaceStructure] add  foreign key([ParentId]) references [CNF_SpaceStructure] ([SpaceStructureId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_Capacity] (
	[CapacityId] Integer Identity(1,1) NOT NULL,
	[EnvelopeId] Integer NULL,
	[PerformanceId] Integer NULL,
	[SpaceStructureId] Integer NOT NULL,
	[SeatCategoryId] Integer NOT NULL,
	[QuantityType] Smallint NOT NULL,
	[Quantity] Integer NULL,
Primary Key  ([CapacityId])
) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create UNIQUE Index [IDX_Capacity_Unique]  ON [CNF_Capacity] ([EnvelopeId] ,[PerformanceId] ,[SpaceStructureId] ,[SeatCategoryId] ) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Capacity] add  foreign key([EnvelopeId]) references [CNF_Envelope] ([EnvelopeId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Capacity] add  foreign key([PerformanceId]) references [CNF_Performance] ([PerformanceId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Capacity] add  foreign key([SpaceStructureId]) references [CNF_SpaceStructure] ([SpaceStructureId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Capacity] add  foreign key([SeatCategoryId]) references [CNF_SeatCategory] ([SeatCategoryId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.92</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>- Add ADM_AccessConfiguration.EnvelopeId
- Remove CNF_EnvelopeTable.EnvelopeId</REASON>
			<TABLENAMES>ADM_AccessConfiguration=AccessConfigurationId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table ADM_AccessConfiguration
add EnvelopeId int null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [ADM_AccessConfiguration] add  foreign key([EnvelopeId]) references [CNF_Envelope] ([EnvelopeId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @foreign_key_name nvarchar(max);
DECLARE @dropstmt nvarchar(max);

SELECT @foreign_key_name = f.name
  FROM sys.foreign_keys AS f
 INNER JOIN sys.foreign_key_columns AS fc 
    ON f.object_id = fc.constraint_object_id 
 WHERE f.parent_object_id = object_id(N'[dbo].[CNF_EnvelopeTable]')
   AND f.referenced_object_id = object_id(N'[dbo].[CNF_Envelope]')
   AND COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'EnvelopeId';

if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[CNF_EnvelopeTable] DROP CONSTRAINT [' + @foreign_key_name + ']';
  execute sp_executesql @dropstmt
end
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.91</SQLVERSION>
			<RMTRACKLINK/>
			<REASON/>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.90</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>- CNF_SeatCategory.Color  from INT to VARCHAR

- CNF_Envelope
  1. Remove field EnvelopeNumber
  2. Add field HoldCode
  3. Add field Color</REASON>
			<TABLENAMES>CNF_SeatCategory=SeatCategoryId
CNF_Envelope=EnvelopeId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_SeatCategory
alter column Color varchar(10) null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>drop Index UQ_CNF_Envelope_EnvelopeNumber ON CNF_Envelope

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Envelope
drop column EnvelopeNumber
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Envelope
add HoldCode nvarchar(10) null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Envelope
add Color varchar(10) null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create Index [UQ_CNF_Envelope_EnvelopeNumber]  ON [CNF_Envelope] ([SystemId] ,[HoldCode] ) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.89</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add table CNF_SeatCategory
			</REASON>
			<TABLENAMES>CNF_SeatCategory=SeatCategoryId
			</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_SeatCategory] (
	[SeatCategoryId] Integer Identity(1,1) NOT NULL UNIQUE,
	[AccessConfigurationId] Integer NOT NULL,
	[Name] Nvarchar(30) NOT NULL,
	[Quantity] Integer NOT NULL,
	[Category] Integer NOT NULL,
	[Color] Integer NULL,
	[AttributeId] Integer NULL,
Primary Key  ([SeatCategoryId])
) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_SeatCategory] add  foreign key([AccessConfigurationId]) references [ADM_AccessConfiguration] ([AccessConfigurationId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_SeatCategory] add  foreign key([AttributeId]) references [CNF_Attribute] ([AttributeId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.88</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>- Add CNF_Envelope.SystemId
- Add unique index for EnvelopeNumber</REASON>
			<TABLENAMES>CNF_Envelope=EnvelopeId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>delete from CNF_Envelope
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Envelope
add SystemId int not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Envelope] add  foreign key([SystemId]) references [CNF_System] ([SystemId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create Index [UQ_CNF_Envelope_EnvelopeNumber]  ON [CNF_Envelope] ([SystemId] ,[EnvelopeNumber] ) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.87</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Create table CNF_Envelope</REASON>
			<TABLENAMES>CNF_Envelope=EnvelopeId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_Envelope] (
	[EnvelopeId] Integer Identity(1,1) NOT NULL UNIQUE,
	[EnvelopeType] Smallint NOT NULL,
	[ParentId] Integer NULL,
	[EnvelopeNumber] Integer NOT NULL,
	[Name] Nvarchar(50) NOT NULL,
Primary Key  ([EnvelopeId])
)
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Saverio Pangallo</ADDEDBY>
			<SQLVERSION>1.86</SQLVERSION>
			<RMTRACKLINK>432</RMTRACKLINK>
			<REASON/>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_Driver
set 
  DllName='DrvDevCommon.dll'
where 
  (DllName='DrvDemo.dll') or 
  (DllName='DrvAutDemo.dll') or   
  (DllName='DrvPrnExternalTck.dll')
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.85</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Removes DATA_IndividualVoucher.DmgId</REASON>
			<TABLENAMES>DATA_IndividualVoucher=IndividualVoucherId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @foreign_key_name nvarchar(max);
DECLARE @dropstmt nvarchar(max);

SELECT @foreign_key_name = f.name
  FROM sys.foreign_keys AS f
 INNER JOIN sys.foreign_key_columns AS fc 
    ON f.object_id = fc.constraint_object_id 
 WHERE f.parent_object_id = object_id(N'[dbo].[DATA_IndividualVoucher]')
   AND f.referenced_object_id = object_id(N'[dbo].[DATA_Dmg]')
   AND COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'DmgId';

if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[DATA_IndividualVoucher] DROP CONSTRAINT [' + @foreign_key_name + ']';
  execute sp_executesql @dropstmt
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_IndividualVoucher
drop column DmgId
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.84</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Rigenerate stored procs for tables DATA_IndividualVoucher and DATA_IndividualVoucherItem</REASON>
			<TABLENAMES>DATA_IndividualVoucher=IndividualVoucherId
DATA_IndividualVoucherItem=IndividualVoucherItemId</TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.83</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add field ParentId to DATA_SaleItem</REASON>
			<TABLENAMES>DATA_SaleItem=SaleItemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_SaleItem
add ParentId int null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_SaleItem] add  foreign key([ParentId]) references [DATA_SaleItem] ([SaleItemId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.82</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>[0..1] Add field SaleItemId to DATA_IndividualVoucher
[2..3] Add field SaleItemId to DATA_IndividualVoucherItem
[4..6] Remove fields TransAmount, VoucherType, VoucherNumber from table DATA_PaymentVoucher
[7..8] Add field IndividualVoucherId to DATA_PaymentVoucher</REASON>
			<TABLENAMES>DATA_IndividualVoucher=IndividualVoucherId
DATA_IndividualVoucherItem=IndividualVoucherItemId
DATA_PaymentVoucher=PaymentId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_IndividualVoucher
add SaleItemId int null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_IndividualVoucher] add  foreign key([SaleItemId]) references [DATA_SaleItem] ([SaleItemId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_IndividualVoucherItem
add SaleItemId int null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_IndividualVoucherItem] add  foreign key([SaleItemId]) references [DATA_SaleItem] ([SaleItemId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_PaymentVoucher
drop column TransAmount
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_PaymentVoucher
drop column VoucherType
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_PaymentVoucher
drop column VoucherNumber
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>delete from DATA_PaymentVoucher
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_PaymentVoucher
add IndividualVoucherId int not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_PaymentVoucher] add  foreign key([IndividualVoucherId]) references [DATA_IndividualVoucher] ([IndividualVoucherId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.81</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Create tables DATA_IndividualVoucher and DATA_IndividualVoucherItem</REASON>
			<TABLENAMES>DATA_IndividualVoucher=IndividualVoucherId
DATA_IndividualVoucherItem=IndividualVoucherItemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [DATA_IndividualVoucher] (
	[IndividualVoucherId] Integer Identity(1,1) NOT NULL,
	[DmgId] Integer NOT NULL,
	[ProductId] Integer NOT NULL,
	[IndividualVoucherCode] Varchar(32) NOT NULL,
	[ValidFrom] Datetime NULL,
	[ValidTo] Datetime NULL,
	[MaxItems] Smallint NULL,
	[MaxAmount] Float NULL,
	[Status] Smallint NOT NULL,
Primary Key  ([IndividualVoucherId])
)
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_IndividualVoucher] add  foreign key([DmgId]) references [DATA_Dmg] ([DmgId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_IndividualVoucher] add  foreign key([ProductId]) references [CNF_Voucher] ([ProductId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [DATA_IndividualVoucherItem] (
	[IndividualVoucherItemId] Integer Identity(1,1) NOT NULL,
	[IndividualVoucherId] Integer NOT NULL,
	[ProductId] Integer NOT NULL,
	[AttributeSetId] Integer NOT NULL,
	[MinQuantity] Smallint NULL,
	[MaxQuantity] Smallint NULL,
Primary Key  ([IndividualVoucherItemId])
) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_IndividualVoucherItem] add  foreign key([IndividualVoucherId]) references [DATA_IndividualVoucher] ([IndividualVoucherId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_IndividualVoucherItem] add  foreign key([AttributeSetId]) references [CNF_AttributeSet] ([AttributeSetId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_IndividualVoucherItem] add  foreign key([ProductId]) references [CNF_Product] ([ProductId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.80</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>add field DmgSubType to DATA_Dmg</REASON>
			<TABLENAMES>DATA_Dmg=DmgId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT> alter table DATA_Dmg 
 add DmgSubType smallint null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.79</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add field PriceListId to DATA_Dmg</REASON>
			<TABLENAMES>DATA_Dmg=DmgId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Dmg
add PriceListId int null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_Dmg] add  foreign key([PriceListId]) references [CNF_PriceList] ([PriceListId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Antonella Mura</ADDEDBY>
			<SQLVERSION>1.78</SQLVERSION>
			<RMTRACKLINK>410</RMTRACKLINK>
			<REASON>0. Rename field ItemValue into ItemCode and ItemName into ItemDescription
1. populate ItemCode with MaskTableItemId
2. Change MaskDescription to not nullable
3. Change ItemCode to Unique

			</REASON>
			<TABLENAMES>CNF_MaskTableItem=MaskTableItemId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>EXEC sp_rename 'CNF_MaskTableItem.ItemName', 'ItemDescription', 'COLUMN'
EXEC sp_rename 'CNF_MaskTableItem.ItemValue', 'ItemCode', 'COLUMN'
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>select cast(MaskTableItemId as Integer) as ItemId, identity(int,1,1) as RowNum
into #tempMaskTableItem
from CNF_MaskTableItem

update CNF_MaskTableItem
set ItemCode = RowNum
from #tempMaskTableItem
where MaskTableItemId=ItemId
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_MaskTableItem
alter column ItemCode nvarchar(30) not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create UNIQUE Index [UQ_CNF_MaskTableItem_ItemCode]  ON [CNF_MaskTableItem] ([ItemCode] )
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.77</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>clean some data for rights linked to products</REASON>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>delete from DATA_Right
where 
  DestType &lt;&gt; 130 and
  RightId in (
    select RightId
    from CNF_Right
    where RightAK in ('DmgCategoryId', 'ForceDmgSecondUsage', 'DmgMandatoryOnSale')
  )

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Antonella Mura</ADDEDBY>
			<SQLVERSION>1.76</SQLVERSION>
			<RMTRACKLINK>411</RMTRACKLINK>
			<REASON>Remove field MaskCode from CNF_Mask</REASON>
			<TABLENAMES>CNF_Mask=MaskId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Mask
drop column MaskCode
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.75</SQLVERSION>
			<RMTRACKLINK>#316</RMTRACKLINK>
			<REASON>Add field PriorityOrder to CNF_PaymentMethod</REASON>
			<TABLENAMES>CNF_PaymentMethod=PaymentMethodId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_PaymentMethod
add PriorityOrder smallint null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>select cast(PaymentMethodId as Integer) as PayId, identity(int,1,1) as RowNum
into #tempPM
from CNF_PaymentMethod

update CNF_PaymentMethod
set PriorityOrder = RowNum
from #tempPM
where PaymentMethodId=PayId
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_PaymentMethod
alter column PriorityOrder smallint not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create UNIQUE Index [UQ_CNF_PaymentMethod_PriorityOrder]  ON [CNF_PaymentMethod] ([PriorityOrder] ) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.74</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add DATA_PaymentFlex.PaymentFlexAK</REASON>
			<TABLENAMES>DATA_PaymentFlex=PaymentId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_PaymentFlex
add PaymentFlexAK varchar(32) null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_PaymentFlex
set PaymentFlexAK=replace(cast(newid() as varchar(max)), '-', '')
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_PaymentFlex
alter column PaymentFlexAK varchar(32) not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create UNIQUE Index [UQ_PaymentFlex_PaymentFlexAK]  ON [DATA_PaymentFlex] ([PaymentFlexAK] ) 
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.73</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Updates to for authorizator changes</REASON>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_PaymentMethod
set Enabled=0
where 
  DriverId in (
    select DriverId    
    from CNF_Driver    
    where DriverType=3
  )
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_Driver
set 
  DriverType=1,
  DriverSubType=8, 
  IconType=7
where DriverType=3
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_Workstation
set Enabled=0
where WorkstationType=2
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_Driver
set FamilyType=134
where
  DllName='DrvAutDEMO.dll'
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_Driver
set FamilyType=135
where
  DllName='DrvAutICVerify.dll'
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.72</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Change the auth drivers AKs</REASON>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_Driver
set DriverAK='TDrvAutDemo'
where DriverAK='DemoAuth'
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_Driver
set DriverAK='TDrvAutICVerify'
where DriverAK='ICVerify'
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_Driver
set DriverAK='TDrvAutShift4'
where DriverAK='Shift4'
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_Driver
set DriverAK='TDrvAutStratus'
where DriverAK='Stratus'
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.71</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add field WorkstationId to tables CNF_Scheduler and DATA_SchedulerLog</REASON>
			<TABLENAMES>CNF_Scheduler=SchedulerId
DATA_SchedulerLog=SchedulerLogId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>delete from CNF_Scheduler
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Scheduler
add WorkstationId int not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Scheduler] add  foreign key([WorkstationId]) references [CNF_Workstation] ([WorkstationId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>delete from DATA_SchedulerLog
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_SchedulerLog
add WorkstationId int not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_SchedulerLog] add  foreign key([WorkstationId]) references [CNF_Workstation] ([WorkstationId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.70</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Regenerate Payment tables for bug fixed in the storedproc generation procedure</REASON>
			<TABLENAMES>DATA_Payment=PaymentId
DATA_PaymentFlex=PaymentId</TABLENAMES>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.69</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>- removed  DATA_PaymentFlex2PaymentAccount
- Added field PaymentAccountId to table DATA_PaymentFlex</REASON>
			<TABLENAMES>DATA_PaymentFlex=PaymentId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>drop table DATA_PaymentFlex2PaymentAccount
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>delete from DATA_PaymentFlex
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>delete from DATA_PaymentPlan2Transaction
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>delete from DATA_PaymentPlan
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_PaymentFlex
add PaymentAccountId int not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_PaymentFlex] add  foreign key([PaymentAccountId]) references [DATA_PaymentAccount] ([PaymentAccountId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Antonella Mura</ADDEDBY>
			<SQLVERSION>1.68</SQLVERSION>
			<RMTRACKLINK>120</RMTRACKLINK>
			<REASON>Change DATA_Box Overshort field , from nullable to not nullable</REASON>
			<TABLENAMES>DATA_Box=BoxId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_Box
set
  Overshort=0
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Box
alter column Overshort float not null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ettore Bottega</ADDEDBY>
			<SQLVERSION>1.67</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Remove old DOC_ tables (Document Manager 2 model in Case Studio).

Drop:
 0. VIEW VW_DOC_ReportDependencies 
 1. DOC_CntxReportParamAssignement
 2. DOC_ParamValue
 3. DOC_CntxReportParam
 4. DOC_ReportDependencies
 5. DOC_Param
 6. DOC_CntxReportItem
 7. DOC_RepositoryItem
 8. DOC_CntxReport
 9. DOC_Report
10. DOC_Device
11. DOC_ReportValidity
12. DOC_CntxReportGroup
13. DOC_CntxProperty
14. DOC_Cntx
15. DOC_CatalogValidity
16. DOC_DeviceCatalog
17. DOC_ReportCatalog
18. DOC_Catalog
19. DOC_ReportType

20..76 stored procedures</REASON>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>DROP VIEW [VW_DOC_ReportDependencies]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[DOC_CntxReportParamAssignement]') AND type in (N'U'))
DROP TABLE [dbo].[DOC_CntxReportParamAssignement]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[DOC_ParamValue]') AND type in (N'U'))
DROP TABLE [dbo].[DOC_ParamValue]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[DOC_CntxReportParam]') AND type in (N'U'))
DROP TABLE [dbo].[DOC_CntxReportParam]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[DOC_ReportDependencies]') AND type in (N'U'))
DROP TABLE [dbo].[DOC_ReportDependencies]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[DOC_Param]') AND type in (N'U'))
DROP TABLE [dbo].[DOC_Param]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[DOC_CntxReportItem]') AND type in (N'U'))
DROP TABLE [dbo].[DOC_CntxReportItem]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[DOC_RepositoryItem]') AND type in (N'U'))
DROP TABLE [dbo].[DOC_RepositoryItem]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[DOC_CntxReport]') AND type in (N'U'))
DROP TABLE [dbo].[DOC_CntxReport]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[DOC_Report]') AND type in (N'U'))
DROP TABLE [dbo].[DOC_Report]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[DOC_Device]') AND type in (N'U'))
DROP TABLE [dbo].[DOC_Device]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[DOC_ReportValidity]') AND type in (N'U'))
DROP TABLE [dbo].[DOC_ReportValidity]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[DOC_CntxReportGroup]') AND type in (N'U'))
DROP TABLE [dbo].[DOC_CntxReportGroup]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[DOC_CntxProperty]') AND type in (N'U'))
DROP TABLE [dbo].[DOC_CntxProperty]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[DOC_Cntx]') AND type in (N'U'))
DROP TABLE [dbo].[DOC_Cntx]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[DOC_CatalogValidity]') AND type in (N'U'))
DROP TABLE [dbo].[DOC_CatalogValidity]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[DOC_DeviceCatalog]') AND type in (N'U'))
DROP TABLE [dbo].[DOC_DeviceCatalog]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[DOC_ReportCatalog]') AND type in (N'U'))
DROP TABLE [dbo].[DOC_ReportCatalog]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[DOC_Catalog]') AND type in (N'U'))
DROP TABLE [dbo].[DOC_Catalog]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[DOC_ReportType]') AND type in (N'U'))
DROP TABLE [dbo].[DOC_ReportType]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_ui_DOC_CntxReportParamAssignement_delete]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_ui_DOC_CntxReportParamAssignement_delete]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_ui_DOC_CntxReportParamAssignement_insert]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_ui_DOC_CntxReportParamAssignement_insert]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_ui_DOC_CntxReportParamAssignement_update]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_ui_DOC_CntxReportParamAssignement_update]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_ui_DOC_ParamValue_delete]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_ui_DOC_ParamValue_delete]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_ui_DOC_ParamValue_insert]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_ui_DOC_ParamValue_insert]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_ui_DOC_ParamValue_update]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_ui_DOC_ParamValue_update]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_ui_DOC_CntxReportParam_delete]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_ui_DOC_CntxReportParam_delete]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_ui_DOC_CntxReportParam_insert]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_ui_DOC_CntxReportParam_insert]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_ui_DOC_CntxReportParam_update]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_ui_DOC_CntxReportParam_update]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_ui_DOC_ReportDependencies_delete]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_ui_DOC_ReportDependencies_delete]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_ui_DOC_ReportDependencies_insert]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_ui_DOC_ReportDependencies_insert]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_ui_DOC_ReportDependencies_update]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_ui_DOC_ReportDependencies_update]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_ui_DOC_Param_delete]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_ui_DOC_Param_delete]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_ui_DOC_Param_insert]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_ui_DOC_Param_insert]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_ui_DOC_Param_update]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_ui_DOC_Param_update]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_ui_DOC_CntxReportItem_delete]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_ui_DOC_CntxReportItem_delete]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_ui_DOC_CntxReportItem_insert]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_ui_DOC_CntxReportItem_insert]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_ui_DOC_CntxReportItem_update]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_ui_DOC_CntxReportItem_update]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_ui_DOC_RepositoryItem_delete]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_ui_DOC_RepositoryItem_delete]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_ui_DOC_RepositoryItem_insert]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_ui_DOC_RepositoryItem_insert]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_ui_DOC_RepositoryItem_update]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_ui_DOC_RepositoryItem_update]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_ui_DOC_CntxReport_delete]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_ui_DOC_CntxReport_delete]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_ui_DOC_CntxReport_insert]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_ui_DOC_CntxReport_insert]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_ui_DOC_CntxReport_update]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_ui_DOC_CntxReport_update]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_ui_DOC_Report_delete]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_ui_DOC_Report_delete]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_ui_DOC_Report_insert]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_ui_DOC_Report_insert]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_ui_DOC_Report_update]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_ui_DOC_Report_update]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_ui_DOC_Device_delete]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_ui_DOC_Device_delete]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_ui_DOC_Device_insert]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_ui_DOC_Device_insert]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_ui_DOC_Device_update]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_ui_DOC_Device_update]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_ui_DOC_ReportValidity_delete]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_ui_DOC_ReportValidity_delete]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_ui_DOC_ReportValidity_insert]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_ui_DOC_ReportValidity_insert]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_ui_DOC_ReportValidity_update]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_ui_DOC_ReportValidity_update]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_ui_DOC_CntxReportGroup_delete]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_ui_DOC_CntxReportGroup_delete]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_ui_DOC_CntxReportGroup_insert]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_ui_DOC_CntxReportGroup_insert]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_ui_DOC_CntxReportGroup_update]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_ui_DOC_CntxReportGroup_update]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_ui_DOC_CntxProperty_delete]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_ui_DOC_CntxProperty_delete]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_ui_DOC_CntxProperty_insert]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_ui_DOC_CntxProperty_insert]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_ui_DOC_CntxProperty_update]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_ui_DOC_CntxProperty_update]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_ui_DOC_Cntx_delete]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_ui_DOC_Cntx_delete]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_ui_DOC_Cntx_insert]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_ui_DOC_Cntx_insert]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_ui_DOC_Cntx_update]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_ui_DOC_Cntx_update]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_ui_DOC_CatalogValidity_delete]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_ui_DOC_CatalogValidity_delete]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_ui_DOC_CatalogValidity_insert]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_ui_DOC_CatalogValidity_insert]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_ui_DOC_CatalogValidity_update]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_ui_DOC_CatalogValidity_update]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_ui_DOC_DeviceCatalog_delete]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_ui_DOC_DeviceCatalog_delete]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_ui_DOC_DeviceCatalog_insert]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_ui_DOC_DeviceCatalog_insert]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_ui_DOC_DeviceCatalog_update]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_ui_DOC_DeviceCatalog_update]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_ui_DOC_ReportCatalog_delete]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_ui_DOC_ReportCatalog_delete]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_ui_DOC_ReportCatalog_insert]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_ui_DOC_ReportCatalog_insert]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_ui_DOC_ReportCatalog_update]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_ui_DOC_ReportCatalog_update]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_ui_DOC_Catalog_delete]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_ui_DOC_Catalog_delete]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_ui_DOC_Catalog_insert]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_ui_DOC_Catalog_insert]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_ui_DOC_Catalog_update]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_ui_DOC_Catalog_update]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_ui_DOC_ReportType_delete]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_ui_DOC_ReportType_delete]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_ui_DOC_ReportType_insert]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_ui_DOC_ReportType_insert]

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_ui_DOC_ReportType_update]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_ui_DOC_ReportType_update]

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Antonella Mura</ADDEDBY>
			<SQLVERSION>1.66</SQLVERSION>
			<RMTRACKLINK>120</RMTRACKLINK>
			<REASON>Added Overshort field to DATA_Box
			</REASON>
			<TABLENAMES>DATA_Box=BoxId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Box
add Overshort float null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.65</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Creating:
- CNF_Scheduler
- DATA_SchedulerLog</REASON>
			<TABLENAMES>CNF_Scheduler=SchedulerId
DATA_SchedulerLog=SchedulerLogId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_Scheduler] (
	[SchedulerId] Integer Identity(1,1) NOT NULL,
	[SchedulerNotes] Ntext NULL,
	[DriverId] Integer NOT NULL,
	[TimeFrom] Datetime NULL,
	[TimeTo] Datetime NULL,
	[Interval] Smallint NOT NULL,
	[ActiveMonday] Smallint NOT NULL,
	[ActiveTuesday] Smallint NOT NULL,
	[ActiveWednesday] Smallint NOT NULL,
	[ActiveThursday] Smallint NOT NULL,
	[ActiveFriday] Smallint NOT NULL,
	[ActiveSaturday] Smallint NOT NULL,
	[ActiveSunday] Smallint NOT NULL,
	[Enabled] Smallint NOT NULL,
	[LastFire] Datetime NULL,
Primary Key  ([SchedulerId])
) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Scheduler] add  foreign key([DriverId]) references [CNF_Driver] ([DriverId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [DATA_SchedulerLog] (
	[SchedulerLogId] Integer Identity(1,1) NOT NULL,
	[LogType] Smallint NOT NULL,
	[DriverId] Integer NULL,
	[DateTimeBegin] Datetime NOT NULL,
	[DateTimeEnd] Datetime NULL,
	[LogState] Smallint NOT NULL,
	[LogMessage] Ntext NULL,
Primary Key  ([SchedulerLogId])
)
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_SchedulerLog] add  foreign key([DriverId]) references [CNF_Driver] ([DriverId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.64</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Tables for secure credit card info storing

DATA_PaymentAccount 
CNF_EncryptionKey
CNF_MasterKey</REASON>
			<TABLENAMES>DATA_PaymentAccount=PaymentAccountId
CNF_EncryptionKey=EncryptionKeyId
CNF_MasterKey=MasterKeyId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_PaymentAccount
alter column EncodingType smallint not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_PaymentAccount
add EncodingIndex int null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_EncryptionKey] (
	[EncryptionKeyId] Integer Identity(1,1) NOT NULL,
	[EncryptionKey] Varchar(100) NOT NULL,
	[Status] Smallint NULL,
Primary Key  ([EncryptionKeyId])
) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_MasterKey] (
	[MasterKeyId] Integer Identity(1,1) NOT NULL,
	[MasterKey] Varchar(100) NOT NULL,
Primary Key  ([MasterKeyId])
)
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.63</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>CNF_PaymentCardRange
fields FromNumber and ToNumber modified to varchar(20)</REASON>
			<TABLENAMES>CNF_PaymentCardRange=PaymentCardRangeId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_PaymentCardRange
alter column FromNumber varchar(20) not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_PaymentCardRange
alter column ToNumber varchar(20) not null
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.62</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>add FK to DATA_Payment.CurrencyId</REASON>
			<TABLENAMES/>
			<SQLSCRIPTLIST>
				<SCRIPT>delete from DATA_Payment
where
  CurrencyId not in (select CurrencyId from CNF_Currency)
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_Payment] add  foreign key([CurrencyId]) references [CNF_Currency] ([CurrencyId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.61</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Added fields to DATA_Payment
- CurrencyAmount
- ExchangeRate

Dropped table DATA_PaymentCash</REASON>
			<TABLENAMES>DATA_Payment=PaymentId</TABLENAMES>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Payment
add CurrencyAmount float null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Payment
add ExchangeRate float null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_Payment
set
  CurrencyAmount=PaymentAmount,  
  ExchangeRate=1
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Payment
alter column CurrencyAmount float not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Payment
alter column ExchangeRate float not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>drop table DATA_PaymentCash
				</SCRIPT>
			</SQLSCRIPTLIST>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.60</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add fields to DATA_Sale:
- PerformanceId
- PerformanceCount
- TicketCount</REASON>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Sale
add PerformanceId int
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_Sale] add  foreign key([PerformanceId]) references [CNF_Performance] ([PerformanceId]) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Sale
add PerformanceCount smallint

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_Sale
set PerformanceCount=0

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Sale
alter column PerformanceCount smallint not null

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Sale
alter column Quantity smallint not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Sale
add TicketCount smallint</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_Sale
set TicketCount=0</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Sale
alter column TicketCount smallint not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>	ALTER procedure [dbo].[sp_ui_DATA_Sale_insert]	
		@SaleId Integer output ,
		@SystemId Integer,
		@CurrencyId Integer,
		@ParentId Integer,
		@WorkstationId Integer,
		@UserId Integer,
		@DmgId Integer,
		@SaleType SmallInt,
		@SaleAK VarChar(32),
		@SaleDate DateTime,
		@FSaleDate DateTime,
		@StatusCode SmallInt,
		@Paid SmallInt,
		@Approved SmallInt,
		@Validated SmallInt,
		@Encoded SmallInt,
		@Completed SmallInt,
		@Quantity smallint,
		@TicketCount smallint,
		@TotalAmount Float,
		@TotalTaxes Float,
		@Revenue Float,
		@TaxRevenue Float,
		@PerformanceId Integer,
		@PerformanceCount Integer
	as
	begin
		insert into DATA_Sale
			(SystemId, CurrencyId, ParentId, WorkstationId, UserId, DmgId, SaleType, SaleAK, SaleDate, FSaleDate, StatusCode, Paid, Approved, Validated, Encoded, Completed, Quantity, TicketCount, TotalAmount, TotalTaxes, Revenue, TaxRevenue, PerformanceId, PerformanceCount)
		values 	
			(@SystemId,@CurrencyId,@ParentId,@WorkstationId,@UserId,@DmgId,@SaleType,@SaleAK,@SaleDate,@FSaleDate,@StatusCode,@Paid,@Approved,@Validated,@Encoded,@Completed,@Quantity,@TicketCount,@TotalAmount,@TotalTaxes,@Revenue,@TaxRevenue,@PerformanceId,@PerformanceCount)


		select @SaleId= SCOPE_IDENTITY() 


	end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>	ALTER procedure [dbo].[sp_ui_DATA_Sale_update]	
		@SaleId Integer,
		@SystemId Integer,
		@CurrencyId Integer,
		@ParentId Integer,
		@WorkstationId Integer,
		@UserId Integer,
		@DmgId Integer,
		@SaleType SmallInt,
		@SaleAK VarChar(32),
		@SaleDate DateTime,
		@FSaleDate DateTime,
		@StatusCode SmallInt,
		@Paid SmallInt,
		@Approved SmallInt,
		@Validated SmallInt,
		@Encoded SmallInt,
		@Completed SmallInt,
		@Quantity smallint,
		@TicketCount smallint,
		@TotalAmount Float,
		@TotalTaxes Float,
		@Revenue Float,
		@TaxRevenue Float,
		@PerformanceId Integer,
		@PerformanceCount smallint
	as
	begin
		update	DATA_Sale
		set	SystemId=@SystemId,
			CurrencyId=@CurrencyId,
			ParentId=@ParentId,
			WorkstationId=@WorkstationId,
			UserId=@UserId,
			DmgId=@DmgId,
			SaleType=@SaleType,
			SaleAK=@SaleAK,
			SaleDate=@SaleDate,
			FSaleDate=@FSaleDate,
			StatusCode=@StatusCode,
			Paid=@Paid,
			Approved=@Approved,
			Validated=@Validated,
			Encoded=@Encoded,
			Completed=@Completed,
			Quantity=@Quantity,
			TicketCount=@TicketCount,
			TotalAmount=@TotalAmount,
			TotalTaxes=@TotalTaxes,
			Revenue=@Revenue,
			TaxRevenue=@TaxRevenue,
			PerformanceId=@PerformanceId,
			PerformanceCount=@PerformanceCount
		where	SaleId=@SaleId

	end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.59</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>DATA_Ledger:

- Table emptied
- Removed field LedgerAccountType
- Added FK to CNF_LedgerAccount.LedgerAccountId
			</REASON>
			<SQLSCRIPTLIST>
				<SCRIPT>delete from DATA_Ledger</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Ledger
drop column LedgerAccountType</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_Ledger] add  foreign key([LedgerAccountId]) references [CNF_LedgerAccount] ([LedgerAccountId]) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER procedure [dbo].[sp_ui_DATA_Ledger_insert]	
	@LedgerId Integer output ,
	@SystemId Integer,
	@TransactionId Integer,
	@LedgerType SmallInt,
	@LedgerAccountId Integer,
	@EntryAmount Float,
	@EntryQuantity SmallInt,
	@ReferenceTable SmallInt,
	@ReferenceId Integer,
	@ReferenceAmount Float
as
begin
	insert into DATA_Ledger
		(TransactionId, SystemId, LedgerType, LedgerAccountId, EntryAmount, EntryQuantity, ReferenceTable, ReferenceId, ReferenceAmount)
	values 	
		(@TransactionId,@SystemId,@LedgerType,@LedgerAccountId,@EntryAmount,@EntryQuantity,@ReferenceTable,@ReferenceId, @ReferenceAmount)

	select @LedgerId= SCOPE_IDENTITY() 
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER procedure [dbo].[sp_ui_DATA_Ledger_update]	
	@LedgerId Integer,
	@SystemId Integer,
	@TransactionId Integer,
	@LedgerType SmallInt,
	@LedgerAccountId Integer,
	@EntryAmount Float,
	@EntryQuantity SmallInt,
	@ReferenceTable SmallInt,
	@ReferenceId Integer,
	@ReferenceAmount Float
as
begin
	update	DATA_Ledger
	set	TransactionId=@TransactionId,
		SystemId=@SystemId,
		LedgerType=@LedgerType,
		LedgerAccountId=@LedgerAccountId,
		EntryAmount=@EntryAmount,
		EntryQuantity=@EntryQuantity,
		ReferenceTable=@ReferenceTable,
		ReferenceId=@ReferenceId,
		ReferenceAmount=@ReferenceAmount
	where	LedgerId=@LedgerId
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.58</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add LedgerAccountAK to CNF_LedgerAccount</REASON>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_LedgerAccount
add LedgerAccountAK varchar(32) null</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_LedgerAccount
set LedgerAccountAK=replace(cast(newid() as varchar(max)), '-', '')</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_LedgerAccount
alter column LedgerAccountAK varchar(32) not null</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER procedure [dbo].[sp_ui_CNF_LedgerAccount_insert]	
	@LedgerAccountId Integer output ,
	@LedgerAccountAK varchar(32),
	@ParentAccountId integer,
	@AccountType SmallInt,
	@AccountCode NVarChar(30),
	@AccountName NVarChar(50),
	@AccountReportLiteral NVarChar(50),
	@AccountNotes NText,
	@SystemAccountTable SmallInt,
	@SystemAccountId Integer,
	@InheritSystemAccountName SmallInt
as
begin
	insert into CNF_LedgerAccount
		(LedgerAccountAK, ParentAccountId, AccountType, AccountCode, AccountName, AccountReportLiteral, AccountNotes, SystemAccountTable, SystemAccountId, InheritSystemAccountName)
	values 	
			(@LedgerAccountAK, @ParentAccountId,@AccountType,@AccountCode,@AccountName,@AccountReportLiteral,@AccountNotes,@SystemAccountTable,@SystemAccountId,@InheritSystemAccountName)


	select @LedgerAccountId= SCOPE_IDENTITY() 
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER procedure [dbo].[sp_ui_CNF_LedgerAccount_update]	
	@LedgerAccountId Integer,
	@LedgerAccountAK varchar(32),
	@ParentAccountId Integer,
	@AccountType SmallInt,
	@AccountCode NVarChar(30),
	@AccountName NVarChar(50),
	@AccountReportLiteral NVarChar(50),
	@AccountNotes NText,
	@SystemAccountTable SmallInt,
	@SystemAccountId Integer,
	@InheritSystemAccountName SmallInt
as
begin
	update	CNF_LedgerAccount
	set	LedgerAccountAK=@LedgerAccountAK,
		ParentAccountId=@ParentAccountId,
		AccountType=@AccountType,
		AccountCode=@AccountCode,
		AccountName=@AccountName,
		AccountReportLiteral=@AccountReportLiteral,
		AccountNotes=@AccountNotes,
		SystemAccountTable=@SystemAccountTable,
		SystemAccountId=@SystemAccountId,
		InheritSystemAccountName=@InheritSystemAccountName
	where	LedgerAccountId=@LedgerAccountId
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.57</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add DocData field to ARC_Document</REASON>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table ARC_Document
add DocData image null</SCRIPT>
			</SQLSCRIPTLIST>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Mirko Bianco</ADDEDBY>
			<SQLVERSION>1.56</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Changed  from CNF_User.NTUSER to CNF_User.NTUser</REASON>
			<SQLSCRIPTLIST>
				<SCRIPT>exec sp_RENAME 'CNF_User.NTUSER', 'NTUser' , 'COLUMN'</SCRIPT>
			</SQLSCRIPTLIST>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.55</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add field ParentAccountId to CNF_LedgerAccount</REASON>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_LedgerAccount
add ParentAccountId int</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table [CNF_LedgerAccount] add  foreign key([ParentAccountId]) references [CNF_LedgerAccount] ([LedgerAccountId]) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER procedure [dbo].[sp_ui_CNF_LedgerAccount_insert]	
	@LedgerAccountId Integer output ,
	@ParentAccountId integer,
	@AccountType SmallInt,
	@AccountCode NVarChar(30),
	@AccountName NVarChar(50),
	@AccountReportLiteral NVarChar(50),
	@AccountNotes NText,
	@SystemAccountTable SmallInt,
	@SystemAccountId Integer,
	@InheritSystemAccountName SmallInt
as
begin
	insert into CNF_LedgerAccount
		(ParentAccountId, AccountType, AccountCode, AccountName, AccountReportLiteral, AccountNotes, SystemAccountTable, SystemAccountId, InheritSystemAccountName)
	values 	
			(@ParentAccountId,@AccountType,@AccountCode,@AccountName,@AccountReportLiteral,@AccountNotes,@SystemAccountTable,@SystemAccountId,@InheritSystemAccountName)


	select @LedgerAccountId= SCOPE_IDENTITY() 
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER procedure [dbo].[sp_ui_CNF_LedgerAccount_update]	
	@LedgerAccountId Integer,
	@ParentAccountId Integer,
	@AccountType SmallInt,
	@AccountCode NVarChar(30),
	@AccountName NVarChar(50),
	@AccountReportLiteral NVarChar(50),
	@AccountNotes NText,
	@SystemAccountTable SmallInt,
	@SystemAccountId Integer,
	@InheritSystemAccountName SmallInt
as
begin
	update	CNF_LedgerAccount
	set	ParentAccountId=@ParentAccountId,
		AccountType=@AccountType,
		AccountCode=@AccountCode,
		AccountName=@AccountName,
		AccountReportLiteral=@AccountReportLiteral,
		AccountNotes=@AccountNotes,
		SystemAccountTable=@SystemAccountTable,
		SystemAccountId=@SystemAccountId,
		InheritSystemAccountName=@InheritSystemAccountName
	where	LedgerAccountId=@LedgerAccountId
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Mirko Bianco</ADDEDBY>
			<SQLVERSION>1.54</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Fixed a problem with CNF_USER table.
store procedure weren't up to date and not nullable value wasn't set.</REASON>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER procedure [dbo].[sp_ui_CNF_User_insert]	
	@UserId Integer output ,
	@UserAK VarChar(32),
	@UserType SmallInt,
	@Template SmallInt,
	@Enabled SmallInt,
	@UserName NVarChar(50),
	@UserCode NVarChar(50),
	@UserDescription NVarChar(50),
	@UserPassword NVarChar(50),
	@CreationDate DateTime,
	@OrganizationId Integer,
	@PasswordChange DateTime,
	@PasswordExpiration DateTime,
	@LastLogin DateTime,
	@LastChange DateTime,
	@MasterUserId Integer,
	@SystemId Integer,
	@NTUser SmallInt,
	@Note NText,
	@RoleNames nvarchar(1000)
as
begin
	insert into CNF_User
		(UserAK, UserType, Template, Enabled, UserName, UserCode, UserDescription, UserPassword, CreationDate, OrganizationId, PasswordChange, PasswordExpiration, LastLogin, LastChange, MasterUserId, SystemId, NTUser, Note, RoleNames)
	values 	
			(@UserAK,@UserType,@Template,@Enabled,@UserName,@UserCode,@UserDescription,@UserPassword,@CreationDate,@OrganizationId,@PasswordChange,@PasswordExpiration,@LastLogin,@LastChange,@MasterUserId,@SystemId,@NTUser,@Note,@RoleNames)


	select @UserId= SCOPE_IDENTITY() 

end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER procedure [dbo].[sp_ui_CNF_User_update]	
	@UserId Integer,
	@UserAK VarChar(32),
	@UserType SmallInt,
	@Template SmallInt,
	@Enabled SmallInt,
	@UserName NVarChar(50),
	@UserCode NVarChar(50),
	@UserDescription NVarChar(50),
	@UserPassword NVarChar(50),
	@CreationDate DateTime,
	@OrganizationId Integer,
	@PasswordChange DateTime,
	@PasswordExpiration DateTime,
	@LastLogin DateTime,
	@LastChange DateTime,
	@MasterUserId Integer,
	@SystemId Integer,
	@NTUser SmallInt,
	@Note NText,
	@RoleNames nvarchar(1000)
as
begin
	update	CNF_User
	set	UserAK=@UserAK,
		UserType=@UserType,
		Template=@Template,
		Enabled=@Enabled,
		UserName=@UserName,
		UserCode=@UserCode,
		UserDescription=@UserDescription,
		UserPassword=@UserPassword,
		CreationDate=@CreationDate,
		OrganizationId=@OrganizationId,
		PasswordChange=@PasswordChange,
		PasswordExpiration=@PasswordExpiration,
		LastLogin=@LastLogin,
		LastChange=@LastChange,
		MasterUserId=@MasterUserId,
		SystemId=@SystemId,
		NTUser=@NTUser,
		Note=@Note,
		RoleNames=@RoleNames
	where	UserId=@UserId
end

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_USER
set NTUSER=0 where NTUSER is null;</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE CNF_USER 
alter column NTUSER smallint NOT NULL;</SCRIPT>
			</SQLSCRIPTLIST>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.53</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add table CNF_LedgerAccount</REASON>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_LedgerAccount] (
	[LedgerAccountId] Integer Identity(1,1) NOT NULL,
	[AccountType] Smallint NOT NULL,
	[AccountCode] Nvarchar(30) NOT NULL,
	[AccountName] Nvarchar(50) NOT NULL,
	[AccountReportLiteral] Nvarchar(50) NULL,
	[AccountNotes] Ntext NULL,
	[SystemAccountTable] Smallint NULL,
	[SystemAccountId] Integer NULL,
	[InheritSystemAccountName] Smallint NOT NULL,
Primary Key  ([LedgerAccountId])
) </SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_ui_CNF_LedgerAccount_insert]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_ui_CNF_LedgerAccount_insert]
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_ui_CNF_LedgerAccount_update]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_ui_CNF_LedgerAccount_update]
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_ui_CNF_LedgerAccount_delete]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_ui_CNF_LedgerAccount_delete]
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>create procedure [dbo].[sp_ui_CNF_LedgerAccount_insert]	
	@LedgerAccountId Integer output ,
	@AccountType SmallInt,
	@AccountCode NVarChar(30),
	@AccountName NVarChar(50),
	@AccountReportLiteral NVarChar(50),
	@AccountNotes NText,
	@SystemAccountTable SmallInt,
	@SystemAccountId Integer,
	@InheritSystemAccountName SmallInt
as
begin
	insert into CNF_LedgerAccount
		(AccountType, AccountCode, AccountName, AccountReportLiteral, AccountNotes, SystemAccountTable, SystemAccountId, InheritSystemAccountName)
	values 	
			(@AccountType,@AccountCode,@AccountName,@AccountReportLiteral,@AccountNotes,@SystemAccountTable,@SystemAccountId,@InheritSystemAccountName)


	select @LedgerAccountId= SCOPE_IDENTITY() 
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>create procedure [dbo].[sp_ui_CNF_LedgerAccount_update]	
	@LedgerAccountId Integer,
	@AccountType SmallInt,
	@AccountCode NVarChar(30),
	@AccountName NVarChar(50),
	@AccountReportLiteral NVarChar(50),
	@AccountNotes NText,
	@SystemAccountTable SmallInt,
	@SystemAccountId Integer,
	@InheritSystemAccountName SmallInt
as
begin
	update	CNF_LedgerAccount
	set	AccountType=@AccountType,
		AccountCode=@AccountCode,
		AccountName=@AccountName,
		AccountReportLiteral=@AccountReportLiteral,
		AccountNotes=@AccountNotes,
		SystemAccountTable=@SystemAccountTable,
		SystemAccountId=@SystemAccountId,
		InheritSystemAccountName=@InheritSystemAccountName
	where	LedgerAccountId=@LedgerAccountId
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>create procedure [dbo].[sp_ui_CNF_LedgerAccount_delete]	
	@LedgerAccountId Integer	
as
begin
	delete from	CNF_LedgerAccount
	where	LedgerAccountId=@LedgerAccountId
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Mirko Bianco</ADDEDBY>
			<SQLVERSION>1.52</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>CNF_USER

changed the field NTUSER from varchar to boolean</REASON>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @constraint_name nvarchar(max);
DECLARE @dropstmt nvarchar(max);

SELECT @constraint_name = OBJECT_NAME(f.constid)
  FROM sys.sysconstraints AS f
where OBJECT_NAME(f.id)='CNF_User'
and OBJECT_NAME(f.constid) like 'DF_%';

if (len(@constraint_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[CNF_User] DROP CONSTRAINT [' + @constraint_name + ']';
  execute sp_executesql @dropstmt
end</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_USER
drop column NTUSER;</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_USER
add NTUSER smallint; </SCRIPT>
			</SQLSCRIPTLIST>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Antonella Mura</ADDEDBY>
			<SQLVERSION>1.51</SQLVERSION>
			<RMTRACKLINK>276</RMTRACKLINK>
			<REASON>0. add Field WorkstationId into DATA_Deposit
1. populate new field for existing records
2. set WorkstationId as not null
3. Create foreign key
4-5. Update DATA_Deposit's store procedures for new field
			</REASON>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Deposit 
add WorkstationId integer</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_Deposit
set DATA_Deposit.WorkstationId = DATA_Box.WorkstationId
from 
  DATA_Box
inner join
  DATA_Deposit
on (DATA_Box.BoxId = DATA_Deposit.BoxId)</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Deposit
alter column WorkstationId integer not null</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_Deposit] add foreign key([WorkstationId]) references [CNF_Workstation] ([WorkstationId]) </SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>	ALTER procedure [dbo].[sp_ui_DATA_Deposit_insert]	
		@DepositId Integer output ,
		@WorkstationId Integer,
		@BoxId Integer,
		@UserId Integer,
		@DepositType SmallInt,
		@DepositDate DateTime,
		@DepositAmount Float,
		@BagNumber Integer
	as
	begin
		insert into DATA_Deposit
			(WorkstationId, BoxId, UserId, DepositType, DepositDate, DepositAmount, BagNumber)
		values 	
			(@WorkstationId,@BoxId,@UserId,@DepositType,@DepositDate,@DepositAmount,@BagNumber)


		select @DepositId= SCOPE_IDENTITY() 


	end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>	ALTER procedure [dbo].[sp_ui_DATA_Deposit_update]	
		@DepositId Integer,
		@WorkstationId Integer,
		@BoxId Integer,
		@UserId Integer,
		@DepositType SmallInt,
		@DepositDate DateTime,
		@DepositAmount Float,
		@BagNumber Integer
	as
	begin
		update	DATA_Deposit
		set	WorkstationId=@WorkstationId,
			BoxId=@BoxId,
			UserId=@UserId,
			DepositType=@DepositType,
			DepositDate=@DepositDate,
			DepositAmount=@DepositAmount,
			BagNumber=@BagNumber
		where	DepositId=@DepositId

	end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.50</SQLVERSION>
			<RMTRACKLINK>72</RMTRACKLINK>
			<REASON>Add LocationCode to table CNF_Location</REASON>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Location
add LocationCode nvarchar(10) null</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER procedure [dbo].[sp_ui_CNF_Location_insert]	
	@LocationId Integer output ,
	@SystemId Integer,
	@SiteId Integer,
	@LocationAK VarChar(32),
	@Name NVarChar(50),
	@City NVarChar(50),
	@Description NText,
	@Enabled SmallInt,
	@LocationCode nvarchar(10)
as
begin
	insert into CNF_Location
		(SystemId, SiteId, LocationAK, Name, City, Description, Enabled, LocationCode)
	values 	
		(@SystemId, @SiteId, @LocationAK, @Name, @City, @Description, @Enabled, @LocationCode)

	select @LocationId= SCOPE_IDENTITY() 
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER procedure [dbo].[sp_ui_CNF_Location_update]	
	@LocationId Integer,
	@SystemId Integer,
	@SiteId Integer,
	@LocationAK VarChar(32),
	@Name NVarChar(50),
	@City NVarChar(50),
	@Description NText,
	@Enabled SmallInt,
	@LocationCode nvarchar(10)
as
begin
	update	CNF_Location
	set	SystemId=@SystemId,
		SiteId=@SiteId,
		LocationAK=@LocationAK,
		Name=@Name,
		City=@City,
		Description=@Description,
		Enabled=@Enabled,
		LocationCode=@LocationCode
	where	LocationId=@LocationId
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.49</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add RoleNames field to CNF_User</REASON>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_User
add RoleNames nvarchar(1000)</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER procedure [dbo].[sp_ui_CNF_User_insert]	
	@UserId Integer output ,
	@UserAK VarChar(32),
	@UserType SmallInt,
	@Template SmallInt,
	@Enabled SmallInt,
	@UserName NVarChar(50),
	@UserCode NVarChar(50),
	@UserDescription NVarChar(50),
	@UserPassword NVarChar(50),
	@CreationDate DateTime,
	@OrganizationId Integer,
	@PasswordChange DateTime,
	@PasswordExpiration DateTime,
	@LastLogin DateTime,
	@LastChange DateTime,
	@MasterUserId Integer,
	@SystemId Integer,
	@NTUser VarChar(256),
	@Note NText,
	@RoleNames nvarchar(1000)
as
begin
	insert into CNF_User
		(UserAK, UserType, Template, Enabled, UserName, UserCode, UserDescription, UserPassword, CreationDate, OrganizationId, PasswordChange, PasswordExpiration, LastLogin, LastChange, MasterUserId, SystemId, NTUser, Note, RoleNames)
	values 	
			(@UserAK,@UserType,@Template,@Enabled,@UserName,@UserCode,@UserDescription,@UserPassword,@CreationDate,@OrganizationId,@PasswordChange,@PasswordExpiration,@LastLogin,@LastChange,@MasterUserId,@SystemId,@NTUser,@Note,@RoleNames)


	select @UserId= SCOPE_IDENTITY() 

end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER procedure [dbo].[sp_ui_CNF_User_update]	
	@UserId Integer,
	@UserAK VarChar(32),
	@UserType SmallInt,
	@Template SmallInt,
	@Enabled SmallInt,
	@UserName NVarChar(50),
	@UserCode NVarChar(50),
	@UserDescription NVarChar(50),
	@UserPassword NVarChar(50),
	@CreationDate DateTime,
	@OrganizationId Integer,
	@PasswordChange DateTime,
	@PasswordExpiration DateTime,
	@LastLogin DateTime,
	@LastChange DateTime,
	@MasterUserId Integer,
	@SystemId Integer,
	@NTUser VarChar(256),
	@Note NText,
	@RoleNames nvarchar(1000)
as
begin
	update	CNF_User
	set	UserAK=@UserAK,
		UserType=@UserType,
		Template=@Template,
		Enabled=@Enabled,
		UserName=@UserName,
		UserCode=@UserCode,
		UserDescription=@UserDescription,
		UserPassword=@UserPassword,
		CreationDate=@CreationDate,
		OrganizationId=@OrganizationId,
		PasswordChange=@PasswordChange,
		PasswordExpiration=@PasswordExpiration,
		LastLogin=@LastLogin,
		LastChange=@LastChange,
		MasterUserId=@MasterUserId,
		SystemId=@SystemId,
		NTUser=@NTUser,
		Note=@Note,
		RoleNames=@RoleNames
	where	UserId=@UserId
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.48</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Modify stored procs for DATA_Ledger changes</REASON>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER procedure [dbo].[sp_ui_DATA_Ledger_insert]	
	@LedgerId Integer output ,
	@SystemId Integer,
	@TransactionId Integer,
	@LedgerType SmallInt,
	@LedgerAccountType SmallInt,
	@LedgerAccountId Integer,
	@EntryAmount Float,
	@EntryQuantity SmallInt,
	@ReferenceTable SmallInt,
	@ReferenceId Integer,
	@ReferenceAmount Float
as
begin
	insert into DATA_Ledger
		(TransactionId, SystemId, LedgerType, LedgerAccountType, LedgerAccountId, EntryAmount, EntryQuantity, ReferenceTable, ReferenceId, ReferenceAmount)
	values 	
		(@TransactionId,@SystemId,@LedgerType,@LedgerAccountType,@LedgerAccountId,@EntryAmount,@EntryQuantity,@ReferenceTable,@ReferenceId, @ReferenceAmount)

	select @LedgerId= SCOPE_IDENTITY() 
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER procedure [dbo].[sp_ui_DATA_Ledger_update]	
	@LedgerId Integer,
	@SystemId Integer,
	@TransactionId Integer,
	@LedgerType SmallInt,
	@LedgerAccountType SmallInt,
	@LedgerAccountId Integer,
	@EntryAmount Float,
	@EntryQuantity SmallInt,
	@ReferenceTable SmallInt,
	@ReferenceId Integer,
	@ReferenceAmount Float
as
begin
	update	DATA_Ledger
	set	TransactionId=@TransactionId,
		SystemId=@SystemId,
		LedgerType=@LedgerType,
		LedgerAccountType=@LedgerAccountType,
		LedgerAccountId=@LedgerAccountId,
		EntryAmount=@EntryAmount,
		EntryQuantity=@EntryQuantity,
		ReferenceTable=@ReferenceTable,
		ReferenceId=@ReferenceId,
		ReferenceAmount=@ReferenceAmount
	where	LedgerId=@LedgerId
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.47</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Minor changes to table DATA_Ledger</REASON>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Ledger
alter column LedgerType smallint not null</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Ledger
alter column EntryQuantity smallint not null</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Ledger
Add ReferenceAmount float null</SCRIPT>
			</SQLSCRIPTLIST>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Mirko Bianco</ADDEDBY>
			<SQLVERSION>1.46</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>recreate the cnf_PaymentCardRange Correctly</REASON>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @foreign_key_name nvarchar(max);
DECLARE @dropstmt nvarchar(max);

SELECT @foreign_key_name = f.name
  FROM sys.foreign_keys AS f
 INNER JOIN sys.foreign_key_columns AS fc 
    ON f.object_id = fc.constraint_object_id 
 WHERE f.parent_object_id = object_id(N'[dbo].[CNF_PaymentCardRange]')
   AND f.referenced_object_id = object_id(N'[dbo].[CNF_PaymentCard]')
   AND COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'PaymentCardId';

if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[CNF_PaymentCardRange] DROP CONSTRAINT [' + @foreign_key_name + ']';
  execute sp_executesql @dropstmt
end</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DROP TABLE [CNF_PaymentCardRange]</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>drop procedure sp_ui_cnf_PaymentCardRange_insert</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>drop procedure sp_ui_cnf_PaymentCardRange_update</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>drop procedure sp_ui_cnf_PaymentCardRange_delete</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_PaymentCardRange] (
	[PaymentCardRangeID] Integer identity(1,1) NOT NULL UNIQUE,
	[PaymentCardId] Integer NOT NULL,
	[FromNumber] Integer NOT NULL,
	[ToNumber] Integer NOT NULL,
	[PriorityOrder] Smallint NOT NULL,
Primary Key  ([PaymentCardRangeID])
) </SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_PaymentCardRange] add  foreign key([PaymentCardId]) references [CNF_PaymentCard] ([PaymentCardId])</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>create procedure [dbo].[sp_ui_CNF_PaymentCardRange_insert]	
                @PaymentCardRangeId Integer output,
		@PaymentCardId Integer,
		@FromNumber Integer,
		@ToNumber Integer,
		@PriorityOrder SmallInt
	as
	begin
		insert into CNF_PaymentCardRange
			(PaymentCardId, FromNumber, ToNumber, PriorityOrder)
		values 	
			(@PaymentCardId,@FromNumber,@ToNumber,@PriorityOrder)

	select @PaymentCardRangeId= SCOPE_IDENTITY() 		

	end</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>	create procedure [dbo].[sp_ui_CNF_PaymentCardRange_update]	
		@PaymentCardRangeID Integer,
		@PaymentCardId Integer,
		@FromNumber Integer,
		@ToNumber Integer,
		@PriorityOrder SmallInt
	as
	begin
		update	CNF_PaymentCardRange
		set	PaymentCardId=@PaymentCardId,
			FromNumber=@FromNumber,
			ToNumber=@ToNumber,
			PriorityOrder=@PriorityOrder
		where	PaymentCardRangeID=@PaymentCardRangeID

	end</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>create procedure [dbo].[sp_ui_CNF_PaymentCardRange_delete]	
		@PaymentCardRangeID Integer	
	as
	begin
		delete from	CNF_PaymentCardRange
		where	PaymentCardRangeID=@PaymentCardRangeID

	end</SCRIPT>
			</SQLSCRIPTLIST>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>saverio pangallo</ADDEDBY>
			<SQLVERSION>1.45</SQLVERSION>
			<RMTRACKLINK/>
			<REASON/>
			<SQLSCRIPTLIST>
				<SCRIPT>drop procedure sp_ui_cnf_MoneyCard_insert
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>drop procedure sp_ui_cnf_MoneyCard_update</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>drop procedure sp_ui_cnf_MoneyCard_delete</SCRIPT>
			</SQLSCRIPTLIST>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>saverio pangallo</ADDEDBY>
			<SQLVERSION>1.44</SQLVERSION>
			<RMTRACKLINK/>
			<REASON/>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @foreign_key_name nvarchar(max);
DECLARE @dropstmt nvarchar(max);

SELECT @foreign_key_name = f.name
  FROM sys.foreign_keys AS f
 INNER JOIN sys.foreign_key_columns AS fc 
    ON f.object_id = fc.constraint_object_id 
 WHERE f.parent_object_id = object_id(N'[dbo].[CNF_Performance]')
   AND f.referenced_object_id = object_id(N'[dbo].[CNF_MoneyCard]')
   AND COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'MoneyCardId';

if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[CNF_Performance] DROP CONSTRAINT [' + @foreign_key_name + ']';
  execute sp_executesql @dropstmt
end</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Performance] add  foreign key([MoneyCardId]) references [CNF_PaymentMethod] ([PaymentMethodId])</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DROP TABLE [CNF_MoneyCard]</SCRIPT>
			</SQLSCRIPTLIST>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>saverio pangallo</ADDEDBY>
			<SQLVERSION>1.43</SQLVERSION>
			<RMTRACKLINK/>
			<REASON/>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @foreign_key_name nvarchar(max);
DECLARE @dropstmt nvarchar(max);

SELECT @foreign_key_name = f.name
  FROM sys.foreign_keys AS f
 INNER JOIN sys.foreign_key_columns AS fc 
    ON f.object_id = fc.constraint_object_id 
 WHERE f.parent_object_id = object_id(N'[dbo].[CNF_Event]')
   AND f.referenced_object_id = object_id(N'[dbo].[CNF_MoneyCard]')
   AND COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'MoneyCardId';

if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[CNF_Event] DROP CONSTRAINT [' + @foreign_key_name + ']';
  execute sp_executesql @dropstmt
end</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Event] add  foreign key([MoneyCardId]) references [CNF_PaymentMethod] ([PaymentMethodId])</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>delete CNF_ProductMatrixOption
where OptionType=4</SCRIPT>
			</SQLSCRIPTLIST>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>saverio pangallo</ADDEDBY>
			<SQLVERSION>1.42</SQLVERSION>
			<RMTRACKLINK/>
			<REASON/>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Payment
add PaymentMethodId int null</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_Payment] add  foreign key([PaymentMethodId]) references [CNF_PaymentMethod] ([PaymentMethodId])</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_Payment
set PaymentMethodId=CNF_PaymentMethod.PaymentMethodId
from 
  CNF_PaymentMethod inner join
  CNF_Driver on CNF_PaymentMethod.DriverId=CNF_Driver.DriverId
where
  DriverType in (2,3) and -- Payment, Auth
  DriverSubType=PaymentType</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Payment
alter column PaymentMethodId int not null</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Payment
alter column PaymentType Smallint not null</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>	ALTER procedure [dbo].[sp_ui_DATA_Payment_update]	
		@PaymentId Integer,
		@PaymentDate DateTime,
		@FPaymentDate DateTime,
		@PaymentAK VarChar(32),
		@PaymentStatus SmallInt,
		@TransactionId Integer,
		@PaymentAmount Float,
		@CurrencyId Integer,
		@PaymentType SmallInt,
		@PaymentMethodId Integer
	as
	begin
		update	DATA_Payment
		set	PaymentDate=@PaymentDate,
			FPaymentDate=@FPaymentDate,
			PaymentAK=@PaymentAK,
			PaymentStatus=@PaymentStatus,
			TransactionId=@TransactionId,
			PaymentAmount=@PaymentAmount,
			CurrencyId=@CurrencyId,
			PaymentType=@PaymentType,
			PaymentMethodId=@PaymentMethodId
		where	PaymentId=@PaymentId

	end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>	ALTER procedure [dbo].[sp_ui_DATA_Payment_insert]	
		@PaymentId Integer output ,
		@PaymentDate DateTime,
		@FPaymentDate DateTime,
		@PaymentAK VarChar(32),
		@PaymentStatus SmallInt,
		@TransactionId Integer,
		@PaymentAmount Float,
		@CurrencyId Integer,
		@PaymentType SmallInt,
		@PaymentMethodId Integer
	as
	begin
		insert into DATA_Payment
			(PaymentDate, FPaymentDate, PaymentAK, PaymentStatus, TransactionId, PaymentAmount, CurrencyId, PaymentType, PaymentMethodId)
		values 	
			(@PaymentDate,@FPaymentDate,@PaymentAK,@PaymentStatus,@TransactionId,@PaymentAmount,@CurrencyId,@PaymentType,@PaymentMethodId)


		select @PaymentId= SCOPE_IDENTITY() 


	end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Mirko Bianco</ADDEDBY>
			<SQLVERSION>1.41</SQLVERSION>
			<RMTRACKLINK/>
			<REASON/>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_PaymentCardRange] (
	[PaymentCardRangeID] Integer NOT NULL UNIQUE,
	[PaymentCardId] Integer NOT NULL,
	[FromNumber] Integer NOT NULL,
	[ToNumber] Integer NOT NULL,
	[PriorityOrder] Smallint NOT NULL,
Primary Key  ([PaymentCardRangeID])
) </SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_PaymentCardRange] add  foreign key([PaymentCardId]) references [CNF_PaymentCard] ([PaymentCardId])</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>create procedure [dbo].[sp_ui_CNF_PaymentCardRange_insert]	
		@PaymentCardRangeID Integer,
		@PaymentCardId Integer,
		@FromNumber Integer,
		@ToNumber Integer,
		@PriorityOrder SmallInt
	as
	begin
		insert into CNF_PaymentCardRange
			(PaymentCardRangeID, PaymentCardId, FromNumber, ToNumber, PriorityOrder)
		values 	
			(@PaymentCardRangeID,@PaymentCardId,@FromNumber,@ToNumber,@PriorityOrder)



	end</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>	create procedure [dbo].[sp_ui_CNF_PaymentCardRange_update]	
		@PaymentCardRangeID Integer,
		@PaymentCardId Integer,
		@FromNumber Integer,
		@ToNumber Integer,
		@PriorityOrder SmallInt
	as
	begin
		update	CNF_PaymentCardRange
		set	PaymentCardId=@PaymentCardId,
			FromNumber=@FromNumber,
			ToNumber=@ToNumber,
			PriorityOrder=@PriorityOrder
		where	PaymentCardRangeID=@PaymentCardRangeID

	end</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>create procedure [dbo].[sp_ui_CNF_PaymentCardRange_delete]	
		@PaymentCardRangeID Integer	
	as
	begin
		delete from	CNF_PaymentCardRange
		where	PaymentCardRangeID=@PaymentCardRangeID

	end</SCRIPT>
			</SQLSCRIPTLIST>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.40</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>remove IDX_Ledger_UniqueAccount</REASON>
			<SQLSCRIPTLIST>
				<SCRIPT>DROP INDEX [IDX_Ledger_UniqueAccount] ON [dbo].[DATA_Ledger] WITH ( ONLINE = OFF )</SCRIPT>
			</SQLSCRIPTLIST>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.39</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>drop unique key on CNF_PaymentMethod.DriverId</REASON>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @index_name nvarchar(max);
DECLARE @dropstmt nvarchar(max);

select @index_name=name from sysindexes where id=object_id('CNF_PaymentMethod') and name like 'UQ_%'

if (len(@index_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[CNF_PaymentMethod] DROP CONSTRAINT [' + @index_name + ']';
  execute sp_executesql @dropstmt
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.38</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add field CNF_PaymentMethod.ShortCut</REASON>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_PaymentMethod
add ShortCut varchar(10) null</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER procedure [dbo].[sp_ui_CNF_PaymentMethod_insert]	
	@PaymentMethodId Integer output ,
	@DriverId Integer,
	@PaymentMethodAk VarChar(32),
	@Description NVarChar(50),
	@Enabled SmallInt,
	@DeviceId Integer,
	@ShortCut nvarchar(10)
as
begin
	insert into CNF_PaymentMethod
		(DriverId, PaymentMethodAk, Description, Enabled, DeviceId, ShortCut)
	values 	
			(@DriverId,@PaymentMethodAk,@Description,@Enabled,@DeviceId,@ShortCut)


	select @PaymentMethodId= SCOPE_IDENTITY() 
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER procedure [dbo].[sp_ui_CNF_PaymentMethod_update]	
	@PaymentMethodId Integer,
	@DriverId Integer,
	@PaymentMethodAk VarChar(32),
	@Description NVarChar(50),
	@Enabled SmallInt,
	@DeviceId Integer,
	@ShortCut nvarchar(10)
as
begin
	update	CNF_PaymentMethod
	set	DriverId=@DriverId,
		PaymentMethodAk=@PaymentMethodAk,
		Description=@Description,
		Enabled=@Enabled,
		DeviceId=@DeviceId,
		ShortCut=@ShortCut
	where	PaymentMethodId=@PaymentMethodId

end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.37</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Removed columns PaymentType e PaymentSubType from table CNF_PaymentMethod</REASON>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_PaymentMethod
drop column PaymentType</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_PaymentMethod
drop column PaymentSubType</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER procedure [dbo].[sp_ui_CNF_PaymentMethod_insert]	
	@PaymentMethodId Integer output ,
	@DriverId Integer,
	@PaymentMethodAk VarChar(32),
	@Description NVarChar(50),
	@Enabled SmallInt,
	@DeviceId Integer
as
begin
	insert into CNF_PaymentMethod
		(DriverId, PaymentMethodAk, Description, Enabled, DeviceId)
	values 	
			(@DriverId,@PaymentMethodAk,@Description,@Enabled,@DeviceId)


	select @PaymentMethodId= SCOPE_IDENTITY() 
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER procedure [dbo].[sp_ui_CNF_PaymentMethod_update]	
	@PaymentMethodId Integer,
	@DriverId Integer,
	@PaymentMethodAk VarChar(32),
	@Description NVarChar(50),
	@Enabled SmallInt,
	@DeviceId Integer
as
begin
	update	CNF_PaymentMethod
	set	DriverId=@DriverId,
		PaymentMethodAk=@PaymentMethodAk,
		Description=@Description,
		Enabled=@Enabled,
		DeviceId=@DeviceId
	where	PaymentMethodId=@PaymentMethodId

end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Antonella Mura</ADDEDBY>
			<SQLVERSION>1.36</SQLVERSION>
			<RMTRACKLINK>234</RMTRACKLINK>
			<REASON>ADM_AccessConfiguration:

0. Description from "ntext" to "nvarchar(50)"
1. Alter procedure [sp_ui_ADM_AccessConfiguration_insert]
2. Alter procedure [sp_ui_ADM_AccessConfiguration_update]</REASON>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table ADM_AccessConfiguration
alter column Description nvarchar(50) null</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER procedure [dbo].[sp_ui_ADM_AccessConfiguration_insert]	
	@AccessConfigurationId Integer output ,
	@LocationId Integer,
	@LayoutCode nvarchar(10),
	@Name NVarChar(30),
	@Description nvarchar(50),
	@Image nvarchar(50),
	@XmlLayout nvarchar(50)
as
begin
	insert into ADM_AccessConfiguration
		(LocationId, LayoutCode, Name, Description, Image, XmlLayout)
	values 	
		(@LocationId, @LayoutCode, @Name, @Description, @Image, @XmlLayout)

	select @AccessConfigurationId= SCOPE_IDENTITY() 
end</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER procedure [dbo].[sp_ui_ADM_AccessConfiguration_update]	
	@AccessConfigurationId Integer,
	@LocationId Integer,
	@LayoutCode nvarchar(10),
	@Name NVarChar(30),
	@Description nvarchar(50),
	@Image nvarchar(50),
	@XmlLayout nvarchar(50)
as
begin
	update	ADM_AccessConfiguration
	set	LocationId=@LocationId,
		LayoutCode=@LayoutCode,
		Name=@Name,
		Description=@Description,
		Image=@Image,
		XmlLayout=@XmlLayout
	where	AccessConfigurationId=@AccessConfigurationId
end</SCRIPT>
			</SQLSCRIPTLIST>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Mirko Bianco</ADDEDBY>
			<SQLVERSION>1.35</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>add field  PaymentProcessorType to store procedures  related to table CNF_MerchantTable</REASON>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER procedure [dbo].[sp_ui_CNF_MerchantTable_update]	
		@MerchantTableId Integer,
		@MerchantId Integer,
		@PaymentCardId Integer,
		@OperatingAreaId Integer,
		@WorkstationId Integer,
                @PaymentProcessorType Integer
	as
	begin
		update	CNF_MerchantTable
		set	MerchantId=@MerchantId,
			PaymentCardId=@PaymentCardId,
			OperatingAreaId=@OperatingAreaId,
			WorkstationId=@WorkstationId,
                        PaymentProcessorType=@PaymentProcessorType 
		where	MerchantTableId=@MerchantTableId

	end</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER procedure [dbo].[sp_ui_CNF_MerchantTable_insert]	
		@MerchantTableId Integer output ,
		@MerchantId Integer,
		@PaymentCardId Integer,
		@OperatingAreaId Integer,
		@WorkstationId Integer,
                @PaymentProcessorType Integer
	as
	begin
		insert into CNF_MerchantTable
			(MerchantId, PaymentCardId, OperatingAreaId, WorkstationId, PaymentProcessorType)
		values 	
			(@MerchantId,@PaymentCardId,@OperatingAreaId,@WorkstationId, @PaymentProcessorType)


		select @MerchantTableId= SCOPE_IDENTITY() 


	end</SCRIPT>
			</SQLSCRIPTLIST>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.34</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>[0..4] Add DATA_TicketUsage.TransactionId
[5..8] Add CNF_MoneyCard.ExchangeRate</REASON>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_TicketUsage
add TransactionId int null</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [DATA_TicketUsage] add  foreign key([TransactionId]) references [DATA_Transaction] ([TransactionId]) </SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER procedure [dbo].[sp_ui_DATA_TicketUsage_insert]	
	@UsageId Integer output ,
	@PerformanceId Integer,
	@TicketId Integer,
	@MediaIdentifierId Integer,
	@AccessAreaId Integer,
	@GateId Integer,
	@UsageDate DateTime,
	@FUsageDate DateTime,
	@UsageType SmallInt,
	@ValidateResult SmallInt,
	@LogTimeStamp DateTime,
	@UsageAmount Float,
	@NumEntries Integer,
	@WorkstationId Integer,
	@TransactionId Integer
as
begin
	insert into DATA_TicketUsage
		(PerformanceId, TicketId, MediaIdentifierId, AccessAreaId, GateId, UsageDate, FUsageDate, UsageType, ValidateResult, LogTimeStamp, UsageAmount, NumEntries, WorkstationId, TransactionId)
	values 	
(@PerformanceId,@TicketId,@MediaIdentifierId,@AccessAreaId,@GateId,@UsageDate,@FUsageDate,@UsageType,@ValidateResult,@LogTimeStamp,@UsageAmount,@NumEntries,@WorkstationId,@TransactionId)


select @UsageId= SCOPE_IDENTITY() 


end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER procedure [dbo].[sp_ui_DATA_TicketUsage_update]	
	@UsageId Integer,
	@PerformanceId Integer,
	@TicketId Integer,
	@MediaIdentifierId Integer,
	@AccessAreaId Integer,
	@GateId Integer,
	@UsageDate DateTime,
	@FUsageDate DateTime,
	@UsageType SmallInt,
	@ValidateResult SmallInt,
	@LogTimeStamp DateTime,
	@UsageAmount Float,
	@NumEntries Integer,
	@WorkstationId Integer,
	@TransactionId Integer
as
begin
	update	DATA_TicketUsage
	set	PerformanceId=@PerformanceId,
		TicketId=@TicketId,
		MediaIdentifierId=@MediaIdentifierId,
		AccessAreaId=@AccessAreaId,
		GateId=@GateId,
		UsageDate=@UsageDate,
		FUsageDate=@FUsageDate,
		UsageType=@UsageType,
		ValidateResult=@ValidateResult,
		LogTimeStamp=@LogTimeStamp,
		UsageAmount=@UsageAmount,
		NumEntries=@NumEntries,
		WorkstationId=@WorkstationId,
		TransactionId=@TransactionId
	where	UsageId=@UsageId

end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_MoneyCard
add ExchangeRate float null</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_MoneyCard
set ExchangeRate=1</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_MoneyCard
alter column ExchangeRate float not null</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER procedure [dbo].[sp_ui_CNF_MoneyCard_insert]	
	@MoneyCardId Integer output ,
	@MoneyCardAK VarChar(32),
	@MoneyCardName NVarChar(50),
	@MoneyCardDescription NText,
	@MoneyCardType SmallInt,
	@SystemId Integer,
	@ExchangeRate float
as
begin
	insert into CNF_MoneyCard
		(MoneyCardAK, MoneyCardName, MoneyCardDescription, MoneyCardType, SystemId, ExchangeRate)
	values 	
		(@MoneyCardAK,@MoneyCardName,@MoneyCardDescription,@MoneyCardType,@SystemId,@ExchangeRate)


select @MoneyCardId= SCOPE_IDENTITY() 


end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER procedure [dbo].[sp_ui_CNF_MoneyCard_update]	
	@MoneyCardId Integer,
	@MoneyCardAK VarChar(32),
	@MoneyCardName NVarChar(50),
	@MoneyCardDescription NText,
	@MoneyCardType SmallInt,
	@SystemId Integer,
	@ExchangeRate float
as
begin
	update	CNF_MoneyCard
	set	MoneyCardAK=@MoneyCardAK,
		MoneyCardName=@MoneyCardName,
		MoneyCardDescription=@MoneyCardDescription,
		MoneyCardType=@MoneyCardType,
		SystemId=@SystemId,
		ExchangeRate=@ExchangeRate
	where	MoneyCardId=@MoneyCardId
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Mirko Bianco</ADDEDBY>
			<SQLVERSION>1.33</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>1) Remove foreing key between CNF_MerchantTable and CNF_ApprovalSystem
2) Remove table CNF_ApprovalSystem from database 
3) Remove field ApprovalSystemId from table CNF_MerchantTable
4) Add field PaymentProcessorType in table CNF_MerchantTable</REASON>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @foreign_key_name nvarchar(max);
DECLARE @dropstmt nvarchar(max);

SELECT @foreign_key_name = f.name
  FROM sys.foreign_keys AS f
 INNER JOIN sys.foreign_key_columns AS fc 
    ON f.object_id = fc.constraint_object_id 
 WHERE f.parent_object_id = object_id(N'[dbo].[CNF_MerchantTable]')
   AND f.referenced_object_id = object_id(N'[dbo].[CNF_ApprovalSystem]')
   AND COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'ApprovalSystemId';

if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[CNF_MerchantTable] DROP CONSTRAINT [' + @foreign_key_name + ']';
  execute sp_executesql @dropstmt
end</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>DROP TABLE [CNF_ApprovalSystem]</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE [CNF_MerchantTable] DROP COLUMN [ApprovalSystemId]</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER TABLE CNF_MerchantTable ADD PaymentProcessorType int NOT NULL;</SCRIPT>
			</SQLSCRIPTLIST>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Mirko Bianco</ADDEDBY>
			<SQLVERSION>1.32</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>1) update cnf_paymentcard set paymentcardtype=1 where paymentcardtype is null;

2) alter table cnf_paymentcard alter column paymentcardtype Smallint not NULL;</REASON>
			<SQLSCRIPTLIST>
				<SCRIPT>update cnf_paymentcard set paymentcardtype=1 where paymentcardtype is null;
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table cnf_paymentcard alter column paymentcardtype Smallint not NULL;</SCRIPT>
			</SQLSCRIPTLIST>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.31</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Recreate table CNF_Product2Product to corrent a wrong field/foregnkey</REASON>
			<SQLSCRIPTLIST>
				<SCRIPT>drop table CNF_Product2Product</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_Product2Product] (
	[Product2ProductId] Integer Identity(1,1) NOT NULL,
	[ProductId] Integer NOT NULL,
	[ChildProductId] Integer NOT NULL,
	[EventId] Integer NULL,
	[PerformanceId] Integer NULL,
	[MinNumber] Smallint NULL,
	[MaxNumber] Smallint NULL,
	[Quantity] Smallint NULL,
Primary Key  ([Product2ProductId])
) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create UNIQUE Index [Idx1]  ON [CNF_Product2Product] ([ProductId] ,[EventId] ,[PerformanceId] ) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Product2Product] add  foreign key([EventId]) references [CNF_Event] ([EventId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Product2Product] add  foreign key([PerformanceId]) references [CNF_Performance] ([PerformanceId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Product2Product] add  foreign key([ProductId]) references [CNF_Product] ([ProductId]) 

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Product2Product] add  foreign key([ProductId]) references [CNF_Product] ([ProductId]) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter procedure [dbo].[sp_ui_CNF_Product2Product_insert]	
	@Product2ProductId Integer output ,
	@ProductId Integer,
	@ChildProductId Integer,
	@EventId Integer,
	@PerformanceId Integer,
	@MinNumber SmallInt,
	@MaxNumber SmallInt,
	@Quantity SmallInt
as
begin
	insert into CNF_Product2Product
		(ProductId, ChildProductId, EventId, PerformanceId, MinNumber, MaxNumber, Quantity)
	values 	
		(@ProductId,@ChildProductId,@EventId,@PerformanceId,@MinNumber,@MaxNumber,@Quantity)

	select @Product2ProductId= SCOPE_IDENTITY() 
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter procedure [dbo].[sp_ui_CNF_Product2Product_update]	
	@Product2ProductId Integer,
	@ProductId Integer,
	@ChildProductId Integer,
	@EventId Integer,
	@PerformanceId Integer,
	@MinNumber SmallInt,
	@MaxNumber SmallInt,
	@Quantity SmallInt
as
begin
	update	CNF_Product2Product
	set	ProductId=@ProductId,
		ChildProductId=@ChildProductId,
		EventId=@EventId,
		PerformanceId=@PerformanceId,
		MinNumber=@MinNumber,
		MaxNumber=@MaxNumber,
		Quantity=@Quantity
	where	Product2ProductId=@Product2ProductId
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter procedure [dbo].[sp_ui_CNF_Product2Product_delete]	
	@Product2ProductId Integer	
as
begin
	delete from	CNF_Product2Product
	where	Product2ProductId=@Product2ProductId
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.30</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>[0..5] create index on CNF_ProductValidity2Event
[6..9] drop CNF_Product2Event and relate stored proc</REASON>
			<SQLSCRIPTLIST>
				<SCRIPT>select distinct 
  ProductValidityId, 
  ReferenceTable, 
  ReferenceId, 
  EventId
into TEMP_PV2E
from CNF_ProductValidity2Event

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>delete from CNF_ProductValidity2Event

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>insert into CNF_ProductValidity2Event (
  ProductValidityId, 
  ReferenceTable, 
  ReferenceId, 
  EventId
)
select 
  ProductValidityId, 
  ReferenceTable, 
  ReferenceId, 
  EventId 
from TEMP_PV2E
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>drop table TEMP_PV2E</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>drop index UQ_ProductValidity2Event ON CNF_ProductValidity2Event</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create UNIQUE Index [UQ_ProductValidity2Event]  ON [CNF_ProductValidity2Event] ([ProductValidityId] ,[ReferenceTable] ,[ReferenceId] ,[EventId] ) </SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>drop table CNF_Product2Event</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>drop procedure sp_ui_cnf_Product2Event_insert
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>drop procedure sp_ui_cnf_Product2Event_update
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>drop procedure sp_ui_cnf_Product2Event_delete</SCRIPT>
			</SQLSCRIPTLIST>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.29</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Unique Index on CNF_ProductValidity2Event</REASON>
			<SQLSCRIPTLIST>
				<SCRIPT>Create Index [UQ_ProductValidity2Event]  ON [CNF_ProductValidity2Event] ([ReferenceTable] ,[ReferenceId] ,[EventId] ) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.28</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>DATA_PaymentCard
  -&gt; MerchantId
  -&gt; PaymentCardId

now nullable</REASON>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_PaymentCard
alter column MerchantId int null</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_PaymentCard
alter column PaymentCardId int null</SCRIPT>
			</SQLSCRIPTLIST>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Antonella Mura</ADDEDBY>
			<SQLVERSION>1.27</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>0. Rename field CNF_User.UserNickName into UserDescription
1. Add new field CNFUser.Note
2. Add new field CNF_UserGroup.Note
3. Alter procedure [sp_ui_CNF_User_insert]
4. Alter procedure [sp_ui_CNF_User_update]
5. Alter procedure [sp_ui_CNF_UserGroup_insert]
6. Alter procedure [sp_ui_CNF_UserGroup_update]</REASON>
			<SQLSCRIPTLIST>
				<SCRIPT>EXEC sp_rename 'CNF_User.UserNickName', 'UserDescription', 'COLUMN'</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_User
add Note ntext null</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_UserGroup
add Note ntext null</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>	alter procedure [dbo].[sp_ui_CNF_User_insert]	
		@UserId Integer output ,
		@UserAK VarChar(32),
		@UserType SmallInt,
		@Template SmallInt,
		@Enabled SmallInt,
		@UserName NVarChar(50),
		@UserCode NVarChar(50),
		@UserDescription NVarChar(50),
		@UserPassword NVarChar(50),
		@CreationDate DateTime,
		@OrganizationId Integer,
		@PasswordChange DateTime,
		@PasswordExpiration DateTime,
		@LastLogin DateTime,
		@LastChange DateTime,
		@MasterUserId Integer,
		@SystemId Integer,
		@NTUser VarChar(256),
		@Note NText
	as
	begin
		insert into CNF_User
			(UserAK, UserType, Template, Enabled, UserName, UserCode, UserDescription, UserPassword, CreationDate, OrganizationId, PasswordChange, PasswordExpiration, LastLogin, LastChange, MasterUserId, SystemId, NTUser, Note)
		values 	
			(@UserAK,@UserType,@Template,@Enabled,@UserName,@UserCode,@UserDescription,@UserPassword,@CreationDate,@OrganizationId,@PasswordChange,@PasswordExpiration,@LastLogin,@LastChange,@MasterUserId,@SystemId,@NTUser,@Note)


		select @UserId= SCOPE_IDENTITY() 


	end</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>	alter procedure [dbo].[sp_ui_CNF_User_update]	
		@UserId Integer,
		@UserAK VarChar(32),
		@UserType SmallInt,
		@Template SmallInt,
		@Enabled SmallInt,
		@UserName NVarChar(50),
		@UserCode NVarChar(50),
		@UserDescription NVarChar(50),
		@UserPassword NVarChar(50),
		@CreationDate DateTime,
		@OrganizationId Integer,
		@PasswordChange DateTime,
		@PasswordExpiration DateTime,
		@LastLogin DateTime,
		@LastChange DateTime,
		@MasterUserId Integer,
		@SystemId Integer,
		@NTUser VarChar(256),
		@Note NText
	as
	begin
		update	CNF_User
		set	UserAK=@UserAK,
			UserType=@UserType,
			Template=@Template,
			Enabled=@Enabled,
			UserName=@UserName,
			UserCode=@UserCode,
			UserDescription=@UserDescription,
			UserPassword=@UserPassword,
			CreationDate=@CreationDate,
			OrganizationId=@OrganizationId,
			PasswordChange=@PasswordChange,
			PasswordExpiration=@PasswordExpiration,
			LastLogin=@LastLogin,
			LastChange=@LastChange,
			MasterUserId=@MasterUserId,
			SystemId=@SystemId,
			NTUser=@NTUser,
			Note=@Note
		where	UserId=@UserId

	end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>	alter procedure [dbo].[sp_ui_CNF_UserGroup_insert]	
		@UserGroupId Integer output ,
		@Enabled SmallInt,
		@UserGroupName NVarChar(50),
		@UserGroupCode NVarChar(10),
		@UserGroupDescription NVarChar(50),
		@UserGroupLevel SmallInt,
		@Note NText
	as
	begin
		insert into CNF_UserGroup
			(Enabled, UserGroupName, UserGroupCode, UserGroupDescription, UserGroupLevel, Note)
		values 	
			(@Enabled,@UserGroupName,@UserGroupCode,@UserGroupDescription,@UserGroupLevel,@Note)


		select @UserGroupId= SCOPE_IDENTITY() 


	end</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>	alter procedure [dbo].[sp_ui_CNF_UserGroup_update]	
		@UserGroupId Integer,
		@Enabled SmallInt,
		@UserGroupName NVarChar(50),
		@UserGroupCode NVarChar(10),
		@UserGroupDescription NVarChar(50),
		@UserGroupLevel SmallInt,
		@Note NText
	as
	begin
		update	CNF_UserGroup
		set	Enabled=@Enabled,
			UserGroupName=@UserGroupName,
			UserGroupCode=@UserGroupCode,
			UserGroupDescription=@UserGroupDescription,
			UserGroupLevel=@UserGroupLevel,
			Note=@Note
		where	UserGroupId=@UserGroupId

	end</SCRIPT>
			</SQLSCRIPTLIST>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Mirko Bianco</ADDEDBY>
			<SQLVERSION>1.26</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add new table  CNF_Event2Attributes
Add new table  CNF_Event2PriceList</REASON>
			<SQLSCRIPTLIST>
				<SCRIPT>
Create table [CNF_Event2Attribute] (
	[Event2AttributeId] Integer Identity(1,1) NOT NULL UNIQUE,
	[AttributeId] Integer NOT NULL,
	[EventId] Integer NOT NULL,
Primary Key  ([Event2AttributeId])
) </SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Event2Attribute] add  foreign key([AttributeId]) references [CNF_Attribute] ([AttributeId]) </SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Event2Attribute] add  foreign key([EventId]) references [CNF_Event] ([EventId])</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_Event2PriceList] (
	[Event2PriceListId] Integer Identity(1,1) NOT NULL UNIQUE,
	[PriceListId] Integer NOT NULL,
	[EventId] Integer NOT NULL,
	[StartDate] Datetime NULL,
	[EndDate] Datetime NULL,
	[CalendarId] Integer NULL,
Primary Key  ([Event2PriceListId])
) </SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Event2PriceList] add  foreign key([PriceListId]) references [CNF_PriceList] ([PriceListId]) </SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Event2PriceList] add  foreign key([CalendarId]) references [CNF_Calendar] ([CalendarId]) </SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Event2PriceList] add  foreign key([EventId]) references [CNF_Event] ([EventId]) </SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>create procedure [dbo].[sp_ui_CNF_Event2Attribute_insert]	
		@Event2AttributeId Integer output ,
		@AttributeId Integer,
		@EventId Integer
	as
	begin
		insert into CNF_Event2Attribute
			(AttributeId, EventId)
		values 	
			(@AttributeId,@EventId)


		select @Event2AttributeId= SCOPE_IDENTITY() 


	end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>create procedure [dbo].[sp_ui_CNF_Event2Attribute_update]	
		@Event2AttributeId Integer,
		@AttributeId Integer,
		@EventId Integer
	as
	begin
		update	CNF_Event2Attribute
		set	AttributeId=@AttributeId,
			EventId=@EventId
		where	Event2AttributeId=@Event2AttributeId

	end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>create procedure [dbo].[sp_ui_CNF_Event2Attribute_delete]	
		@Event2AttributeId Integer	
	as
	begin
		delete from	CNF_Event2Attribute
		where	Event2AttributeId=@Event2AttributeId

	end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>create procedure [dbo].[sp_ui_CNF_Event2PriceList_insert]	
		@Event2PriceListId Integer output ,
		@PriceListId Integer,
		@EventId Integer,
		@StartDate DateTime,
		@EndDate DateTime,
		@CalendarId Integer
	as
	begin
		insert into CNF_Event2PriceList
			(PriceListId, EventId, StartDate, EndDate, CalendarId)
		values 	
			(@PriceListId,@EventId,@StartDate,@EndDate,@CalendarId)


		select @Event2PriceListId= SCOPE_IDENTITY() 


	end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>create procedure [dbo].[sp_ui_CNF_Event2PriceList_update]	
		@Event2PriceListId Integer,
		@PriceListId Integer,
		@EventId Integer,
		@StartDate DateTime,
		@EndDate DateTime,
		@CalendarId Integer
	as
	begin
		update	CNF_Event2PriceList
		set	PriceListId=@PriceListId,
			EventId=@EventId,
			StartDate=@StartDate,
			EndDate=@EndDate,
			CalendarId=@CalendarId
		where	Event2PriceListId=@Event2PriceListId

	end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>create procedure [dbo].[sp_ui_CNF_Event2PriceList_delete]	
		@Event2PriceListId Integer	
	as
	begin
		delete from	CNF_Event2PriceList
		where	Event2PriceListId=@Event2PriceListId

	end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Antonella Mura</ADDEDBY>
			<SQLVERSION>1.25</SQLVERSION>
			<RMTRACKLINK>245</RMTRACKLINK>
			<REASON>0. Rename field CNF_UserGroup.UserGroupStatus into Enabled
1. Alter procedure [sp_ui_CNF_UserGroup_insert]
2. Alter procedure [sp_ui_CNF_UserGroup_update]</REASON>
			<SQLSCRIPTLIST>
				<SCRIPT>EXEC sp_rename 'CNF_UserGroup.UserGroupStatus', 'Enabled', 'COLUMN'</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>	ALTER procedure [dbo].[sp_ui_CNF_UserGroup_insert]	
		@UserGroupId Integer output ,
		@Enabled SmallInt,
		@UserGroupName NVarChar(50),
		@UserGroupCode NVarChar(10),
		@UserGroupDescription NVarChar(50),
		@UserGroupLevel SmallInt
	as
	begin
		insert into CNF_UserGroup
			(Enabled, UserGroupName, UserGroupCode, UserGroupDescription, UserGroupLevel)
		values 	
			(@Enabled,@UserGroupName,@UserGroupCode,@UserGroupDescription,@UserGroupLevel)


		select @UserGroupId= SCOPE_IDENTITY() 


	end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>	ALTER procedure [dbo].[sp_ui_CNF_UserGroup_update]	
		@UserGroupId Integer,
		@Enabled SmallInt,
		@UserGroupName NVarChar(50),
		@UserGroupCode NVarChar(10),
		@UserGroupDescription NVarChar(50),
		@UserGroupLevel SmallInt
	as
	begin
		update	CNF_UserGroup
		set	Enabled=@Enabled,
			UserGroupName=@UserGroupName,
			UserGroupCode=@UserGroupCode,
			UserGroupDescription=@UserGroupDescription,
			UserGroupLevel=@UserGroupLevel
		where	UserGroupId=@UserGroupId

	end</SCRIPT>
			</SQLSCRIPTLIST>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Mirko Bianco</ADDEDBY>
			<SQLVERSION>1.24</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Added NTUser field on CNF_User table.</REASON>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_User 
  add NTUser Varchar(256) null</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter procedure [dbo].[sp_ui_CNF_User_insert]	
		@UserId Integer output ,
		@UserAK VarChar(32),
		@UserType SmallInt,
		@Template SmallInt,
		@Enabled SmallInt,
		@UserName NVarChar(50),
		@UserCode NVarChar(50),
		@UserNickName NVarChar(50),
		@UserPassword NVarChar(50),
		@CreationDate DateTime,
		@OrganizationId Integer,
		@PasswordChange DateTime,
		@PasswordExpiration DateTime,
		@LastLogin DateTime,
		@LastChange DateTime,
		@MasterUserId Integer,
		@SystemId Integer,
		@NTUser VarChar(256)
	as
	begin
		insert into CNF_User
			(UserAK, UserType, Template, Enabled, UserName, UserCode, UserNickName, UserPassword, CreationDate, OrganizationId, PasswordChange, PasswordExpiration, LastLogin, LastChange, MasterUserId, SystemId, NTUser)
		values 	
			(@UserAK,@UserType,@Template,@Enabled,@UserName,@UserCode,@UserNickName,@UserPassword,@CreationDate,@OrganizationId,@PasswordChange,@PasswordExpiration,@LastLogin,@LastChange,@MasterUserId,@SystemId,@NTUser)


		select @UserId= SCOPE_IDENTITY() 


	end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter procedure [dbo].[sp_ui_CNF_User_update]	
		@UserId Integer,
		@UserAK VarChar(32),
		@UserType SmallInt,
		@Template SmallInt,
		@Enabled SmallInt,
		@UserName NVarChar(50),
		@UserCode NVarChar(50),
		@UserNickName NVarChar(50),
		@UserPassword NVarChar(50),
		@CreationDate DateTime,
		@OrganizationId Integer,
		@PasswordChange DateTime,
		@PasswordExpiration DateTime,
		@LastLogin DateTime,
		@LastChange DateTime,
		@MasterUserId Integer,
		@SystemId Integer,
		@NTUser VarChar(256)
	as
	begin
		update	CNF_User
		set	UserAK=@UserAK,
			UserType=@UserType,
			Template=@Template,
			Enabled=@Enabled,
			UserName=@UserName,
			UserCode=@UserCode,
			UserNickName=@UserNickName,
			UserPassword=@UserPassword,
			CreationDate=@CreationDate,
			OrganizationId=@OrganizationId,
			PasswordChange=@PasswordChange,
			PasswordExpiration=@PasswordExpiration,
			LastLogin=@LastLogin,
			LastChange=@LastChange,
			MasterUserId=@MasterUserId,
			SystemId=@SystemId,
			NTUser=@NTUser
		where	UserId=@UserId

	end</SCRIPT>
			</SQLSCRIPTLIST>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.23</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Renamed DriverAKs</REASON>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_Driver 
set DriverAk='TDspDemo' 
where DriverAk='DspDemo'
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_Driver 
set DriverAk='TDspEpsonSerial' 
where DriverAk='DspEpson'</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_Driver 
set DriverAk='TDspEpsonOPOS' 
where DriverAk='DspEpsonOPOS'</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_Driver 
set DriverAk='TDspFutaba' 
where DriverAk='DspFutaba'</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_Driver 
set DriverAk='TPrnTckDemo' 
where DriverAk='PrnTckDemo'</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_Driver 
set DriverAk='TPrnRecDemo' 
where DriverAk='PrnRecDemo'</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_Driver 
set DriverAk='TPrnEpsonSerial' 
where DriverAk='PrnEpsonSerial'</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_Driver 
set DriverAk='TPrnEpsonOPOS' 
where DriverAk='PrnEpsonOPOS'</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_Driver 
set DriverAk='TPrnBocaSerial' 
where DriverAk='PrnBocaSerial'</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_Driver 
set DriverAk='TPrnDataCard' 
where DriverAk='PrnDataCard'</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_Driver 
set DriverAk='TEndEpsonSerial' 
where DriverAk='EndEpsonSerial'</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_Driver 
set DriverAk='TEndorserEpsonOPOS' 
where DriverAk='EndEpsonOPOS'</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_Driver 
set DriverAk='TDrvDLDragon' 
where DriverAk='IoDLDragon'</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_Driver 
set DriverAk='TOtnVideoCapture' 
where DriverAk='IoVideoCapture'</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_Driver 
set DriverAk='TDrvMOXA' 
where DriverAk='IoMOXA'</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_Driver 
set DriverAk='IoAxessGCM' 
where DriverAk='TDrvAxessGCM'</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_Driver 
set DriverAk='RptViewHtml' 
where DriverAk='TRptViewHtml'</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_Driver 
set DriverAk='RptViewPdf' 
where DriverAk='TRptViewPdf'</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_Driver 
set DriverAk='TRptViewWord' 
where DriverAk='RptViewWord'</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_Driver 
set DriverAk='TRptViewDecisionCube' 
where DriverAk='RptViewDecisionCube'</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_Driver 
set DriverAk='TRptHtmlBrowser' 
where DriverAk='RptHtmlBrowser'</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_Driver 
set DriverAk='TMailSendMapi' 
where DriverAk='MAPIMailSend'</SCRIPT>
			</SQLSCRIPTLIST>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.22</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Added field CNF_BoardPackage.BoardPackageAK
Updated stored procs for CNF_BoardPackage</REASON>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_BoardPackage
add BoardPackageAK varchar(32) null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_BoardPackage
set BoardPackageAK=replace(newid(),'-','')
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_BoardPackage
set BoardPackageAK='SystemPackage'
where PackageDescription='{5A61FE27-6CBE-4972-A1D0-2B2C916928E4}'
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_BoardPackage
alter column BoardPackageAK varchar(32) not null</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER procedure [dbo].[sp_ui_CNF_BoardPackage_insert]	
	@BoardPackageId Integer output ,
	@BoardPackageAK varchar(32),
	@SystemId Integer,
	@DocumentId Integer,
	@PackageDescription NVarChar(50)
as
begin
	insert into CNF_BoardPackage
		(BoardPackageAK, SystemId, DocumentId, PackageDescription)
	values 	
		(@BoardPackageAK, @SystemId,@DocumentId,@PackageDescription)

	select @BoardPackageId= SCOPE_IDENTITY() 
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER procedure [dbo].[sp_ui_CNF_BoardPackage_update]	
	@BoardPackageId Integer,
	@BoardPackageAK varchar(32),
	@SystemId Integer,
	@DocumentId Integer,
	@PackageDescription NVarChar(50)
as
begin
	update	CNF_BoardPackage
	set	BoardPackageAK=@BoardPackageAK,
		SystemId=@SystemId,
		DocumentId=@DocumentId,
		PackageDescription=@PackageDescription
	where	BoardPackageId=@BoardPackageId
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Antonella Mura</ADDEDBY>
			<SQLVERSION>1.21</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>0. Create fields DisplayFormat and SaveFormat into CNF_DataMask
1. Alter procedure [sp_ui_CNF_DataMask_insert]
2. Alter procedure [sp_ui_CNF_DataMask_update]</REASON>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table [CNF_DataMask] 
add DisplayFormat Nvarchar(30) NULL,
    SaveFormat Nvarchar(30) NULL;</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>	ALTER procedure [dbo].[sp_ui_CNF_DataMask_insert]	
		@DataMaskId Integer output ,
		@MaskTableId Integer,
		@MaskId Integer,
		@DataType SmallInt,
		@FieldNumber SmallInt,
		@AnagCode SmallInt,
		@MaskGroup SmallInt,
		@FieldName NVarChar(30),
		@Width SmallInt,
		@Height SmallInt,
		@Posx SmallInt,
		@Posy SmallInt,
		@KeyNumber SmallInt,
		@RuleId VarChar(40),
		@ObjType SmallInt,
		@Language SmallInt,
		@FieldDescription NText,
		@FieldHint NVarChar(50),
		@Required SmallInt,
		@IsUnique SmallInt,
		@MaskTableEdit SmallInt,
		@MaxLength SmallInt,
		@DisplayFormat NVarChar(30),
		@SaveFormat NVarChar(30)
	as
	begin
		insert into CNF_DataMask
			(MaskTableId, MaskId, DataType, FieldNumber, AnagCode, MaskGroup, FieldName, Width, Height, Posx, Posy, KeyNumber, RuleId, ObjType, Language, FieldDescription, FieldHint, Required, IsUnique, MaskTableEdit, MaxLength, DisplayFormat, SaveFormat)
		values 	
			(@MaskTableId,@MaskId,@DataType,@FieldNumber,@AnagCode,@MaskGroup,@FieldName,@Width,@Height,@Posx,@Posy,@KeyNumber,@RuleId,@ObjType,@Language,@FieldDescription,@FieldHint,@Required,@IsUnique,@MaskTableEdit,@MaxLength,@DisplayFormat,@SaveFormat)


		select @DataMaskId= SCOPE_IDENTITY() 


	end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>	ALTER procedure [dbo].[sp_ui_CNF_DataMask_update]	
		@DataMaskId Integer,
		@MaskTableId Integer,
		@MaskId Integer,
		@DataType SmallInt,
		@FieldNumber SmallInt,
		@AnagCode SmallInt,
		@MaskGroup SmallInt,
		@FieldName NVarChar(30),
		@Width SmallInt,
		@Height SmallInt,
		@Posx SmallInt,
		@Posy SmallInt,
		@KeyNumber SmallInt,
		@RuleId VarChar(40),
		@ObjType SmallInt,
		@Language SmallInt,
		@FieldDescription NText,
		@FieldHint NVarChar(50),
		@Required SmallInt,
		@IsUnique SmallInt,
		@MaskTableEdit SmallInt,
		@MaxLength SmallInt,
		@DisplayFormat NVarChar(30),
		@SaveFormat NVarChar(30)
	as
	begin
		update	CNF_DataMask
		set	MaskTableId=@MaskTableId,
			MaskId=@MaskId,
			DataType=@DataType,
			FieldNumber=@FieldNumber,
			AnagCode=@AnagCode,
			MaskGroup=@MaskGroup,
			FieldName=@FieldName,
			Width=@Width,
			Height=@Height,
			Posx=@Posx,
			Posy=@Posy,
			KeyNumber=@KeyNumber,
			RuleId=@RuleId,
			ObjType=@ObjType,
			Language=@Language,
			FieldDescription=@FieldDescription,
			FieldHint=@FieldHint,
			Required=@Required,
			IsUnique=@IsUnique,
			MaskTableEdit=@MaskTableEdit,
			MaxLength=@MaxLength,
			DisplayFormat=@DisplayFormat,
			SaveFormat=@SaveFormat
		where	DataMaskId=@DataMaskId

	end</SCRIPT>
			</SQLSCRIPTLIST>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ettore Bottega</ADDEDBY>
			<SQLVERSION>1.20</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add new fields CntxPropertyType and ParamValue to table CNF_DocTemplateParam:

  0. alter table adding new fields
  1. alter procedure [sp_ui_CNF_DocTemplateParam_insert]
  2. alter procedure [sp_ui_CNF_DocTemplateParam_update]
			</REASON>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table [CNF_DocTemplateParam] add 
  [CntxPropertyType] Smallint NULL,
  [ParamValue] Nvarchar(50) NULL;</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter procedure [dbo].[sp_ui_CNF_DocTemplateParam_insert]  
  @DocTemplateParamId Integer output ,
  @DocTemplateId Integer,
  @ParamName NVarChar(30),
  @ParamType SmallInt,
  @CntxPropertyType SmallInt,
  @ParamValue NVarChar(50),
  @ParamCaption NVarChar(50)
as
begin
  insert into CNF_DocTemplateParam
    (DocTemplateId, ParamName, ParamType, CntxPropertyType, ParamValue, ParamCaption)
  values   
    (@DocTemplateId,@ParamName,@ParamType,@CntxPropertyType,@ParamValue,@ParamCaption)


  select @DocTemplateParamId= SCOPE_IDENTITY() 

end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter procedure [dbo].[sp_ui_CNF_DocTemplateParam_update]  
  @DocTemplateParamId Integer,
  @DocTemplateId Integer,
  @ParamName NVarChar(30),
  @ParamType SmallInt,
  @CntxPropertyType SmallInt,
  @ParamValue NVarChar(50),
  @ParamCaption NVarChar(50)
as
begin
  update  CNF_DocTemplateParam
  set  DocTemplateId=@DocTemplateId,
    ParamName=@ParamName,
    ParamType=@ParamType,
    CntxPropertyType=@CntxPropertyType,
    ParamValue=@ParamValue,
    ParamCaption=@ParamCaption
  where  DocTemplateParamId=@DocTemplateParamId
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Antonella Mura</ADDEDBY>
			<SQLVERSION>1.19</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>0-1-2. Create field Enabled into CNF_MaskTableItem
3. Alter procedure [sp_ui_CNF_MaskTableItem_insert]
4. Alter procedure [sp_ui_CNF_MaskTableItem_update]</REASON>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_MaskTableItem
add Enabled smallint null</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_MaskTableItem
set Enabled=1</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_MaskTableItem
alter column Enabled smallint not null</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter procedure [dbo].[sp_ui_CNF_MaskTableItem_insert]	
		@MaskTableItemId Integer output ,
		@MasterFieldId Integer,
		@MaskTableId Integer,
		@ItemName NVarChar(30),
		@ItemValue NVarChar(30),
		@Enabled SmallInt
as
begin
	insert into CNF_MaskTableItem
	(MasterFieldId, MaskTableId, ItemName, ItemValue, Enabled)
values 	
	(@MasterFieldId,@MaskTableId,@ItemName,@ItemValue,@Enabled)

select @MaskTableItemId= SCOPE_IDENTITY() 
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter procedure [dbo].[sp_ui_CNF_MaskTableItem_update]	
		@MaskTableItemId Integer,
		@MasterFieldId Integer,
		@MaskTableId Integer,
		@ItemName NVarChar(30),
		@ItemValue NVarChar(30),
		@Enabled SmallInt
as
begin
	update	CNF_MaskTableItem
	set	MasterFieldId=@MasterFieldId,
			MaskTableId=@MaskTableId,
			ItemName=@ItemName,
			ItemValue=@ItemValue,
			Enabled=@Enabled
	where	MaskTableItemId=@MaskTableItemId

end</SCRIPT>
			</SQLSCRIPTLIST>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.18</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>(0..2) create table CNF_ProductValidity2Event
(3..5) create stored procs</REASON>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_ProductValidity2Event] (
	[ProductValidity2EventId] Integer Identity(1,1) NOT NULL,
	[ProductValidityId] Integer NOT NULL,
	[ReferenceTable] Smallint NOT NULL,
	[ReferenceId] Integer NOT NULL,
	[EventId] Integer NOT NULL,
Primary Key  ([ProductValidity2EventId])
) </SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_ProductValidity2Event] add  foreign key([ProductValidityId]) references [CNF_ProductValidity] ([ProductValidityId]) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_ProductValidity2Event] add  foreign key([EventId]) references [CNF_Event] ([EventId]) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>create procedure [dbo].[sp_ui_CNF_ProductValidity2Event_insert]	
	@ProductValidity2EventId Integer output ,
	@ProductValidityId Integer,
	@ReferenceTable smallint,
	@ReferenceId int,
	@EventId int
as
begin
	insert into CNF_ProductValidity2Event
		(ProductValidityId, ReferenceTable, ReferenceId, EventId)
	values 	
		(@ProductValidityId, @ReferenceTable, @ReferenceId, @EventId)

	select @ProductValidity2EventId= SCOPE_IDENTITY() 
end</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>create procedure [dbo].[sp_ui_CNF_ProductValidity2Event_update]	
	@ProductValidity2EventId Integer,
	@ProductValidityId Integer,
	@ReferenceTable smallint,
	@ReferenceId int,
	@EventId int
as
begin
	update CNF_ProductValidity2Event
	set
		ProductValidityId=@ProductValidityId,
		ReferenceTable=@ReferenceTable,
		ReferenceId=@ReferenceId,
		EventId=@EventId
	where
		ProductValidity2EventId=@ProductValidity2EventId
end</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>create procedure [dbo].[sp_ui_CNF_ProductValidity2Event_delete]	
	@ProductValidity2EventId Integer	
as
begin
	delete from CNF_ProductValidity2Event
	where	ProductValidity2EventId=@ProductValidity2EventId
end</SCRIPT>
			</SQLSCRIPTLIST>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.17</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>CNF_Attribute.RootId have to be nullable</REASON>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Attribute
alter column RootId int null</SCRIPT>
			</SQLSCRIPTLIST>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.16</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>(0..2) drop procecures for DATA_SaleItemValidity
(3..5) drop procedures for DATA_TicketRight
(6..8) drop procedures for DATA_TicketValidity
(9..10) alter procedures for CNF_Product2Event
(11..12) alter procedures for DATA_Ticket
(13..15) create procedures for  CNF_ProductValidity
(16..17) alter procedures for CNF_AttributeTemplate
(18..19) alter procedures for CNF_Attribute
(20..21) alter procedures for CNF_Product
(22..23) alter procedures for DATA_Ledger
(24..26) alter procedures for CNF_Product2Attribute</REASON>
			<SQLSCRIPTLIST>
				<SCRIPT>drop procedure  sp_ui_DATA_SaleItemValidity_insert</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>drop procedure  sp_ui_DATA_SaleItemValidity_update</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>drop procedure sp_ui_DATA_SaleItemValidity_delete</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>drop procedure sp_ui_DATA_TicketRight_insert</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>drop procedure sp_ui_DATA_TicketRight_update</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>drop procedure sp_ui_DATA_TicketRight_delete</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>drop procedure sp_ui_DATA_TicketValidity_insert</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>drop procedure sp_ui_DATA_TicketValidity_update</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>drop procedure sp_ui_DATA_TicketValidity_delete</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER procedure [dbo].[sp_ui_CNF_Product2Event_insert]	
	@Product2EventId Integer output ,
	@ProductId Integer,
	@EventId Integer
as
begin
	insert into CNF_Product2Event
		(ProductId, EventId)
	values 	
		(@ProductId,@EventId)

	select @Product2EventId= SCOPE_IDENTITY() 
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER procedure [dbo].[sp_ui_CNF_Product2Event_update]	
	@Product2EventId Integer,
	@ProductId Integer,
	@EventId Integer
as
begin
	update	CNF_Product2Event
	set	ProductId=@ProductId,
		EventId=@EventId
	where	Product2EventId=@Product2EventId
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER procedure [dbo].[sp_ui_DATA_Ticket_insert]	
	@TicketId Integer output ,
	@TicketAK VarChar(32),
	@ProductId Integer,
	@AttributeSetId Integer,
	@WorkstationId Integer,
	@Serial Integer,
	@Encoded SmallInt,
	@Active SmallInt,
	@EncodingType Integer,
	@ElementType SmallInt,
	@VoidType SmallInt,
	@EncodingDateTime DateTime,
	@CurrencyId Integer,
	@Price Float,
	@PrintedPrice Float,
	@Taxes Float,
	@ActiveFrom DateTime,
	@ActiveTo DateTime,
	@TaxExempt SmallInt,
	@MaxDebit Float,
	@ExtType Integer,
	@Expire DateTime,
	@WalletKey Numeric(20),
	@ValidityXML NText
as
begin
	insert into DATA_Ticket (
		TicketAK, 
		ProductId, 
		AttributeSetId, 
		WorkstationId, 
		Serial, 
		Encoded, 
		Active, 
		EncodingType, 
		ElementType, 
		VoidType, 
		EncodingDateTime, 
		CurrencyId, 
		Price, 
		PrintedPrice, 
		Taxes, 
		ActiveFrom, 
		ActiveTo, 
		TaxExempt, 
		MaxDebit, 
		ExtType, 
		Expire, 
		WalletKey,
		ValidityXML
	) values (
		@TicketAK,
		@ProductId,
		@AttributeSetId,
		@WorkstationId,
		@Serial,
		@Encoded,
		@Active,
		@EncodingType,
		@ElementType,
		@VoidType,
		@EncodingDateTime,
		@CurrencyId,
		@Price,
		@PrintedPrice,
		@Taxes,
		@ActiveFrom,
		@ActiveTo,
		@TaxExempt,
		@MaxDebit,
		@ExtType,
		@Expire,
		@WalletKey,
		@ValidityXML
	)

	select @TicketId= SCOPE_IDENTITY() 
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER procedure [dbo].[sp_ui_DATA_Ticket_update]	
	@TicketId Integer,
	@TicketAK VarChar(32),
	@ProductId Integer,
	@AttributeSetId Integer,
	@WorkstationId Integer,
	@Serial Integer,
	@Encoded SmallInt,
	@Active SmallInt,
	@EncodingType Integer,
	@ElementType SmallInt,
	@VoidType SmallInt,
	@EncodingDateTime DateTime,
	@CurrencyId Integer,
	@Price Float,
	@PrintedPrice Float,
	@Taxes Float,
	@ActiveFrom DateTime,
	@ActiveTo DateTime,
	@TaxExempt SmallInt,
	@MaxDebit Float,
	@ExtType Integer,
	@Expire DateTime,
	@WalletKey Numeric(20),
	@ValidityXML NText
as
begin
	update	DATA_Ticket
	set	TicketAK=@TicketAK,
		ProductId=@ProductId,
		AttributeSetId=@AttributeSetId,
		WorkstationId=@WorkstationId,
		Serial=@Serial,
		Encoded=@Encoded,
		Active=@Active,
		EncodingType=@EncodingType,
		ElementType=@ElementType,
		VoidType=@VoidType,
		EncodingDateTime=@EncodingDateTime,
		CurrencyId=@CurrencyId,
		Price=@Price,
		PrintedPrice=@PrintedPrice,
		Taxes=@Taxes,
		ActiveFrom=@ActiveFrom,
		ActiveTo=@ActiveTo,
		TaxExempt=@TaxExempt,
		MaxDebit=@MaxDebit,
		ExtType=@ExtType,
		Expire=@Expire,
		WalletKey=@WalletKey,
		ValidityXML=@ValidityXML
	where	TicketId=@TicketId
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>create procedure [dbo].[sp_ui_CNF_ProductValidity_insert]	
	@ProductValidityId Integer output ,
	@SystemId Integer,
	@ReferenceTable smallint,
	@ReferenceId int,
	@ValidityXML NText
as
begin
	insert into CNF_ProductValidity
		(SystemId, ReferenceTable, ReferenceId, ValidityXML)
	values 	
		(@SystemId, @ReferenceTable, @ReferenceId, @ValidityXML)

	select @ProductValidityId= SCOPE_IDENTITY() 
end</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>create procedure [dbo].[sp_ui_CNF_ProductValidity_update]	
	@ProductValidityId Integer,
	@SystemId Integer,
	@ReferenceTable smallint,
	@ReferenceId int,
	@ValidityXML NText
as
begin
	update CNF_ProductValidity
	set
		SystemId=@SystemId,
		ReferenceTable=@ReferenceTable,
		ReferenceId=@ReferenceId,
		ValidityXML=@ValidityXML
	where
		ProductValidityId=@ProductValidityId
end</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>create procedure [dbo].[sp_ui_CNF_ProductValidity_delete]	
	@ProductValidityId Integer	
as
begin
	delete from CNF_ProductValidity
	where	ProductValidityId=@ProductValidityId
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER procedure [dbo].[sp_ui_CNF_AttributeTemplate_insert]	
	@AttributeTemplateId Integer output ,
	@SystemId Integer,
	@AttributeTemplateAK VarChar(32),
	@AttributeTemplateCode NVarChar(10),
	@Description NVarChar(50),
	@AttributeTemplateType SmallInt,
	@AttributeTemplateSubType SmallInt,
	@EffectPrice SmallInt
as
begin
	insert into CNF_AttributeTemplate
		(SystemId, AttributeTemplateAK, AttributeTemplateCode, Description, AttributeTemplateType, AttributeTemplateSubType, EffectPrice)
	values 	
		(@SystemId,@AttributeTemplateAK,@AttributeTemplateCode,@Description,@AttributeTemplateType,@AttributeTemplateSubType,@EffectPrice)

	select @AttributeTemplateId= SCOPE_IDENTITY() 
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER procedure [dbo].[sp_ui_CNF_AttributeTemplate_update]	
	@AttributeTemplateId Integer,
	@SystemId Integer,
	@AttributeTemplateAK VarChar(32),
	@AttributeTemplateCode NVarChar(10),
	@Description NVarChar(50),
	@AttributeTemplateType SmallInt,
	@AttributeTemplateSubType SmallInt,
	@EffectPrice SmallInt
as
begin
	update	CNF_AttributeTemplate
	set	SystemId=@SystemId,
		AttributeTemplateAK=@AttributeTemplateAK,
		AttributeTemplateCode=@AttributeTemplateCode,
		Description=@Description,
		AttributeTemplateType=@AttributeTemplateType,
		AttributeTemplateSubType=@AttributeTemplateSubType,
		EffectPrice=@EffectPrice
	where	AttributeTemplateId=@AttributeTemplateId
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER procedure [dbo].[sp_ui_CNF_Attribute_insert]	
	@AttributeId Integer output ,
	@AttributeTemplateId Integer,
	@AttributeAK VarChar(32),
	@RootId Integer,
	@ParentId Integer,
	@Name NVarChar(50),
	@Code NVarChar(10),
	@Weight Integer,
	@ValidityOverride smallint,
	@Enabled smallint
as
begin
	insert into CNF_Attribute
		(AttributeTemplateId, AttributeAK, RootId, ParentId, Name, Code, Weight, ValidityOverride, Enabled)
	values 	
		(@AttributeTemplateId,@AttributeAK,@RootId,@ParentId,@Name,@Code,@Weight,@ValidityOverride,@Enabled)

	select @AttributeId= SCOPE_IDENTITY() 
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER procedure [dbo].[sp_ui_CNF_Attribute_update]	
	@AttributeId Integer,
	@AttributeTemplateId Integer,
	@AttributeAK VarChar(32),
	@RootId int,
	@ParentId int,
	@Name NVarChar(50),
	@Code NVarChar(10),
	@Weight Integer,
	@ValidityOverride smallint,
	@Enabled smallint
as
begin
	update	CNF_Attribute
	set	AttributeTemplateId=@AttributeTemplateId,
		AttributeAK=@AttributeAK,
		RootId=@RootId,
		ParentId=@ParentId,
		Name=@Name,
		Code=@Code,
		Weight=@Weight,
		ValidityOverride=@ValidityOverride,
		Enabled=@Enabled
	where	AttributeId=@AttributeId
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER procedure [dbo].[sp_ui_CNF_Product_insert]	
	@ProductId Integer output ,
	@Key1 Integer,
	@Key2 Integer,
	@ProductAK VarChar(32),
	@ProductType SmallInt,
	@Enabled SmallInt,
	@ProductGroupId Integer,
	@ProductStatus SmallInt,
	@ProductTaxType SmallInt,
	@ProductCode NVarChar(20),
	@ProductName NVarChar(50),
	@ProductDescription NText,
	@IsCombo SmallInt,
	@PriceType SmallInt,
	@Price Float,
	@Cost Float,
	@Refundable SmallInt,
	@MinPrice Float,
	@PrintedPrice Float,
	@CreationDate DateTime,
	@CreatedByUser Integer,
	@ProductMinQty Integer,
	@ProductQtyStep Integer,
	@ShellId Integer,
	@TaxPackageId Integer,
	@ValidFrom DateTime,
	@ValidTo DateTime,
	@ValidityOverride smallint
as
begin
	insert into CNF_Product
		(Key1, Key2, ProductAK, ProductType, Enabled, ProductGroupId, ProductStatus, ProductTaxType, ProductCode, ProductName, ProductDescription, IsCombo, PriceType, Price, Cost, Refundable, MinPrice, PrintedPrice, CreationDate, CreatedByUser, ProductMinQty, ProductQtyStep, ShellId, TaxPackageId, ValidFrom, ValidTo, ValidityOverride)
	values 	
			(@Key1,@Key2,@ProductAK,@ProductType,@Enabled,@ProductGroupId,@ProductStatus,@ProductTaxType,@ProductCode,@ProductName,@ProductDescription,@IsCombo,@PriceType,@Price,@Cost,@Refundable,@MinPrice,@PrintedPrice,@CreationDate,@CreatedByUser,@ProductMinQty,@ProductQtyStep,@ShellId,@TaxPackageId,@ValidFrom,@ValidTo,@ValidityOverride)


	select @ProductId= SCOPE_IDENTITY() 


end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER procedure [dbo].[sp_ui_CNF_Product_update]	
	@ProductId Integer,
	@Key1 Integer,
	@Key2 Integer,
	@ProductAK VarChar(32),
	@ProductType SmallInt,
	@Enabled SmallInt,
	@ProductGroupId Integer,
	@ProductStatus SmallInt,
	@ProductTaxType SmallInt,
	@ProductCode NVarChar(20),
	@ProductName NVarChar(50),
	@ProductDescription NText,
	@IsCombo SmallInt,
	@PriceType SmallInt,
	@Price Float,
	@Cost Float,
	@Refundable SmallInt,
	@MinPrice Float,
	@PrintedPrice Float,
	@CreationDate DateTime,
	@CreatedByUser Integer,
	@ProductMinQty Integer,
	@ProductQtyStep Integer,
	@ShellId Integer,
	@TaxPackageId Integer,
	@ValidFrom DateTime,
	@ValidTo DateTime,
	@ValidityOverride smallint
as
begin
	update	CNF_Product
	set	Key1=@Key1,
		Key2=@Key2,
		ProductAK=@ProductAK,
		ProductType=@ProductType,
		Enabled=@Enabled,
		ProductGroupId=@ProductGroupId,
		ProductStatus=@ProductStatus,
		ProductTaxType=@ProductTaxType,
		ProductCode=@ProductCode,
		ProductName=@ProductName,
		ProductDescription=@ProductDescription,
		IsCombo=@IsCombo,
		PriceType=@PriceType,
		Price=@Price,
		Cost=@Cost,
		Refundable=@Refundable,
		MinPrice=@MinPrice,
		PrintedPrice=@PrintedPrice,
		CreationDate=@CreationDate,
		CreatedByUser=@CreatedByUser,
		ProductMinQty=@ProductMinQty,
		ProductQtyStep=@ProductQtyStep,
		ShellId=@ShellId,
		TaxPackageId=@TaxPackageId,
		ValidFrom=@ValidFrom,
		ValidTo=@ValidTo,
		ValidityOverride=@ValidityOverride
	where	ProductId=@ProductId

end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER procedure [dbo].[sp_ui_DATA_Ledger_insert]	
	@LedgerId Integer output ,
	@SystemId Integer,
	@TransactionId Integer,
	@LedgerType Integer,
	@LedgerAccountType SmallInt,
	@LedgerAccountId Integer,
	@EntryAmount Float,
	@EntryQuantity Integer,
	@ReferenceTable SmallInt,
	@ReferenceId Integer
as
begin
	insert into DATA_Ledger
		(TransactionId, SystemId, LedgerType, LedgerAccountType, LedgerAccountId, EntryAmount, EntryQuantity, ReferenceTable, ReferenceId)
	values 	
		(@TransactionId,@SystemId,@LedgerType,@LedgerAccountType,@LedgerAccountId,@EntryAmount,@EntryQuantity,@ReferenceTable,@ReferenceId)

	select @LedgerId= SCOPE_IDENTITY() 
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER procedure [dbo].[sp_ui_DATA_Ledger_update]	
	@LedgerId Integer,
	@SystemId Integer,
	@TransactionId Integer,
	@LedgerType Integer,
	@LedgerAccountType SmallInt,
	@LedgerAccountId Integer,
	@EntryAmount Float,
	@EntryQuantity Integer,
	@ReferenceTable SmallInt,
	@ReferenceId Integer
as
begin
	update	DATA_Ledger
	set	TransactionId=@TransactionId,
		SystemId=@SystemId,
		LedgerType=@LedgerType,
		LedgerAccountType=@LedgerAccountType,
		LedgerAccountId=@LedgerAccountId,
		EntryAmount=@EntryAmount,
		EntryQuantity=@EntryQuantity,
		ReferenceTable=@ReferenceTable,
		ReferenceId=@ReferenceId
	where	LedgerId=@LedgerId
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>create procedure [dbo].[sp_ui_CNF_Product2Attribute_insert]	
	@Product2AttributeId Integer output ,
	@ProductId Integer,
	@AttributeId Integer,
	@PriorityOrder smallint,
	@ValidityOverride smallint
as
begin
	insert into CNF_Product2Attribute
		(ProductId, AttributeId, PriorityOrder, ValidityOverride)
	values 	
		(@ProductId, @AttributeId, @PriorityOrder, @ValidityOverride)

	select @Product2AttributeId= SCOPE_IDENTITY() 
end</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>create procedure [dbo].[sp_ui_CNF_Product2Attribute_update]	
	@Product2AttributeId Integer,
	@ProductId Integer,
	@AttributeId Integer,
	@PriorityOrder smallint,
	@ValidityOverride smallint
as
begin
	update CNF_Product2Attribute
	set
		ProductId=@ProductId, 
		AttributeId=@AttributeId, 
		PriorityOrder=@PriorityOrder, 
		ValidityOverride=@ValidityOverride
	where	
		Product2AttributeId=@Product2AttributeId
end</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>create procedure [dbo].[sp_ui_CNF_Product2Attribute_delete]	
	@Product2AttributeId Integer	
as
begin
	delete from CNF_Product2Attribute
	where	Product2AttributeId=@Product2AttributeId
end</SCRIPT>
			</SQLSCRIPTLIST>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.15</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Changes for product/components/validity

0) drop table CNF_Product2Event
1) drop table DATA_SaleItemValidity
2) drop table DATA_TicketRight
3) drop table DATA_TicketValidity
4) add DATA_Ticket.ValidityXML
5..7) create table CNF_ProductValidity
8) add CNF_AttributeTemplate.AttributeTemplateSubType
9..15) add CNF_Attribute (RootId, ParentId, ValidityOverride, Enabled)
16..18) add CNF_Product.ValidityOverride
19..22) add DATA_Ledger.SystemId
23..25) create table CNF_Product2Attribute
26..28) re-create table CNF_Product2Event</REASON>
			<SQLSCRIPTLIST>
				<SCRIPT>drop table CNF_Product2Event
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>drop table DATA_SaleItemValidity
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>drop table DATA_TicketRight
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>drop table DATA_TicketValidity</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Ticket
add ValidityXML NText
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_ProductValidity] (
	[ProductValidityId] Integer Identity(1,1) NOT NULL,
	[SystemId] Integer NOT NULL,
	[ReferenceTable] Smallint NOT NULL,
	[ReferenceId] Integer NOT NULL,
	[ValidityXML] Ntext NOT NULL,
Primary Key  ([ProductValidityId])
) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create UNIQUE Index [IDX_ProductValidity_Reference]  ON [CNF_ProductValidity] ([ReferenceTable] ,[ReferenceId] ) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_ProductValidity] add  foreign key([SystemId]) references [CNF_System] ([SystemId]) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_AttributeTemplate
add AttributeTemplateSubType smallint null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Attribute
add RootId int null, ParentId int null, ValidityOverride smallint null, [Enabled] smallint null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_Attribute
set RootId=AttributeId, ValidityOverride=0, [Enabled]=1
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Attribute
alter column RootId int not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Attribute
alter column ValidityOverride smallint not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Attribute
alter column [Enabled] smallint not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Attribute] add  foreign key([RootId]) references [CNF_Attribute] ([AttributeId]) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Attribute] add  foreign key([ParentId]) references [CNF_Attribute] ([AttributeId]) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Product
add ValidityOverride smallint null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_Product
set ValidityOverride=0
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Product
alter column ValidityOverride smallint not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Ledger
add SystemId int null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>update DATA_Ledger
set SystemId=SYD
from (select TransactionId as TID, SystemId as SYD from DATA_Transaction) TRN
where TRN.TID=TransactionId
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Ledger
alter column SystemId int not null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Ledger add  foreign key([SystemId]) references [CNF_System] ([SystemId]) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_Product2Attribute] (
	[Product2AttributeId] Integer Identity(1,1) NOT NULL,
	[ProductId] Integer NOT NULL,
	[AttributeId] Integer NULL,
	[PriorityOrder] Smallint NULL,
	[ValidityOverride] Smallint NOT NULL,
Primary Key  ([Product2AttributeId])
) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Product2Attribute] add  foreign key([AttributeId]) references [CNF_Attribute] ([AttributeId]) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Product2Attribute] add  foreign key([ProductId]) references [CNF_Product] ([ProductId]) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_Product2Event] (
	[Product2EventId] Integer Identity(1,1) NOT NULL UNIQUE,
	[ProductId] Integer NOT NULL,
	[EventId] Integer NOT NULL,
Primary Key  ([Product2EventId])
) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Product2Event] add  foreign key([EventId]) references [CNF_Event] ([EventId]) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_Product2Event] add  foreign key([ProductId]) references [CNF_Product] ([ProductId]) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ettore Bottega</ADDEDBY>
			<SQLVERSION>1.14</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Change foreign key relation for table DATA_Media from old to new report configuration

  0. Drop foreign key CntxReportGroupId for DATA_Media
  1. Create new column for the foreign key DocTemplateId for DATA_Media
  2. Add foreign key constraint WITH NO CHECK, populate new values, activate constraint
  3. Alter procedure [sp_ui_DATA_Media_insert]
  4. Alter procedure [sp_ui_DATA_Media_update]

			</REASON>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @parenttable nvarchar(max);
DECLARE @refrencedtable nvarchar(max);
DECLARE @referencedcolumn nvarchar(max);
DECLARE @foreign_key_name nvarchar(max);
DECLARE @sqlstmt nvarchar(max);

select @parenttable = '[dbo].[DATA_Media]';
select @refrencedtable = '[dbo].[DOC_CntxReportGroup]';
select @referencedcolumn = 'CntxReportGroupId';

-- search the foreign key name to be dropped
SELECT @foreign_key_name = f.name
  FROM sys.foreign_keys AS f
 INNER JOIN sys.foreign_key_columns AS fc 
    ON f.object_id = fc.constraint_object_id 
 WHERE f.parent_object_id = object_id(@parenttable)
   AND f.referenced_object_id = object_id(@refrencedtable)
   AND COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = @referencedcolumn;

if (len(@foreign_key_name) &gt; 0) 
begin
  -- drop the foreign key constraint
  select @sqlstmt = 'alter table ' + @parenttable + ' drop constraint [' + @foreign_key_name + ']';
  execute sp_executesql @sqlstmt;

  -- drop the foreign key column
  select @sqlstmt = 'alter table ' + @parenttable + ' drop column [' + @referencedcolumn + ']';
  execute sp_executesql @sqlstmt  
end

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>-- add new column for FK
alter table [DATA_Media] add [DocTemplateId] int;

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>-- add the new foreign key constraint WITH NOCHECK (let us polpulate the column)
alter table [DATA_Media] with NOCHECK add constraint [FK_DATA_Media_CNF_DocTemplate] foreign key([DocTemplateId]) 
references [CNF_DocTemplate] ([DocTemplateId]);

-- insert "default" values into foreign key
declare @valore int;
select @valore = min([DocTemplateId]) from [CNF_DocTemplate] where [DocTemplateType] = 2;
update [DATA_Media] set [DocTemplateId] = @valore;

-- activate the foreign key constraint
alter table [DATA_Media] check constraint [FK_DATA_Media_CNF_DocTemplate];
alter table [DATA_Media] alter column [DocTemplateId] int not null;

				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter procedure [dbo].[sp_ui_DATA_Media_insert]	
	@MediaId Integer output ,
	@TableId Integer,
	@VoidType SmallInt,
	@WalletKey Numeric(20),
	@Printed SmallInt,
	@DocTemplateId Integer
as
begin
	insert into DATA_Media
		(TableId, VoidType, WalletKey, Printed, DocTemplateId)
	values 	
		(@TableId,@VoidType,@WalletKey,@Printed,@DocTemplateId)

  select @MediaId= SCOPE_IDENTITY() 

end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter procedure [dbo].[sp_ui_DATA_Media_update]	
	@MediaId Integer,
	@TableId Integer,
	@VoidType SmallInt,
	@WalletKey Numeric(20),
	@Printed SmallInt,
	@DocTemplateId Integer
as
begin
	update	DATA_Media
	set	TableId=@TableId,
		VoidType=@VoidType,
		WalletKey=@WalletKey,
		Printed=@Printed,
		DocTemplateId=@DocTemplateId
	where	MediaId=@MediaId
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.13</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>DATA_Ledger:

0. ReferenceId from "smallint" to "int"
1. Drop unique index
2. Add "reference" fields in the unique index</REASON>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DATA_Ledger
alter column ReferenceId int null</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[DATA_Ledger]') AND name = N'IDX_Ledger_UniqueAccount')
DROP INDEX [IDX_Ledger_UniqueAccount] ON [dbo].[DATA_Ledger] WITH ( ONLINE = OFF )
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>CREATE UNIQUE NONCLUSTERED INDEX [IDX_Ledger_UniqueAccount] ON [dbo].[DATA_Ledger] 
(
	[TransactionId] ASC,
	[LedgerType] ASC,
	[LedgerAccountType] ASC,
	[LedgerAccountId] ASC,
	[ReferenceTable] ASC,
	[ReferenceId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = OFF) ON [PRIMARY]</SCRIPT>
			</SQLSCRIPTLIST>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ettore Bottega</ADDEDBY>
			<SQLVERSION>1.12</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Add missing foreign keys to CNF_Doc... tables:
  0. CNF_DocCategory ---- CNF_System.SystemId
  1. CNF_DocRepository ---- CNF_System.SystemId
  2. CNF_DocTemplate2Device ---- CNF_Device.DeviceId
  3. CNF_DocTemplate ---- CNF_System.SystemId
			</REASON>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_DocCategory] add  foreign key([SystemId]) references [CNF_System] ([SystemId]) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_DocRepository] add  foreign key([SystemId]) references [CNF_System] ([SystemId]) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_DocTemplate2Device] add  foreign key([DeviceId]) references [CNF_Device] ([DeviceId]) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_DocTemplate] add  foreign key([SystemId]) references [CNF_System] ([SystemId]) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.11</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Field CNF_DocTemplate.DocDatasourceId

from "nullable" to "not null"</REASON>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_DocTemplate
alter column DocDatasourceId int null</SCRIPT>
			</SQLSCRIPTLIST>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.10</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Dropped Table ADM_Performance2AccessArea</REASON>
			<SQLSCRIPTLIST>
				<SCRIPT>drop table ADM_Performance2AccessArea</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>drop procedure sp_ui_ADM_Performance2AccessArea_insert</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>drop procedure sp_ui_ADM_Performance2AccessArea_update</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>drop procedure sp_ui_ADM_Performance2AccessArea_delete</SCRIPT>
			</SQLSCRIPTLIST>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.9</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>StoredProcs for modifications 1.8</REASON>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER procedure [dbo].[sp_ui_ADM_Gate2AccessArea_insert]	
	@Gate2AccessAreaId Integer output ,
	@AccessAreaId Integer,
	@GateId Integer
as
begin
	insert into ADM_Gate2AccessArea
		(AccessAreaId, GateId)
	values 	
		(@AccessAreaId,@GateId)

	select @Gate2AccessAreaId= SCOPE_IDENTITY() 
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER procedure [dbo].[sp_ui_ADM_Gate2AccessArea_update]	
	@Gate2AccessAreaId Integer,
	@AccessAreaId Integer,
	@GateId Integer
as
begin
	update	ADM_Gate2AccessArea
	set	AccessAreaId=@AccessAreaId,
		GateId=@GateId
	where	Gate2AccessAreaId=@Gate2AccessAreaId
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.8</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Dropped field ADM_Gate2AccessArea.AccessConfigurationId</REASON>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @foreign_key_name nvarchar(max);
DECLARE @dropstmt nvarchar(max);

SELECT @foreign_key_name = f.name
  FROM sys.foreign_keys AS f
 INNER JOIN sys.foreign_key_columns AS fc 
    ON f.object_id = fc.constraint_object_id 
 WHERE f.parent_object_id = object_id(N'[dbo].[ADM_Gate2AccessArea]')
   AND f.referenced_object_id = object_id(N'[dbo].[ADM_AccessConfiguration]')
   AND COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'AccessConfigurationId';

if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[ADM_Gate2AccessArea] DROP CONSTRAINT [' + @foreign_key_name + ']';
  execute sp_executesql @dropstmt
end</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>drop index ADM_Gate2AccessArea.IX_ADM_Gate2AccessArea</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table ADM_Gate2AccessArea
drop column AccessConfigurationId</SCRIPT>
			</SQLSCRIPTLIST>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.7</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Added fields to ADM_AccessConfiguration
- LayoutCode
- Image
- XmlLayout</REASON>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table ADM_AccessConfiguration
add LayoutCode nvarchar(10)</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table ADM_AccessConfiguration
add Image nvarchar(50)</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table ADM_AccessConfiguration
add XmlLayout nvarchar(50)</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER procedure [dbo].[sp_ui_ADM_AccessConfiguration_insert]	
	@AccessConfigurationId Integer output ,
	@LocationId Integer,
	@LayoutCode nvarchar(10),
	@Name NVarChar(30),
	@Description NText,
	@Image nvarchar(50),
	@XmlLayout nvarchar(50)
as
begin
	insert into ADM_AccessConfiguration
		(LocationId, LayoutCode, Name, Description, Image, XmlLayout)
	values 	
		(@LocationId, @LayoutCode, @Name, @Description, @Image, @XmlLayout)

	select @AccessConfigurationId= SCOPE_IDENTITY() 
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER procedure [dbo].[sp_ui_ADM_AccessConfiguration_update]	
	@AccessConfigurationId Integer,
	@LocationId Integer,
	@LayoutCode nvarchar(10),
	@Name NVarChar(30),
	@Description NText,
	@Image nvarchar(50),
	@XmlLayout nvarchar(50)
as
begin
	update	ADM_AccessConfiguration
	set	LocationId=@LocationId,
		LayoutCode=@LayoutCode,
		Name=@Name,
		Description=@Description,
		Image=@Image,
		XmlLayout=@XmlLayout
	where	AccessConfigurationId=@AccessConfigurationId
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Antonella Mura</ADDEDBY>
			<SQLVERSION>1.6</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>0. Add new fields into CNF_DataMask:
    - FieldDescription  U_Text         nullable 
    - FieldHint             U_Name50    nullable
    - Required            U_Bool          mandatory
    - IsUnique            U_Bool          mandatory 
    - MaskTableEdit   U_Bool          mandatory
    - MaxLength       smallint          nullable
    - Height              smallint          mandatory

1. Rename CNF_DataMask's field Length in Width

2. Create table CNF_MaskTable

3. Create table CNF_MaskTableItem

4-5-6. Create foreign keys

7-8. Update CNF_DataMask's store procedures for new fields

9-10-11. Create store procedure for new table CNF_MaskTable

12-13-14. Create store procedure for new table CNF_MaskTableItem

15. From patch 1.4: store procedure update in consequence of renaming field CNF_PriceList.PriceListStatus 

			</REASON>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_DataMask 
add FieldDescription ntext,
FieldHint nvarchar(50),
Required smallint not null default 0,
IsUnique smallint not null default 0,
MaskTableId integer,
MaskTableEdit smallint not null default 0,
MaxLength smallint,
Height smallint not null default 0</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>EXEC sp_rename 'CNF_DataMask.Length', 'Width', 'COLUMN'</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_MaskTable] (
	[MaskTableId] Integer Identity(1,1) NOT NULL,
	[MaskTableAK] Varchar(32) NOT NULL,
	[MaskTableName] Nvarchar(50) NOT NULL,
	[MaskTableDescription] Ntext NULL,
	[Private] Smallint NOT NULL,
	[Enabled] Smallint NOT NULL,
Primary Key  ([MaskTableId])
) </SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_MaskTableItem] (
	[MaskTableItemId] Integer Identity(1,1) NOT NULL,
	[MasterFieldId] Integer NULL,
	[MaskTableId] Integer NOT NULL,
	[ItemName] Nvarchar(30) NOT NULL,
	[ItemValue] Nvarchar(30) NULL,
Primary Key  ([MaskTableItemId])
) </SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_DataMask] add foreign key([MaskTableId]) references [CNF_MaskTable] ([MaskTableId]) </SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_MaskTableItem] add foreign key([MaskTableId]) references [CNF_MaskTable] ([MaskTableId]) </SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_MaskTableItem] add foreign key([MasterFieldId]) references [CNF_MaskTableItem] ([MaskTableItemId]) </SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER procedure [dbo].[sp_ui_CNF_DataMask_insert]	
		@DataMaskId Integer output ,
		@MaskTableId Integer,
		@MaskId Integer,
		@DataType SmallInt,
		@FieldNumber SmallInt,
		@AnagCode SmallInt,
		@MaskGroup SmallInt,
		@FieldName NVarChar(30),
		@Width SmallInt,
		@Height SmallInt,
		@Posx SmallInt,
		@Posy SmallInt,
		@KeyNumber SmallInt,
		@RuleId VarChar(40),
		@ObjType SmallInt,
		@Language SmallInt,
		@FieldDescription NText,
		@FieldHint NVarChar(50),
		@Required SmallInt,
		@IsUnique SmallInt,
		@MaskTableEdit SmallInt,
		@MaxLength SmallInt
as
begin
  insert into CNF_DataMask
   (MaskTableId, MaskId, DataType, FieldNumber, AnagCode, MaskGroup, FieldName, Width, Height, Posx, Posy, KeyNumber, RuleId, ObjType, Language, FieldDescription, FieldHint, Required, IsUnique, MaskTableEdit, MaxLength)
		values 	
			(@MaskTableId,@MaskId,@DataType,@FieldNumber,@AnagCode,@MaskGroup,@FieldName,@Width,@Height,@Posx,@Posy,@KeyNumber,@RuleId,@ObjType,@Language,@FieldDescription,@FieldHint,@Required,@IsUnique,@MaskTableEdit,@MaxLength)


  select @DataMaskId= SCOPE_IDENTITY() 


end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>	ALTER procedure [dbo].[sp_ui_CNF_DataMask_update]	
		@DataMaskId Integer,
		@MaskTableId Integer,
		@MaskId Integer,
		@DataType SmallInt,
		@FieldNumber SmallInt,
		@AnagCode SmallInt,
		@MaskGroup SmallInt,
		@FieldName NVarChar(30),
		@Width SmallInt,
		@Height SmallInt,
		@Posx SmallInt,
		@Posy SmallInt,
		@KeyNumber SmallInt,
		@RuleId VarChar(40),
		@ObjType SmallInt,
		@Language SmallInt,
		@FieldDescription NText,
		@FieldHint NVarChar(50),
		@Required SmallInt,
		@IsUnique SmallInt,
		@MaskTableEdit SmallInt,
		@MaxLength SmallInt
	as
	begin
		update	CNF_DataMask
		set	MaskTableId=@MaskTableId,
			MaskId=@MaskId,
			DataType=@DataType,
			FieldNumber=@FieldNumber,
			AnagCode=@AnagCode,
			MaskGroup=@MaskGroup,
			FieldName=@FieldName,
			Width=@Width,
			Height=@Height,
			Posx=@Posx,
			Posy=@Posy,
			KeyNumber=@KeyNumber,
			RuleId=@RuleId,
			ObjType=@ObjType,
			Language=@Language,
			FieldDescription=@FieldDescription,
			FieldHint=@FieldHint,
			Required=@Required,
			IsUnique=@IsUnique,
			MaskTableEdit=@MaskTableEdit,
			MaxLength=@MaxLength
		where	DataMaskId=@DataMaskId

	end</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>	create procedure [dbo].[sp_ui_CNF_MaskTable_delete]	
		@MaskTableId Integer	
	as
	begin
		delete from	CNF_MaskTable
		where	MaskTableId=@MaskTableId

	end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>	create procedure [dbo].[sp_ui_CNF_MaskTable_insert]	
		@MaskTableId Integer output ,
		@MaskTableAK VarChar(32),
		@MaskTableName NVarChar(50),
		@MaskTableDescription NText,
		@Private SmallInt,
		@Enabled SmallInt
	as
	begin
		insert into CNF_MaskTable
			(MaskTableAK, MaskTableName, MaskTableDescription, Private, Enabled)
		values 	
			(@MaskTableAK,@MaskTableName,@MaskTableDescription,@Private,@Enabled)


		select @MaskTableId= SCOPE_IDENTITY() 


	end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>	create procedure [dbo].[sp_ui_CNF_MaskTable_update]	
		@MaskTableId Integer,
		@MaskTableAK VarChar(32),
		@MaskTableName NVarChar(50),
		@MaskTableDescription NText,
		@Private SmallInt,
		@Enabled SmallInt
	as
	begin
		update	CNF_MaskTable
		set	MaskTableAK=@MaskTableAK,
			MaskTableName=@MaskTableName,
			MaskTableDescription=@MaskTableDescription,
			Private=@Private,
			Enabled=@Enabled
		where	MaskTableId=@MaskTableId

	end</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>	create procedure [dbo].[sp_ui_CNF_MaskTableItem_delete]	
		@MaskTableItemId Integer	
	as
	begin
		delete from	CNF_MaskTableItem
		where	MaskTableItemId=@MaskTableItemId

	end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>	create procedure [dbo].[sp_ui_CNF_MaskTableItem_insert]	
		@MaskTableItemId Integer output ,
		@MasterFieldId Integer,
		@MaskTableId Integer,
		@ItemName NVarChar(30),
		@ItemValue NVarChar(30)
	as
	begin
		insert into CNF_MaskTableItem
			(MasterFieldId, MaskTableId, ItemName, ItemValue)
		values 	
			(@MasterFieldId,@MaskTableId,@ItemName,@ItemValue)


		select @MaskTableItemId= SCOPE_IDENTITY() 


	end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>	create procedure [dbo].[sp_ui_CNF_MaskTableItem_update]	
		@MaskTableItemId Integer,
		@MasterFieldId Integer,
		@MaskTableId Integer,
		@ItemName NVarChar(30),
		@ItemValue NVarChar(30)
	as
	begin
		update	CNF_MaskTableItem
		set	MasterFieldId=@MasterFieldId,
			MaskTableId=@MaskTableId,
			ItemName=@ItemName,
			ItemValue=@ItemValue
		where	MaskTableItemId=@MaskTableItemId

	end</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>	ALTER procedure [dbo].[sp_ui_CNF_PriceList_insert]	
		@PriceListId Integer output ,
		@Key1 Integer,
		@PriceListAK VarChar(32),
		@PriceListType SmallInt,
		@PriceListCode NVarChar(10),
		@PriceListName NVarChar(50),
		@Enabled SmallInt,
		@ValidFrom DateTime,
		@ValidTo DateTime,
		@SystemId Integer
	as
	begin
		insert into CNF_PriceList
			(Key1, PriceListAK, PriceListType, PriceListCode, PriceListName, Enabled, ValidFrom, ValidTo, SystemId)
		values 	
			(@Key1,@PriceListAK,@PriceListType,@PriceListCode,@PriceListName,@Enabled,@ValidFrom,@ValidTo,@SystemId)


		select @PriceListId= SCOPE_IDENTITY() 


	end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>	ALTER procedure [dbo].[sp_ui_CNF_PriceList_update]	
		@PriceListId Integer,
		@Key1 Integer,
		@PriceListAK VarChar(32),
		@PriceListType SmallInt,
		@PriceListCode NVarChar(10),
		@PriceListName NVarChar(50),
		@Enabled SmallInt,
		@ValidFrom DateTime,
		@ValidTo DateTime,
		@SystemId Integer
	as
	begin
		update	CNF_PriceList
		set	Key1=@Key1,
			PriceListAK=@PriceListAK,
			PriceListType=@PriceListType,
			PriceListCode=@PriceListCode,
			PriceListName=@PriceListName,
			Enabled=@Enabled,
			ValidFrom=@ValidFrom,
			ValidTo=@ValidTo,
			SystemId=@SystemId
		where	PriceListId=@PriceListId

	end</SCRIPT>
			</SQLSCRIPTLIST>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ettore Bottega</ADDEDBY>
			<SQLVERSION>1.5</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>1. remove column StageConfigurationId from CNF_Performance table, with koreign key drop and stored procedures update.

2. New Document Manager tables:
  - CNF_DocTemplate
  - CNF_DocTemplate2Device
  - CNF_DocRepository
  - CNF_DocTemplateParam
  - CNF_DocTemplateParamValue
  - CNF_DocCategory

			</REASON>
			<SQLSCRIPTLIST>
				<SCRIPT>DECLARE @foreign_key_name nvarchar(32);
DECLARE @dropstmt nvarchar(100);

SELECT @foreign_key_name = f.name
  FROM sys.foreign_keys AS f
 INNER JOIN sys.foreign_key_columns AS fc 
    ON f.object_id = fc.constraint_object_id 
 WHERE f.parent_object_id = object_id(N'[dbo].[CNF_Performance]')
   AND f.referenced_object_id = object_id(N'[dbo].[CNF_StageConfiguration]')
   AND COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = 'StageConfigurationId';

if (len(@foreign_key_name) &gt; 0) 
begin
  select @dropstmt = 'ALTER TABLE [dbo].[CNF_Performance] DROP CONSTRAINT [' + @foreign_key_name + ']';
  execute sp_executesql @dropstmt
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_Performance drop column StageConfigurationId</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER procedure [dbo].[sp_ui_CNF_Performance_insert]	
	@PerformanceId Integer output ,
	@EventId Integer,
	@PriceTableId Integer,
	@PerformanceAK VarChar(32),
	@PerfDateTime DateTime,
	@LocationId Integer,
	@AccessConfigurationId Integer,
	@Status SmallInt,
	@PerfTurno VarChar(10),
	@TimeOpening Integer,
	@TimeLimit Integer,
	@PerformanceEnd DateTime,
	@PurgeDeltaTime DateTime,
	@OnSaleFrom DateTime,
	@OnSaleUntil DateTime,
	@MoneyCardId Integer,
	@MoneyCardCost Float
as
begin
insert into CNF_Performance
	(EventId, PriceTableId, PerformanceAK, PerfDateTime, LocationId, AccessConfigurationId, Status, PerfTurno, TimeOpening, TimeLimit, PerformanceEnd, PurgeDeltaTime, OnSaleFrom, OnSaleUntil, MoneyCardId, MoneyCardCost)
	values 	
(@EventId,@PriceTableId,@PerformanceAK,@PerfDateTime,@LocationId,@AccessConfigurationId,@Status,@PerfTurno,@TimeOpening,@TimeLimit,@PerformanceEnd,@PurgeDeltaTime,@OnSaleFrom,@OnSaleUntil,@MoneyCardId,@MoneyCardCost)

	select @PerformanceId= SCOPE_IDENTITY() 


end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER procedure [dbo].[sp_ui_CNF_Performance_update]	
	@PerformanceId Integer,
	@EventId Integer,
	@PriceTableId Integer,
	@PerformanceAK VarChar(32),
	@PerfDateTime DateTime,
	@LocationId Integer,
	@AccessConfigurationId Integer,
	@Status SmallInt,
	@PerfTurno VarChar(10),
	@TimeOpening Integer,
	@TimeLimit Integer,
	@PerformanceEnd DateTime,
	@PurgeDeltaTime DateTime,
	@OnSaleFrom DateTime,
	@OnSaleUntil DateTime,
	@MoneyCardId Integer,
	@MoneyCardCost Float
as
begin
	update	CNF_Performance
set	EventId=@EventId,
	PriceTableId=@PriceTableId,
	PerformanceAK=@PerformanceAK,
	PerfDateTime=@PerfDateTime,
	LocationId=@LocationId,
	AccessConfigurationId=@AccessConfigurationId,
	Status=@Status,
	PerfTurno=@PerfTurno,
	TimeOpening=@TimeOpening,
	TimeLimit=@TimeLimit,
	PerformanceEnd=@PerformanceEnd,
	PurgeDeltaTime=@PurgeDeltaTime,
	OnSaleFrom=@OnSaleFrom,
	OnSaleUntil=@OnSaleUntil,
	MoneyCardId=@MoneyCardId,
	MoneyCardCost=@MoneyCardCost
where	PerformanceId=@PerformanceId
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_DocTemplate] (
	[DocTemplateId] Integer Identity(1,1) NOT NULL,
	[SystemId] Integer NOT NULL,
	[DocCategoryId] Integer NULL,
	[DocTemplateAk] Varchar(32) NOT NULL UNIQUE,
	[DocCntxType] Smallint NOT NULL,
	[DocTemplateType] Smallint NOT NULL,
	[DocTemplateName] Nvarchar(50) NOT NULL,
	[Enabled] Smallint NOT NULL,
	[DocDatasourceId] Integer NOT NULL,
	[PriorityOrder] Smallint NULL,
Primary Key  ([DocTemplateId])
) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_DocTemplate2Device] (
	[DocTemplate2DeviceId] Integer Identity(1,1) NOT NULL,
	[PriorityOrder] Smallint NULL,
	[DocTemplateId] Integer NOT NULL,
	[DeviceId] Integer NOT NULL,
Primary Key  ([DocTemplate2DeviceId])
) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_DocRepository] (
	[DocRepositoryId] Integer Identity(1,1) NOT NULL,
	[SystemId] Integer NOT NULL,
	[ParentId] Integer NULL,
	[DocTemplateId] Integer NULL,
Primary Key  ([DocRepositoryId])
) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_DocTemplateParam] (
	[DocTemplateParamId] Integer Identity(1,1) NOT NULL,
	[DocTemplateId] Integer NOT NULL,
	[ParamName] Nvarchar(30) NOT NULL,
	[ParamType] Smallint NOT NULL,
	[ParamCaption] Nvarchar(50) NULL,
Primary Key  ([DocTemplateParamId])
) </SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_DocTemplateParamValue] (
	[DocTemplateParamValueId] Integer Identity(1,1) NOT NULL,
	[DocTemplateParamId] Integer NOT NULL,
	[DocTemplateId] Integer NOT NULL,
	[CntxPropertyType] Smallint NULL,
	[ParamValue] Nvarchar(50) NULL,
	[ParamCaption] Nvarchar(50) NULL,
	[ReadOnly] Smallint NOT NULL,
	[NotNull] Smallint NOT NULL,
Primary Key  ([DocTemplateParamValueId])
) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Create table [CNF_DocCategory] (
	[DocCategoryId] Integer Identity(1,1) NOT NULL,
	[SystemId] Integer NOT NULL,
	[DocCntxType] Smallint NOT NULL,
	[ParentId] Integer NULL,
	[DocCategoryName] Nvarchar(50) NOT NULL,
Primary Key  ([DocCategoryId])
) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_DocTemplate] add  foreign key([DocDatasourceId]) references [CNF_DocTemplate] ([DocTemplateId]) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_DocTemplate2Device] add  foreign key([DocTemplateId]) references [CNF_DocTemplate] ([DocTemplateId]) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_DocTemplateParamValue] add  foreign key([DocTemplateId]) references [CNF_DocTemplate] ([DocTemplateId]) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_DocRepository] add  foreign key([DocTemplateId]) references [CNF_DocTemplate] ([DocTemplateId]) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_DocRepository] add  foreign key([ParentId]) references [CNF_DocRepository] ([DocRepositoryId]) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_DocTemplateParam] add  foreign key([DocTemplateId]) references [CNF_DocTemplate] ([DocTemplateId]) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_DocTemplateParamValue] add  foreign key([DocTemplateParamId]) references [CNF_DocTemplateParam] ([DocTemplateParamId]) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_DocCategory] add  foreign key([ParentId]) references [CNF_DocCategory] ([DocCategoryId]) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>Alter table [CNF_DocTemplate] add  foreign key([DocCategoryId]) references [CNF_DocCategory] ([DocCategoryId]) 
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>	create procedure [dbo].[sp_ui_CNF_DocTemplate_insert]	
		@DocTemplateId Integer output ,
		@SystemId Integer,
		@DocCategoryId Integer,
		@DocTemplateAk VarChar(32),
		@DocCntxType SmallInt,
		@DocTemplateType SmallInt,
		@DocTemplateName NVarChar(50),
		@Enabled SmallInt,
		@DocDatasourceId Integer,
		@PriorityOrder SmallInt
	as
	begin
		insert into CNF_DocTemplate
			(SystemId, DocCategoryId, DocTemplateAk, DocCntxType, DocTemplateType, DocTemplateName, Enabled, DocDatasourceId, PriorityOrder)
		values 	
			(@SystemId,@DocCategoryId,@DocTemplateAk,@DocCntxType,@DocTemplateType,@DocTemplateName,@Enabled,@DocDatasourceId,@PriorityOrder)


		select @DocTemplateId= SCOPE_IDENTITY() 


	end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>	create procedure [dbo].[sp_ui_CNF_DocTemplate_update]	
		@DocTemplateId Integer,
		@SystemId Integer,
		@DocCategoryId Integer,
		@DocTemplateAk VarChar(32),
		@DocCntxType SmallInt,
		@DocTemplateType SmallInt,
		@DocTemplateName NVarChar(50),
		@Enabled SmallInt,
		@DocDatasourceId Integer,
		@PriorityOrder SmallInt
	as
	begin
		update	CNF_DocTemplate
		set	SystemId=@SystemId,
			DocCategoryId=@DocCategoryId,
			DocTemplateAk=@DocTemplateAk,
			DocCntxType=@DocCntxType,
			DocTemplateType=@DocTemplateType,
			DocTemplateName=@DocTemplateName,
			Enabled=@Enabled,
			DocDatasourceId=@DocDatasourceId,
			PriorityOrder=@PriorityOrder
		where	DocTemplateId=@DocTemplateId

	end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>	create procedure [dbo].[sp_ui_CNF_DocTemplate_delete]	
		@DocTemplateId Integer	
	as
	begin
		delete from	CNF_DocTemplate
		where	DocTemplateId=@DocTemplateId

	end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>	create procedure [dbo].[sp_ui_CNF_DocCategory_insert]	
		@DocCategoryId Integer output ,
		@SystemId Integer,
		@DocCntxType SmallInt,
		@ParentId Integer,
		@DocCategoryName NVarChar(50)
	as
	begin
		insert into CNF_DocCategory
			(SystemId, DocCntxType, ParentId, DocCategoryName)
		values 	
			(@SystemId,@DocCntxType,@ParentId,@DocCategoryName)


		select @DocCategoryId= SCOPE_IDENTITY() 


	end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>	create procedure [dbo].[sp_ui_CNF_DocCategory_update]	
		@DocCategoryId Integer,
		@SystemId Integer,
		@DocCntxType SmallInt,
		@ParentId Integer,
		@DocCategoryName NVarChar(50)
	as
	begin
		update	CNF_DocCategory
		set	SystemId=@SystemId,
			DocCntxType=@DocCntxType,
			ParentId=@ParentId,
			DocCategoryName=@DocCategoryName
		where	DocCategoryId=@DocCategoryId

	end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>	create procedure [dbo].[sp_ui_CNF_DocCategory_delete]	
		@DocCategoryId Integer	
	as
	begin
		delete from	CNF_DocCategory
		where	DocCategoryId=@DocCategoryId

	end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>	create procedure [dbo].[sp_ui_CNF_DocRepository_insert]	
		@DocRepositoryId Integer output ,
		@SystemId Integer,
		@ParentId Integer,
		@DocTemplateId Integer
	as
	begin
		insert into CNF_DocRepository
			(SystemId, ParentId, DocTemplateId)
		values 	
			(@SystemId,@ParentId,@DocTemplateId)


		select @DocRepositoryId= SCOPE_IDENTITY() 


	end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>	create procedure [dbo].[sp_ui_CNF_DocRepository_update]	
		@DocRepositoryId Integer,
		@SystemId Integer,
		@ParentId Integer,
		@DocTemplateId Integer
	as
	begin
		update	CNF_DocRepository
		set	SystemId=@SystemId,
			ParentId=@ParentId,
			DocTemplateId=@DocTemplateId
		where	DocRepositoryId=@DocRepositoryId

	end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>	create procedure [dbo].[sp_ui_CNF_DocRepository_delete]	
		@DocRepositoryId Integer	
	as
	begin
		delete from	CNF_DocRepository
		where	DocRepositoryId=@DocRepositoryId

	end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>	create procedure [dbo].[sp_ui_CNF_DocTemplate2Device_insert]	
		@DocTemplate2DeviceId Integer output ,
		@PriorityOrder SmallInt,
		@DocTemplateId Integer,
		@DeviceId Integer
	as
	begin
		insert into CNF_DocTemplate2Device
			(PriorityOrder, DocTemplateId, DeviceId)
		values 	
			(@PriorityOrder,@DocTemplateId,@DeviceId)


		select @DocTemplate2DeviceId= SCOPE_IDENTITY() 


	end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>	create procedure [dbo].[sp_ui_CNF_DocTemplate2Device_update]	
		@DocTemplate2DeviceId Integer,
		@PriorityOrder SmallInt,
		@DocTemplateId Integer,
		@DeviceId Integer
	as
	begin
		update	CNF_DocTemplate2Device
		set	PriorityOrder=@PriorityOrder,
			DocTemplateId=@DocTemplateId,
			DeviceId=@DeviceId
		where	DocTemplate2DeviceId=@DocTemplate2DeviceId

	end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>	create procedure [dbo].[sp_ui_CNF_DocTemplate2Device_delete]	
		@DocTemplate2DeviceId Integer	
	as
	begin
		delete from	CNF_DocTemplate2Device
		where	DocTemplate2DeviceId=@DocTemplate2DeviceId

	end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>	create procedure [dbo].[sp_ui_CNF_DocTemplateParam_insert]	
		@DocTemplateParamId Integer output ,
		@DocTemplateId Integer,
		@ParamName NVarChar(30),
		@ParamType SmallInt,
		@ParamCaption NVarChar(50)
	as
	begin
		insert into CNF_DocTemplateParam
			(DocTemplateId, ParamName, ParamType, ParamCaption)
		values 	
			(@DocTemplateId,@ParamName,@ParamType,@ParamCaption)


		select @DocTemplateParamId= SCOPE_IDENTITY() 


	end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>	create procedure [dbo].[sp_ui_CNF_DocTemplateParam_update]	
		@DocTemplateParamId Integer,
		@DocTemplateId Integer,
		@ParamName NVarChar(30),
		@ParamType SmallInt,
		@ParamCaption NVarChar(50)
	as
	begin
		update	CNF_DocTemplateParam
		set	DocTemplateId=@DocTemplateId,
			ParamName=@ParamName,
			ParamType=@ParamType,
			ParamCaption=@ParamCaption
		where	DocTemplateParamId=@DocTemplateParamId

	end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>	create procedure [dbo].[sp_ui_CNF_DocTemplateParam_delete]	
		@DocTemplateParamId Integer	
	as
	begin
		delete from	CNF_DocTemplateParam
		where	DocTemplateParamId=@DocTemplateParamId

	end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>	create procedure [dbo].[sp_ui_CNF_DocTemplateParamValue_insert]	
		@DocTemplateParamValueId Integer output ,
		@DocTemplateParamId Integer,
		@DocTemplateId Integer,
		@CntxPropertyType SmallInt,
		@ParamValue NVarChar(50),
		@ParamCaption NVarChar(50),
		@ReadOnly SmallInt,
		@NotNull SmallInt
	as
	begin
		insert into CNF_DocTemplateParamValue
			(DocTemplateParamId, DocTemplateId, CntxPropertyType, ParamValue, ParamCaption, ReadOnly, NotNull)
		values 	
			(@DocTemplateParamId,@DocTemplateId,@CntxPropertyType,@ParamValue,@ParamCaption,@ReadOnly,@NotNull)


		select @DocTemplateParamValueId= SCOPE_IDENTITY() 


	end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>	create procedure [dbo].[sp_ui_CNF_DocTemplateParamValue_update]	
		@DocTemplateParamValueId Integer,
		@DocTemplateParamId Integer,
		@DocTemplateId Integer,
		@CntxPropertyType SmallInt,
		@ParamValue NVarChar(50),
		@ParamCaption NVarChar(50),
		@ReadOnly SmallInt,
		@NotNull SmallInt
	as
	begin
		update	CNF_DocTemplateParamValue
		set	DocTemplateParamId=@DocTemplateParamId,
			DocTemplateId=@DocTemplateId,
			CntxPropertyType=@CntxPropertyType,
			ParamValue=@ParamValue,
			ParamCaption=@ParamCaption,
			ReadOnly=@ReadOnly,
			NotNull=@NotNull
		where	DocTemplateParamValueId=@DocTemplateParamValueId

	end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>	create procedure [dbo].[sp_ui_CNF_DocTemplateParamValue_delete]	
		@DocTemplateParamValueId Integer	
	as
	begin
		delete from	CNF_DocTemplateParamValue
		where	DocTemplateParamValueId=@DocTemplateParamValueId

	end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Antonella Mura</ADDEDBY>
			<SQLVERSION>1.4</SQLVERSION>
			<RMTRACKLINK>205</RMTRACKLINK>
			<REASON>Rename CNF_PriceList.PriceListStatus into Enabled</REASON>
			<SQLSCRIPTLIST>
				<SCRIPT>update CNF_PriceList
set PriceListStatus = 0
where PriceListStatus is null
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>EXEC sp_rename 'CNF_PriceList.PriceListStatus', 'Enabled', 'COLUMN'</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table CNF_PriceList
alter column Enabled smallint not null</SCRIPT>
			</SQLSCRIPTLIST>
			<TABLENAMES/>
		</SQLUPDATE>
		<SQLUPDATE>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<SQLVERSION>1.3</SQLVERSION>
			<RMTRACKLINK/>
			<REASON>Removed TinyInt (replaced with smallint) from DOC tables</REASON>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DOC_CatalogValidity
alter column AnyDest smallint</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DOC_CatalogValidity
alter column AnySource smallint</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DOC_CntxReportItem
alter column LocalExecute smallint</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DOC_Device
alter column Private smallint</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DOC_ParamValue
alter column NotNull smallint not null</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DOC_ParamValue
alter column ReadOnly smallint not null</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DOC_Report
alter column Private smallint</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DOC_Report
alter column LocalExecute smallint</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>alter table DOC_ReportType
alter column LocalExecute smallint not null</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER procedure [dbo].[sp_ui_DOC_CatalogValidity_insert]	
	@CatalogValidityId Integer output ,
	@DestCatalogId Integer,
	@SourceCatalogId Integer,
	@AnyDest smallint,
	@AnySource smallint
as
begin
	insert into DOC_CatalogValidity
		(DestCatalogId, SourceCatalogId, AnyDest, AnySource)
	values 	
		(@DestCatalogId,@SourceCatalogId,@AnyDest,@AnySource)


	select @CatalogValidityId= SCOPE_IDENTITY() 


end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER procedure [dbo].[sp_ui_DOC_CatalogValidity_update]	
	@CatalogValidityId Integer,
	@DestCatalogId Integer,
	@SourceCatalogId Integer,
	@AnyDest smallint,
	@AnySource smallint
as
begin
	update	DOC_CatalogValidity
	set	DestCatalogId=@DestCatalogId,
		SourceCatalogId=@SourceCatalogId,
		AnyDest=@AnyDest,
		AnySource=@AnySource
	where	CatalogValidityId=@CatalogValidityId

end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER procedure [dbo].[sp_ui_DOC_CntxReportItem_insert]	
	@CntxReportItemId Integer output ,
	@CntxReportItemAk VarChar(32),
	@CntxReportId Integer,
	@DeviceId Integer,
	@ReportId Integer,
	@LocalExecute smallint
as
begin
	insert into DOC_CntxReportItem
		(CntxReportItemAk, CntxReportId, DeviceId, ReportId, LocalExecute)
	values 	
		(@CntxReportItemAk,@CntxReportId,@DeviceId,@ReportId,@LocalExecute)


	select @CntxReportItemId= SCOPE_IDENTITY() 

end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER procedure [dbo].[sp_ui_DOC_CntxReportItem_update]	
	@CntxReportItemId Integer,
	@CntxReportItemAk VarChar(32),
	@CntxReportId Integer,
	@DeviceId Integer,
	@ReportId Integer,
	@LocalExecute smallint
as
begin
	update	DOC_CntxReportItem
	set	CntxReportItemAk=@CntxReportItemAk,
		CntxReportId=@CntxReportId,
		DeviceId=@DeviceId,
		ReportId=@ReportId,
		LocalExecute=@LocalExecute
	where	CntxReportItemId=@CntxReportItemId
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER procedure [dbo].[sp_ui_DOC_Device_insert]	
	@DeviceId Integer,
	@Description NVarChar(50),
	@Author NVarChar(50),
	@DataMod SmallDateTime,
	@Private smallint
as
begin
	insert into DOC_Device
		(DeviceId, Description, Author, DataMod, Private)
	values 	
		(@DeviceId,@Description,@Author,@DataMod,@Private)
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER procedure [dbo].[sp_ui_DOC_Device_update]	
	@DeviceId Integer,
	@Description NVarChar(50),
	@Author NVarChar(50),
	@DataMod SmallDateTime,
	@Private smallint
as
begin
	update	DOC_Device
	set	Description=@Description,
		Author=@Author,
		DataMod=@DataMod,
		Private=@Private
	where	DeviceId=@DeviceId
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER procedure [dbo].[sp_ui_DOC_ParamValue_insert]	
	@ParamValueId Integer output ,
	@CntxReportParamId Integer,
	@CntxPropertyId Integer,
	@Value NVarChar(100),
	@NotNull smallint,
	@ReadOnly smallint
as
begin
	insert into DOC_ParamValue
		(CntxReportParamId, CntxPropertyId, Value, NotNull, ReadOnly)
	values 	
		(@CntxReportParamId,@CntxPropertyId,@Value,@NotNull,@ReadOnly)


	select @ParamValueId= SCOPE_IDENTITY() 
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER procedure [dbo].[sp_ui_DOC_ParamValue_update]	
	@ParamValueId Integer,
	@CntxReportParamId Integer,
	@CntxPropertyId Integer,
	@Value NVarChar(100),
	@NotNull smallint,
	@ReadOnly smallint
as
begin
	update	DOC_ParamValue
	set	CntxReportParamId=@CntxReportParamId,
		CntxPropertyId=@CntxPropertyId,
		Value=@Value,
		NotNull=@NotNull,
		ReadOnly=@ReadOnly
	where	ParamValueId=@ParamValueId
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER procedure [dbo].[sp_ui_DOC_Report_insert]	
	@ReportId Integer output ,
	@DeviceId Integer,
	@SystemId Integer,
	@ReportAk VarChar(32),
	@ReportTypeId Integer,
	@Author NVarChar(50),
	@DataMod SmallDateTime,
	@Description NVarChar(50),
	@Private smallint,
	@LocalExecute smallint
as
begin
	insert into DOC_Report
		(DeviceId, SystemId, ReportAk, ReportTypeId, Author, DataMod, Description, Private, LocalExecute)
	values 	
		(@DeviceId,@SystemId,@ReportAk,@ReportTypeId,@Author,@DataMod,@Description,@Private,@LocalExecute)


	select @ReportId= SCOPE_IDENTITY() 


end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER procedure [dbo].[sp_ui_DOC_Report_update]	
	@ReportId Integer,
	@DeviceId Integer,
	@SystemId Integer,
	@ReportAk VarChar(32),
	@ReportTypeId Integer,
	@Author NVarChar(50),
	@DataMod SmallDateTime,
	@Description NVarChar(50),
	@Private smallint,
	@LocalExecute smallint
as
begin
	update	DOC_Report
	set	DeviceId=@DeviceId,
		SystemId=@SystemId,
		ReportAk=@ReportAk,
		ReportTypeId=@ReportTypeId,
		Author=@Author,
		DataMod=@DataMod,
		Description=@Description,
		Private=@Private,
		LocalExecute=@LocalExecute
	where	ReportId=@ReportId
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER procedure [dbo].[sp_ui_DOC_ReportType_insert]	
	@ReportTypeId Integer output ,
	@ReportTypeAk VarChar(32),
	@Description NVarChar(50),
	@LocalExecute smallint
as
begin
	insert into DOC_ReportType
		(ReportTypeAk, Description, LocalExecute)
	values 	
		(@ReportTypeAk,@Description,@LocalExecute)


	select @ReportTypeId= SCOPE_IDENTITY() 
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<SQLSCRIPTLIST>
				<SCRIPT>ALTER procedure [dbo].[sp_ui_DOC_ReportType_update]	
	@ReportTypeId Integer,
	@ReportTypeAk VarChar(32),
	@Description NVarChar(50),
	@LocalExecute smallint
as
begin
	update	DOC_ReportType
	set	ReportTypeAk=@ReportTypeAk,
		Description=@Description,
		LocalExecute=@LocalExecute
	where	ReportTypeId=@ReportTypeId
end
				</SCRIPT>
			</SQLSCRIPTLIST>
			<TABLENAMES/>
		</SQLUPDATE>
		<LATESTDBVERSION>3938</LATESTDBVERSION>
		<SQLUPDATE>
			<SQLVERSION>1.2</SQLVERSION>
			<SQLSCRIPTLIST>
				<SCRIPT/>
			</SQLSCRIPTLIST>
			<ADDEDBY>Ugo Galbiati</ADDEDBY>
			<RMTRACKLINK></RMTRACKLINK>
			<REASON>do nothing.... initial version</REASON>
			<TABLENAMES></TABLENAMES>
		</SQLUPDATE>
	</SQLUPDATELIST>
</ROOT>