
------------------------------------------------------------------------------
-- ADVANTAGE 2004.6.1.0100
-- NEW OPTIONS, LOOKUPS and APPLICATIONS
-- 2015-03-14
------------------------------------------------------------------------------

--1 sp_AB_Get_Fiscal_Span
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AB_Get_Fiscal_Span]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AB_Get_Fiscal_Span]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AB_Get_Fiscal_Span
--Purpose       :Get the START and END of a FISCAL YEAR
--              :    for the SELECTED ACCOUNTING PERIOD
--Parameters    :
--Date          :2003/03/05
--Authors       :TB
--MODS:         :
--2004.4.3      :13/03/09 - Modified @YearEndMonthID validation by INITIALIZING it to ZERO
--              :           and REMOVING its NULL validation
--RL	V6.0	2014-10-14 - If @YearEndMonthID = 1, Then Begining of Fin year is 1 = Jan
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AB_Get_Fiscal_Span]
	(
        @CompanyID int,
        @YearEndMonthID int OUTPUT,
        @StartMonthID int OUTPUT,
        @StartYearID int OUTPUT,
        @SelectedMonthID int OUTPUT,
        @SelectedYearID int OUTPUT
	)

AS

SET NOCOUNT ON

    SET @YearEndMonthID = 0

    SELECT @YearEndMonthID = Year_End_Month_ID
    FROM AW_User_Companies
    WHERE AW_User_Companies_ID = @CompanyID

--	IF @YearEndMonthID IS NULL OR @YearEndMonthID = 0
    IF @YearEndMonthID = 0
        BEGIN
            SET @YearEndMonthID = 2
        END

	--RL 2014-10-14 V6.0 If @YearEndMonthID = 1, Then Begining of Fin year is 1 = Jan
	IF @YearEndMonthID = 12
		SET @StartMonthID = 1								--FIRST month of the Financial Year	
	ELSE
		SET @StartMonthID = @YearEndMonthID + 1            --FIRST month of the Financial Year

    IF @SelectedMonthID <= @YearEndMonthID
        BEGIN
            SET @StartYearID = @SelectedYearID - 1
        END
    ELSE
    IF @SelectedMonthID > @YearEndMonthID
        BEGIN
            SET @StartYearID = @SelectedYearID
        END
     
     --RL 2014-10-14 V6.0 If @YearEndMonthID = 1, Then Begining of Fin year is 1 = Jan of current year  
     IF @YearEndMonthID = 12
       SET @StartYearID = @SelectedYearID
        
SET NOCOUNT OFF
GO

--2 sp_AS_POS_RPT_Invoice_Print
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_POS_RPT_Invoice_Print]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_POS_RPT_Invoice_Print]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_POS_RPT_Invoice_Print
--Purpose       :POS Invoice printing
--Parameters    :
--Date          :2002/04/12
--Authors       :TB
--MODS:         :12/04/02 - Added Time extracted from Transaction_Date
--              :18/04/02 - Added AW_Users.UserName
--              :21/04/02 - Added (AC_Customers_ID) to Customer_Number
--              :22/04/02 - Changed Customer Addresses from Physical to Postal
--              :10/06/02 - Added Company Tel_No & Company Fax_No fields
--              :18/07/02 - Added Discount % per Line Item as [DetailDiscPerc]
--              :10/09/02 - Convert Discount % per Line from SMALLMONEY to MONEY
--              :30/12/02 - Added t.SmallComment AS [Comment] for POS Asset No
--              :26/05/03 - Added ISNULL validation to customer address fields
--              :26/05/03 - Added Cell/Home/Work telephone number (next to Post Code)
--              :09/07/03 - Added Tax_Number (VATNo) effective 1 APR 2004 per SARS
--              :29/01/04 - Added [TranTypeID] to print a PICKLIST with a JOBCARD
--              :09/02/04 - Added [JobSource] to print any JOBCARD source docs
--              :07/06/04 - Added t.AW_User_Companies_ID to locate Company Logo
--              :           path parameter in SpSPOSPrint.CCutSheetLogoA4
--              :17/08/04 - Added p.Pack_Mass to aggregate invoice load mass
--              :21/12/04 - Added XREF to Sys_AW_Payment_Methods and PRINT
--              :08/01/05 - Added [JobRefNo] to print on new MAXIPREST layout
--              :02/02/05 - Added [TextMessage] to print on all invoice documents
--              :19/05/05 - Removed Payment Method from primary SELECT and pre-fetch
--2004.2.4      :28/08/05 - Added t.Amount AS TransactionAmount for OPOS printing
--              :28/10/05 - Added Street and Delivery Adresses
--              :28/10/05 - Added System Option address choice using @WhichAddress
--2004.2.7      :13/04/06 - Replaced SELECT vw_AS_Transactions with AS_Transactions
--2004.3.1      :21/08/09 - Rearranged order of telephone numbers: Work/Cell/Home
--2004.3.2      :08/10/06 - Added [SerialNo] fields
--2004.3.3      :23/11/06 - Added [NameType] for Company Trading Name
--2004.3.4      :23/11/06 - Added Old_Customer_Number as [MerchantNo] for Card Companies
--              :21/03/07 - Added [Make] and [Customer] fields
--2004.3.9      :05/07/08 - Renamed Job XRef from AS_Transaction_Sources
--              :           from 'Jobcard No: ' to 'Sales Order/Job No: '
--2004.4.5      :18/07/09 - Converted into DYNAMIC script to include NEW
--              :           POS Document Print Order of items settings
--2004.4.8      :17/04/10 - Reworked setting DEFAULT message and Added new QUOTE message
--2004.5.0      :26/01/11 - Added [Emails] for all customer e-mail addresses
--              :26/01/11 - Added [CompanyEmail] for company e-mail address
--2004.5.3      :18/07/11 - Added REPLACE syntax to REMOVE single APOSTROPHE in MESSAGES text
--2004.5.7 RGL  :2012-09-20 - Added check to to print tradeing name with company name
--2004.5.8 RGL  :2013-02-20 - Fixed check to to print tradeing name with customer and not company name
--RL	V6.0	:2014-01-28 - Use product print description instead of description
--RL	V6.0	:2014-04-22 - Return Customer ID
--RL	V6.0	:2014-07-19 - Return TDHeader & TDDetail
--RL	V6.1	:2015-03-13 - Fixed - If Firstname was blank it still displayed the /
-------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[sp_AS_POS_RPT_Invoice_Print]
    (
    	@TransactionID int
    )
AS

SET NOCOUNT ON

    DECLARE @SortOrder tinyint,
            @TranTypeID tinyint,
            @Message varchar(100),
            @DefaultMessage varchar(100),
            @QuoteMessage varchar(100),
            @PrintDefaultMessage varchar(10),
            @PrintQuoteMessage varchar(10),
            @OrderFilter tinyint,
            @sql varchar(8000)
            
	DECLARE @Customer_Name varchar(100),
 			@Inv_Address1 varchar(40),
 			@Inv_Address2 varchar(40),
 			@Inv_City varchar(30),
			@Inv_Code varchar(10),
			@Tax_Number varchar(16),
			@AW_YesNo_Invoice tinyint,
			
			@Delivery_Address varchar(40),
			@Delivery_Suburb varchar(40),
			@Delivery_City varchar(30),
			@Delivery_Post_Code varchar(10),
			@AW_YesNo_Delivery_Address tinyint,
			@AC_Customers_ID int
            
    --> Get TranTypeID
    SELECT @TranTypeID = Sys_AW_Transaction_Types_ID
    FROM AS_Transactions
    WHERE AS_Transactions_ID = @TransactionID

    --> Get POS Document Print Sort Order settings
    SELECT @SortOrder = ISNULL(Control_Value, 0)
    FROM Sys_AW_Options
    WHERE Control_Index = 0 AND
    Control_Type = 'CheckBox' AND
    Control_Name = 'chkPOSPrintSortOrder'
    
    --> Get POS Document Print Sort Order Filter
    SELECT @OrderFilter = ISNULL(Control_Index, 0)
    FROM Sys_AW_Options
    WHERE Control_Type = 'OptionButton' AND
    Control_Name = 'optPOSSortOrderFilter' AND
    Control_Value = 'True'

    --------------------------------------------------------------------
    -- Set the MESSAGES text
    --------------------------------------------------------------------
    --> Get the DEFAULT Message text
    SELECT TOP 1 @DefaultMessage = REPLACE(ISNULL(Control_Value, ''), '''', '')
    FROM Sys_AW_Options
    WHERE Control_Index = 0 AND
          Control_Type = 'TextBox' AND
          Control_Name = 'txtPOSDocumentText'

    --> Get the DEFAULT Message CheckBox setting
    SELECT TOP 1 @PrintDefaultMessage = REPLACE(ISNULL(Control_Value, ''), '''', '')
    FROM Sys_AW_Options
    WHERE Control_Index = 0 AND
          Control_Type = 'CheckBox' AND
          Control_Name = 'chkPOSDocumentText'

    --> Get the QUOTE Message text
    SELECT TOP 1 @QuoteMessage = REPLACE(ISNULL(Control_Value, ''), '''', '')
    FROM Sys_AW_Options
    WHERE Control_Index = 0 AND
          Control_Type = 'TextBox' AND
          Control_Name = 'txtPOSQuoteText'

    --> Get the QUOTE Message CheckBox setting
    SELECT TOP 1 @PrintQuoteMessage = REPLACE(ISNULL(Control_Value, ''), '''', '')
    FROM Sys_AW_Options
    WHERE Control_Index = 0 AND
          Control_Type = 'CheckBox' AND
          Control_Name = 'chkPOSQuoteText'

    SET @Message = ''

    IF @TranTypeID = 1        --Quote message
        BEGIN
            IF @PrintQuoteMessage = '1' SET @Message = @QuoteMessage
        END
    ELSE                      --Default message
        BEGIN
            IF @PrintDefaultMessage = '1' SET @Message = @DefaultMessage
        END

    SET @Message = LEFT(@Message, 80)
        
    SET @AC_Customers_ID = 0
    SET @AW_YesNo_Invoice = 0
    SET @AW_YesNo_Delivery_Address = 0
    
    SELECT @AC_Customers_ID = AC_Customers_ID
    FROM AS_Transactions_Address a
	INNER JOIN AS_Transactions_Address_Detail d ON
		a.AS_Transactions_Address_Detail_ID = d.AS_Transactions_Address_Detail_ID
	WHERE a.AS_Transactions_ID = @TransactionID

    IF @AC_Customers_ID <> 0
	BEGIN
		SELECT	@Customer_Name = REPLACE(ISNULL(Customer_Name, ''), '''', ''),
				@Inv_Address1 = REPLACE(ISNULL(Inv_Address1, ''), '''', ''),
				@Inv_Address2 = REPLACE(ISNULL(Inv_Address2, ''), '''', ''), 
				@Inv_City = REPLACE(ISNULL(Inv_City, ''), '''', ''),
				@Inv_Code = REPLACE(ISNULL(Inv_Code, ''), '''', ''),
				@Tax_Number = REPLACE(ISNULL(Tax_Number, ''), '''', ''),
				@AW_YesNo_Invoice = AW_YesNo_Invoice,
				@Delivery_Address = REPLACE(ISNULL(Delivery_Address, ''), '''', ''),
				@Delivery_Suburb = REPLACE(ISNULL(Delivery_Suburb, ''), '''', ''),
				@Delivery_City = REPLACE(ISNULL(Delivery_City, ''), '''', ''),
				@Delivery_Post_Code = REPLACE(ISNULL(Delivery_Post_Code, ''), '''', ''),
				@AW_YesNo_Delivery_Address = AW_YesNo_Delivery_Address
		FROM AS_Transactions_Address a
		INNER JOIN AS_Transactions_Address_Detail d ON 
			a.AS_Transactions_Address_Detail_ID = d.AS_Transactions_Address_Detail_ID
		WHERE a.AS_Transactions_ID = @TransactionID
	END    
    --------------------------------------------------------------------

	SET @sql = ' ' 
	SET @sql = @sql + ' DECLARE @WhichAddress tinyint, '
	SET @sql = @sql + ' @WhichName tinyint, '
	SET @sql = @sql + ' @PaymentMethod varchar(20) '

	SET @sql = @sql + ' SET @WhichAddress = 0 '

    --> Get Print POSTAL or STREET Addres (0 = POSTAL, 1 = STREET)
	SET @sql = @sql + ' SELECT @WhichAddress = ISNULL(Control_Index, 0) '
	SET @sql = @sql + ' FROM Sys_AW_Options '
	SET @sql = @sql + ' WHERE Control_Type = ''OptionButton'' AND '
	SET @sql = @sql + ' Control_Name = ''optPOSPrintAddress'' AND '
	SET @sql = @sql + ' Control_Value = ''True'' '

	SET @sql = @sql + ' SELECT TOP 1 @WhichName = ISNULL(Control_Value, ''0'') '
	SET @sql = @sql + ' FROM Sys_AW_Options '
	SET @sql = @sql + ' WHERE Control_Index = 0 AND '
	SET @sql = @sql + ' Control_Type = ''CheckBox'' AND '
	SET @sql = @sql + ' Control_Name = ''chkPOSPrintTradeName'' '

	SET @sql = @sql + ' SELECT TOP 1 @PaymentMethod = LEFT(ISNULL(pm.[Description], ''''), 20) '
	SET @sql = @sql + ' FROM AS_Transactions_Transactions att '
	SET @sql = @sql + ' LEFT JOIN AS_Transaction_Payments tp '
	SET @sql = @sql + ' ON tp.AS_Transactions_ID = att.Destination_AS_Transactions_ID '
	SET @sql = @sql + ' LEFT JOIN Sys_AW_Payment_Methods pm '
	SET @sql = @sql + ' ON pm.Sys_AW_Payment_Methods_ID = tp.Sys_AW_Payment_Methods_ID '
	SET @sql = @sql + ' WHERE att.Source_AS_Transactions_ID = ' + CONVERT(varchar(20), @TransactionID)
	SET @sql = @sql + ' ORDER BY att.Source_AS_Transactions_ID '

    --------------------------------------------------------------------------------------------------
    --The query starts here
    --------------------------------------------------------------------------------------------------
	SET @sql = @sql + ' SELECT '

	IF @AW_YesNo_Invoice = 1
	BEGIN
      SET @sql = @sql + '''' + @Customer_Name + '''' + ' AS [CustomerName], '	  
	END
	ELSE
	BEGIN		
		--RL V6.1 Fixed - If Firstname was blank it still displayed the /
		SET @sql = @sql + ' CASE WHEN @WhichName = 1 '
		SET @sql = @sql + ' THEN '
		SET @sql = @sql + ' 	CASE WHEN ISNULL(c.Initials,'''') = '''' '
		SET @sql = @sql + ' 	THEN '
		SET @sql = @sql + ' 		CASE WHEN ISNULL(c.Firstnames,'''') = '''' '
		SET @sql = @sql + ' 		THEN LTRIM(RTRIM(c.Surname)) '
		SET @sql = @sql + ' 		ELSE LTRIM(RTRIM(c.Surname)) + '' / '' + LTRIM(RTRIM(c.Firstnames)) '
		SET @sql = @sql + ' 		END '
		SET @sql = @sql + ' 	ELSE '
		SET @sql = @sql + ' 		CASE WHEN ISNULL(c.Firstnames,'''') = '''' '
		SET @sql = @sql + ' 		THEN LTRIM(RTRIM(c.Surname)) + '', '' + LTRIM(RTRIM(c.Initials)) '
		SET @sql = @sql + ' 		ELSE LTRIM(RTRIM(c.Surname)) + '', '' + LTRIM(RTRIM(c.Initials)) + '' / '' + LTRIM(RTRIM(c.Firstnames)) '
		SET @sql = @sql + ' 		END '
		SET @sql = @sql + ' 	END '
		SET @sql = @sql + ' ELSE '
		SET @sql = @sql + ' 	CASE WHEN ISNULL(c.Initials,'''') = '''' '
		SET @sql = @sql + ' 	THEN LTRIM(RTRIM(c.Surname)) '
		SET @sql = @sql + ' 	ELSE LTRIM(RTRIM(c.Surname)) + '', '' + LTRIM(RTRIM(c.Initials)) '
		SET @sql = @sql + ' 	END '
		SET @sql = @sql + ' END AS [CustomerName], '
	END
	           	
    --> NB NB: Customer ADD in POS saves with STREET address copied to POSTAL Address
    --> POSTAL Address
	IF @AW_YesNo_Invoice = 1
	BEGIN
		SET @sql = @sql + '''' + @Inv_Address1 + '''' + ' AS [PostBox], '
		SET @sql = @sql + '''' + @Inv_Address1 + '''' + ' AS [PostBox], '      
		SET @sql = @sql + '''' + @Inv_Address2 + '''' + ' AS [PostOffice], '
		SET @sql = @sql + '''' + @Inv_City + '''' + ' AS [PostCity], '
		SET @sql = @sql + '''' + @Inv_Code + '''' + ' AS [PostCode], '
	END
	ELSE
	BEGIN
		SET @sql = @sql + ' ISNULL(c.Post_Box, '''') AS [PostBox], '
		SET @sql = @sql + ' ISNULL(c.Post_Box, '''') AS [PostBox], '
		SET @sql = @sql + ' ISNULL(c.Post_Office, '''') AS [PostOffice], '
		SET @sql = @sql + ' ISNULL(c.City, '''') AS [PostCity], '
		SET @sql = @sql + ' ISNULL(c.Post_Code, '''') AS [PostCode], '
	END

	IF @AW_YesNo_Invoice = 1
	BEGIN
		SET @sql = @sql + '''' + @Inv_Address1 + '''' + ' AS [StreetAddress], '      
		SET @sql = @sql + '''' + @Inv_Address2 + '''' + ' AS [StreetSuburb], '
		SET @sql = @sql + '''' + @Inv_City + '''' + ' AS [StreetCity], '
		SET @sql = @sql + '''' + @Inv_Code + '''' + ' AS [StreetPostCode], '
	END
	ELSE
	BEGIN
		SET @sql = @sql + ' ISNULL(c.Street_Address, '''') AS [StreetAddress], '
		SET @sql = @sql + ' ISNULL(c.Suburb, '''') AS [StreetSuburb], '
		SET @sql = @sql + ' ISNULL(c.City, '''') AS [StreetCity], '
		SET @sql = @sql + ' ISNULL(c.Street_Post_Code, '''') AS [StreetPostCode], '
	END

	IF @AW_YesNo_Delivery_Address = 1
	BEGIN
		SET @sql = @sql + '''' + @Delivery_Address + '''' + ' AS [DeliverAddress], '      
		SET @sql = @sql + '''' + @Delivery_Suburb + '''' + ' AS [DeliverSuburb], '
		SET @sql = @sql + '''' + @Delivery_City + '''' + ' AS [DeliverCity], '
		SET @sql = @sql + '''' + @Delivery_Post_Code + '''' + ' AS [DeliverPostCode], '
	END
	ELSE
	BEGIN
		SET @sql = @sql + ' ISNULL(c.Delivery_Address, '''') AS [DeliverAddress], '
		SET @sql = @sql + ' ISNULL(c.Delivery_Suburb, '''') AS [DeliverSuburb], '
		SET @sql = @sql + ' ISNULL(c.Delivery_City, '''') AS [DeliverCity], '
		SET @sql = @sql + ' ISNULL(c.Delivery_Post_Code, '''') AS [DeliverPostCode], '
	END

	SET @sql = @sql + ' CONVERT(VARCHAR(12), c.AC_Customers_ID) AS [CustomerID], '
	SET @sql = @sql + ' ISNULL(c.Customer_Number, '''') + ''('' + CONVERT(VARCHAR(12), c.AC_Customers_ID) + '')'' AS [CustomerNo], '

    SET @sql = @sql + ' CASE WHEN RTRIM(LTRIM(c.Old_Customer_Number)) <> '''' '
    SET @sql = @sql + ' THEN ''Merchant No: '' + RTRIM(LTRIM(c.Old_Customer_Number)) '
    SET @sql = @sql + ' ELSE '''' '
    SET @sql = @sql + ' END AS [MerchantNo], '

    SET @sql = @sql + ' t.Sys_AW_Transaction_Types_ID AS [TranTypeID], '
    SET @sql = @sql + ' tt.[Description] AS [TransactionType], '
    SET @sql = @sql + ' comp.Tax_Number AS [CompanyTaxNumber], '
    SET @sql = @sql + ' comp.E_Mail AS [CompanyEmail], '
    SET @sql = @sql + ' comp.Company_Name AS [CompanyName], '
--    SET @sql = @sql + ' CASE WHEN @WhichName = 1 '
--    SET @sql = @sql + ' THEN comp.Company_Name + '' / '' + IsNull(comp.Company_Trading_Name,'''')'
--    SET @sql = @sql + ' ELSE comp.Company_Name '
--    SET @sql = @sql + ' END AS [CompanyName], '
    
    SET @sql = @sql + ' comp.Company_Trading_Name AS [TradingName], '
    SET @sql = @sql + ' comp.Company_Addr1 AS [CompanyAddress1], '
    SET @sql = @sql + ' comp.Company_Addr2 AS [CompanyAddress2], '
    SET @sql = @sql + ' comp.Company_City AS [CompanyCity], '
    SET @sql = @sql + ' comp.Company_Post_Code AS [CompanyPostCode], '
    SET @sql = @sql + ' comp.Company_Registration_Number AS [CompanyRegNo], '
    SET @sql = @sql + ' comp.Tel_No AS [CompanyTelNo], '
    SET @sql = @sql + ' comp.Fax_No AS [CompanyFaxNo], '
    SET @sql = @sql + ' rep.[Description] AS [RepName], '
    SET @sql = @sql + ' t.AS_Transactions_ID AS [TransactionID], '
    SET @sql = @sql + ' t.Transaction_Number AS [TransactionNo], '
    SET @sql = @sql + ' CONVERT(varchar(12), t.Transaction_Date, 103) AS [TransactionDate], '
    SET @sql = @sql + ' t.Customer_Reference AS [TransactionCustomerRef], '
    SET @sql = @sql + ' t.Amount AS [TransactionAmount], '
    SET @sql = @sql + ' t.Total_Amount AS [TransactionTotalAmount], '
    SET @sql = @sql + ' t.Total_Discount_Amount AS [TransactionTotalDiscount], '
    SET @sql = @sql + ' t.Total_Tax_Amount AS [TransactionTotalTax], '
    SET @sql = @sql + ' com.Comment AS [TransactionComment], '
-------------------------------------------------------------------------------
    SET @sql = @sql + ' p.Product_Code AS [ProductCode], '

--    SET @sql = @sql + ' p.Description AS [ProductDescription], '
    --RL 2014-01-28 Vs 6.0 Use print discription if there is a value instead of Description
    SET @sql = @sql + ' CASE WHEN LEN(ISNULL(Print_Description,'''')) > 0 '
    SET @sql = @sql + ' THEN p.Print_Description '
    SET @sql = @sql + ' ELSE p.Description '
    SET @sql = @sql + ' END AS [ProductDescription], '
    
    
    SET @sql = @sql + ' td.Quantity AS [DetailQty], '
    SET @sql = @sql + ' td.Unit_Price AS [DetailUnitPrice], '

    SET @sql = @sql + ' CASE WHEN (td.Unit_Price * td.Quantity) <> 0 '
    SET @sql = @sql + ' THEN CONVERT(money,ABS(ROUND((((td.Discount_Amount) / (td.Unit_Price * td.Quantity)) * 100), 2))) '
    SET @sql = @sql + ' ELSE 0.00 '
    SET @sql = @sql + ' END AS [DetailDiscPerc], '

    SET @sql = @sql + ' td.Discount_Amount AS [DetailDiscount] , '
    SET @sql = @sql + ' (td.Unit_Price * td.Quantity) + td.Discount_Amount AS [DetailAmount], '
    SET @sql = @sql + ' td.Tax_Amount AS [DetailTaxAmount], '
    SET @sql = @sql + ' td.Extended_Amount AS [DetailExtendedAmount], '
    SET @sql = @sql + ' CONVERT(varchar(4), DATEPART(hour, t.Transaction_Date)) + '':'' + '
    SET @sql = @sql + ' CONVERT(varchar(4), DATEPART(minute, t.Transaction_Date)) + '':'' + '
    SET @sql = @sql + ' CONVERT(varchar(4), DATEPART(second, t.Transaction_Date)) AS [TransactionTime], '
    SET @sql = @sql + ' u.UserName AS [UserCode], '
    SET @sql = @sql + ' t.Comment AS [Comment], '
    SET @sql = @sql + ' ISNULL(RTRIM(LTRIM(c.Work_Tel_No)), '''') + '
    SET @sql = @sql + ' ISNULL('' / '' + RTRIM(LTRIM(c.Cell_No)), '''') + '
    SET @sql = @sql + ' ISNULL('' / '' + RTRIM(LTRIM(c.Home_Tel_No)), '''') AS [TelNos], '
	
	--> TAX Number
    --SET @sql = @sql + ' ISNULL(RTRIM(LTRIM(c.Tax_Number)), '''') AS [VATNo], '
	IF @AW_YesNo_Invoice = 1
	BEGIN
		SET @sql = @sql + '''' + @Tax_Number + '''' + ' AS [VATNo], '      
	END
	ELSE
	BEGIN
		SET @sql = @sql + ' ISNULL(RTRIM(LTRIM(c.Tax_Number)), '''') AS [VATNo], '
	END

    SET @sql = @sql + ' CASE WHEN RTRIM(LTRIM(ts.Transaction_Numbers)) <> '''' '
    SET @sql = @sql + ' THEN ''Sales Order/Job No: '' + RTRIM(LTRIM(ts.Transaction_Numbers)) '
    SET @sql = @sql + ' ELSE '''' '
    SET @sql = @sql + ' END AS [JobSource], '

    SET @sql = @sql + ' t.AW_User_Companies_ID AS [CompanyID], '
    SET @sql = @sql + ' ROUND(ISNULL(td.Quantity, 0) * ISNULL(p.Pack_Mass, 0), 2) AS [PackMass], '
    SET @sql = @sql + ' @PaymentMethod AS [PayMethod], '

    SET @sql = @sql + ' CASE WHEN td.AS_Job_References_ID = 0 '
    SET @sql = @sql + ' THEN NULL '
    SET @sql = @sql + ' ELSE td.AS_Job_References_ID '
    SET @sql = @sql + ' END AS [JobRefNo], '

    SET @sql = @sql +  '''' + @Message + '''' + ' AS [TextMessage], '
    SET @sql = @sql + ' @WhichAddress AS [AddressType], '
    SET @sql = @sql + ' td.Serial_No AS [SerialNo], '
    SET @sql = @sql + ' td.Make AS [Make], '
    SET @sql = @sql + ' td.Customer AS [Customer], '
    SET @sql = @sql + ' @WhichName AS [NameType], '
    SET @sql = @sql + ' ISNULL(RTRIM(LTRIM(c.Orders_URL)), '''') + '
    SET @sql = @sql + ' ISNULL(''; '' + RTRIM(LTRIM(c.Home_Email)), '''') + '
    SET @sql = @sql + ' ISNULL(''; '' + RTRIM(LTRIM(c.Home_Email)), '''') AS [Emails], '
    SET @sql = @sql + ' td.TDHeader AS [TDHeader], '
    SET @sql = @sql + ' td.TDDetail AS [TDDetail] '

--	FROM vw_AS_Transactions t 
    SET @sql = @sql + ' FROM AS_Transactions t '
    SET @sql = @sql + ' LEFT JOIN AC_Customers c '
    SET @sql = @sql + ' ON t.AC_Customers_ID = c.AC_Customers_ID '
    SET @sql = @sql + ' LEFT JOIN Sys_AW_Transaction_Types tt '
    SET @sql = @sql + ' ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID '
    SET @sql = @sql + ' LEFT JOIN AW_User_Companies comp '
    SET @sql = @sql + ' ON t.AW_User_Companies_ID = comp.AW_User_Companies_ID '
    SET @sql = @sql + ' LEFT JOIN Lup_AS_Reps rep '
    SET @sql = @sql + ' ON t.Lup_AS_Reps_ID = rep.Lup_AS_Reps_ID '
    SET @sql = @sql + ' LEFT JOIN AS_Transaction_Details td '
    SET @sql = @sql + ' ON t.AS_Transactions_ID = td.AS_Transactions_ID '
    SET @sql = @sql + ' LEFT JOIN AP_Products p '
    SET @sql = @sql + ' ON td.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + ' LEFT JOIN AW_Users u '
    SET @sql = @sql + ' ON t.[User_ID] = u.AW_Users_ID '
    SET @sql = @sql + ' LEFT JOIN AS_Transaction_Sources ts '
    SET @sql = @sql + ' ON t.AS_Transactions_ID = ts.AS_Transactions_ID '
    SET @sql = @sql + ' LEFT JOIN AW_Comments com '
    SET @sql = @sql + ' ON t.AW_Comments_ID = com.AW_Comments_ID '
    SET @sql = @sql + ' WHERE t.AS_Transactions_ID = ' + CONVERT(varchar(20), @TransactionID)

    IF @SortOrder = 1
        BEGIN
            IF @OrderFilter = 0        --Product Description
                BEGIN
                    SET @sql = @sql + ' ORDER BY p.Description '
                END
            ELSE
            IF @OrderFilter = 1        --Product Code
                BEGIN
                    SET @sql = @sql + ' ORDER BY p.Product_Code '
                END
            ELSE
            IF @OrderFilter = 2        --Product Type
                BEGIN
                    SET @sql = @sql + ' ORDER BY p.Lup_AP_Product_Types_ID, p.Description '
                END
            ELSE
            IF @OrderFilter = 3        --Product Group
                BEGIN
                    SET @sql = @sql + ' ORDER BY p.Lup_AP_Product_Groups_ID, p.Description '
                END
            ELSE
            IF @OrderFilter = 4        --Product Department
                BEGIN
                    SET @sql = @sql + ' ORDER BY p.Lup_AP_Product_Departments_ID, p.Description '
                END
            ELSE
            IF @OrderFilter = 5        --Product Location
                BEGIN
                    SET @sql = @sql + ' ORDER BY p.Lup_AP_Product_Locations_ID, p.Description '
                END
            ELSE
            IF @OrderFilter = 6        --Product Purchase Category
                BEGIN
                    SET @sql = @sql + ' ORDER BY p.Lup_AP_Purchase_Categories_ID, p.Description '
                END
            ELSE
            IF @OrderFilter = 7        --Product Manufacturer
                BEGIN
                    SET @sql = @sql + ' ORDER BY p.Lup_AP_Product_Manufacturers_ID, p.Description '
                END
        END
    ELSE                    --Default
        BEGIN
            SET @sql = @sql + ' ORDER BY AS_Transaction_Details_ID '
        END

EXEC (@sql)
--Select @sql

SET NOCOUNT OFF
GO

--3 sp_RPT_AB_Income_Statement
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_RPT_AB_Income_Statement]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_RPT_AB_Income_Statement]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_RPT_AB_Income_Statement
--Purpose       :GAAP Income Statement Report
--Parameters    :
--Date          :2002/12/01
--Authors       :TB
--Version       :1.0.0
--MODS:         :31/12/02 - Modified to SUM from any given Accounting Period
--              :           with NEW fn_AB_Get_Ending_GL_Period
--              :06/03/03 - Show YTD TOTALS based on SPAN of CURRENT FISCAL YEAR
--              :           FROM @StartMonthID and @StartYearID inclusive
--              :           TO @CurrentYearID and @CurrentYearID inclusive
--              :19/03/03 - Added ORDER BY AB_Accounts.Description to display
--              :           all report category accounts
--              :03/08/03 - Added Cost Center filtering
--              :14/04/05 - Added @IgnoreYEJnl input parameter that now displays
--              :           monthly account totals reflecting ACTUAL movement
--2004.2.7      :06/04/06 - Added @IgnoreZeroTrans and @IgnoreZeroBalance options
--2004.2.8      :10/04/08 - Increased @sql to 8000
--RL	V6.0	:2013-12-09 - Exclude year end GL's on balance and transaction checks
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_RPT_AB_Income_Statement]
    (
        @CompanyID int,
        @CurrentMonthID int,
        @CurrentYearID int,
        @CurrentMonth varchar(20),
        @PriorMonth1ID int,
        @PriorYear1ID int,
        @PriorMonth1 varchar(20),
        @PriorMonth2ID int,
        @PriorYear2ID int,
        @PriorMonth2 varchar(20),
        @CostCenterID int,
        @IgnoreYEJnl tinyint,
        @IgnoreZeroTrans tinyint,
        @IgnoreZeroBalance tinyint
    )
AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000),
            @EndPeriod varchar(6),
            @YearEndMonthID int,
            @StartMonthID int,
            @StartYearID int,
            @StartPeriod varchar(6)


--NEW 06/03/03----------------------------------
    EXEC sp_AB_Get_Fiscal_Span
                        @CompanyID,
                        @YearEndMonthID OUTPUT,
                        @StartMonthID OUTPUT,
                        @StartYearID OUTPUT,
                        @CurrentMonthID OUTPUT,
                        @CurrentYearID OUTPUT

    SET @StartPeriod = dbo.fn_AB_Get_Ending_GL_Period(@StartMonthID, @StartYearID)
------------------------------------------------


    SET @EndPeriod = dbo.fn_AB_Get_Ending_GL_Period(@CurrentMonthID, @CurrentYearID)


    SET @sql = ' SELECT '

    SET @sql = @sql + ' ISNULL(c.[Description], '''') AS [Level1], '
    SET @sql = @sql + ' ISNULL(d.[Description], '''') AS [Level2], '
    SET @sql = @sql + ' ISNULL(e.[Description], '''') AS [Level3], '
    SET @sql = @sql + ' ISNULL(f.[Description], '''') AS [Level4], '
    SET @sql = @sql + ' ISNULL(a.[Description], '''') AS [Account], '


    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0) '
    SET @sql = @sql + '     FROM AB_GL_Transactions t '
    SET @sql = @sql + '     WHERE t.AB_Accounts_ID = a.AB_Accounts_ID AND '
    SET @sql = @sql + '           t.Slu_AW_Months_ID = ' + CONVERT(varchar(10), @PriorMonth2ID) + ' AND '
    SET @sql = @sql + '           t.Slu_AW_Years_ID = ' + CONVERT(varchar(10), @PriorYear2ID)
--> IGNORE the INCOME & EXPENSE CLOSING JNL
    IF @IgnoreYEJnl = 1
        BEGIN
            SET @sql = @sql + '       AND t.Sys_AB_Transaction_Types_ID <> 16'
        END
    SET @sql = @sql + ' ) AS [Prior2], '


    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0) '
    SET @sql = @sql + '     FROM AB_GL_Transactions t '
    SET @sql = @sql + '     WHERE t.AB_Accounts_ID = a.AB_Accounts_ID AND '
    SET @sql = @sql + '           t.Slu_AW_Months_ID = ' + CONVERT(varchar(10), @PriorMonth1ID) + ' AND '
    SET @sql = @sql + '           t.Slu_AW_Years_ID = ' + CONVERT(varchar(10), @PriorYear1ID)
--> IGNORE the INCOME & EXPENSE CLOSING JNL
    IF @IgnoreYEJnl = 1
        BEGIN
            SET @sql = @sql + '       AND t.Sys_AB_Transaction_Types_ID <> 16'
        END
    SET @sql = @sql + ' ) AS [Prior1], '


    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0) '
    SET @sql = @sql + '     FROM AB_GL_Transactions t '
    SET @sql = @sql + '     WHERE t.AB_Accounts_ID = a.AB_Accounts_ID AND '
    SET @sql = @sql + '           t.Slu_AW_Months_ID = ' + CONVERT(varchar(10), @CurrentMonthID) + ' AND '
    SET @sql = @sql + '           t.Slu_AW_Years_ID = ' + CONVERT(varchar(10), @CurrentYearID)
--> IGNORE the INCOME & EXPENSE CLOSING JNL
    IF @IgnoreYEJnl = 1
        BEGIN
            SET @sql = @sql + '       AND t.Sys_AB_Transaction_Types_ID <> 16'
        END
    SET @sql = @sql + ' ) AS  [Current], '


    SET @sql = @sql + ' ( '
    SET @sql = @sql + '     SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0) '
    SET @sql = @sql + '     FROM AB_GL_Transactions t '
    SET @sql = @sql + '     WHERE t.AB_Accounts_ID = a.AB_Accounts_ID '
    SET @sql = @sql + '       AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) >= ' + '''' + @StartPeriod + ''''
    SET @sql = @sql + '       AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
--> IGNORE the INCOME & EXPENSE CLOSING JNL
    IF @IgnoreYEJnl = 1
        BEGIN
            SET @sql = @sql + '       AND t.Sys_AB_Transaction_Types_ID <> 16'
        END
    SET @sql = @sql + ' ) AS [Balance] '


    SET @sql = @sql + ' FROM AB_Accounts a '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_Account_Categories b '
    SET @sql = @sql + '         ON a.Sys_AB_Account_Categories_ID = b.Sys_AB_Account_Categories_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_I1 c '
    SET @sql = @sql + '         ON b.Sys_AB_I1_ID = c.Sys_AB_I1_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_I2 d '
    SET @sql = @sql + '         ON b.Sys_AB_I2_ID = d.Sys_AB_I2_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_I3 e '
    SET @sql = @sql + '         ON b.Sys_AB_I3_ID = e.Sys_AB_I3_ID '
    SET @sql = @sql + '     LEFT JOIN Sys_AB_I4 f '
    SET @sql = @sql + '         ON b.Sys_AB_I4_ID = f.Sys_AB_I4_ID '

    SET @sql = @sql + ' WHERE a.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND '
    SET @sql = @sql + '       b.Sys_AB_I4_ID <> 0 '    --Only Income Statement accounts


    IF @CostCenterID > 0
        BEGIN
            SET @sql = @sql + '   AND a.Lup_AB_Cost_Centers_ID = '  + CONVERT(varchar(10), @CostCenterID) + ' '
        END

    IF @IgnoreZeroTrans = 1
        BEGIN
            SET @sql = @sql + ' AND ( '
            SET @sql = @sql + '     SELECT COUNT(*) '
            SET @sql = @sql + '     FROM AB_GL_Transactions t '
            SET @sql = @sql + '     WHERE '
            SET @sql = @sql + '         ( '
            SET @sql = @sql + '          t.AB_Accounts_ID = a.AB_Accounts_ID '
            --SET @sql = @sql + '          AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
            --Needs to be same period as the rest of the report
		    SET @sql = @sql + '       AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) >= ' + '''' + @StartPeriod + ''''
			SET @sql = @sql + '       AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
            
            SET @sql = @sql + '         ) '
		    
		    --> IGNORE the INCOME & EXPENSE CLOSING JNL - RL 2013-12-09
			IF @IgnoreYEJnl = 1
				BEGIN
					SET @sql = @sql + '       AND t.Sys_AB_Transaction_Types_ID <> 16'
				END
            
            SET @sql = @sql + ' ) <> 0 '
        END


    IF @IgnoreZeroBalance = 1
        BEGIN
            SET @sql = @sql + ' AND ( '
            SET @sql = @sql + '     SELECT ISNULL(SUM(t.AB_Transaction_Amount), 0) '
            SET @sql = @sql + '     FROM AB_GL_Transactions t '
            SET @sql = @sql + '     WHERE '
            SET @sql = @sql + '         ( '
            SET @sql = @sql + '          t.AB_Accounts_ID = a.AB_Accounts_ID '
            --SET @sql = @sql + '          AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
            --Needs to be same period as the rest of the report            
		    SET @sql = @sql + '       AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) >= ' + '''' + @StartPeriod + ''''
			SET @sql = @sql + '       AND dbo.fn_AB_Get_Ending_GL_Period(t.Slu_AW_Months_ID, t.Slu_AW_Years_ID) <= ' + '''' + @EndPeriod + ''''
            
            SET @sql = @sql + '         ) '
		    
		    --> IGNORE the INCOME & EXPENSE CLOSING JNL - RL 2013-12-09
			IF @IgnoreYEJnl = 1
				BEGIN
					SET @sql = @sql + '       AND t.Sys_AB_Transaction_Types_ID <> 16'
				END
            
           SET @sql = @sql + ' ) <> 0 '

        END

    SET @sql = @sql + ' ORDER BY b.Sys_AB_I1_ID, '
    SET @sql = @sql + '          b.Sys_AB_I2_ID, '
    SET @sql = @sql + '          b.Sys_AB_I3_ID, '
    SET @sql = @sql + '          b.Sys_AB_I4_ID, '
--------------------------------------------------------------
--19/03/03 - Added ORDER BY AB_Accounts.Description to display
--           all report category accounts 
    SET @sql = @sql + '          a.Description   '
--------------------------------------------------------------
--Select @EndPeriod

EXEC (@sql)


SET NOCOUNT OFF
GO

--4 sp_AP_Update_Inventory_Details
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Update_Inventory_Details]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Update_Inventory_Details]
GO
--> NEW 05/06/03: Calculate AVERAGE COST

--------------------------------------------------------------------------------
--Description   :sp_AP_Product_Inventory_Details
--Purpose       :Updates Product Last_Cost, On_Hand & Reserved for ONE product in GRV
--   			:Also inserts GL Inventory Adjustments for Reval/Deval
--   			:    NB: Any mods must sync with sp_AP_Update_Adjusted_Inventory_Details
--              :    that is used for Stock Adjustments
--Functionality :Handles Stock Adjustment Types 2, 4, 5
--Date          :2002/02/13
--Authors       :TB
--Version       :1.0.0
--Mods          :21/05/02 - Declared ALL decimals size (9,3)
--              :21/05/02 - Moved the Reval/Deval Adjustment here from
--              :           sp_AO_Insert_OR_Update_GRV_Detail
--              :04/06/02 - Added text to @Note for normal Stock Adjustments
--              :                and ensured that AP_Inventory_Adjustments is
--              :                for new LastCost AND OnHand adjustments
--              :31/05/03 - Renamed @Unit_Price to @Unit_Last_Cost for clarity
--              :05/06/03 - Added calculate and update AVERAGE COST in AP_Products
--              :05/06/03 - Added COST-OF-SALES / INVENTORY GL adjustments
--              :           GL Journal and GL Transaction for INVENTORY CONTROL
--              :           entries if @COS_Adjust <> 0
--              :06/08/03 - Modified C.O.S. Adjustment GL Transaction Type
--              :           from 22 (Accounts Receivable - Journal)
--              :           to 15 (General Journal - Normal)
--              :04/09/03 - Added to GL Post Purchases/Sales to Inventory/C.O.S.
--              :           ONLY IF chkGRVtoInventoryCOS parameter is vbChecked
--              :17/10/03 - Added NEW @AB_Transaction_Date and @AB_Source_Ref
--              :           parameters passed to sp_AB_Insert_GL_Transactions
--              :18/10/03 - Added @GRV_ID input parameter to get the GRV
--              :           Delivery_Note_Number as GLTran RefNo
--              :08/01/04 - Added Inventory Adjustment Type field Sys_AP_Adjustment_Types_ID
--              :26/05/05 - Added match the Accounting Period of the CALENDAR DAY
--              : ********  FIX the above LATER to match the Accounting Period of the GRV
--2004.3.2      :04/10/06 - Removed comments appended to parameters passed to a SP.
--              :           THIS BUG CAUSES PROCEDURES TO NOT EXECUTE !!!!!!!!!!!!!
--2004.4.0      :08/08/08 - Removed setting @New_Average_Cost = 0 if On_Hand now 0
--              :           in NEW 30/05/08 - 2004.3.8 - Calculate AVERAGE COST
--2004.4.4      :27/04/09 - Replaced GL Post from Control_Number = 106 (Cost Of Sales Control)
--              :           to Control_Number = 107 (Inventory Adjustments Control)
--2004.4.5      :16/07/09 - Removed check 'IF @NextGLTranID = 0' when creating NORMAL JOURNAL header
--              :           for the C.O.S. Adjustment if item was sold when it was in NEGATIVE On-Hand
--              :15/07/09 - Added new @ProductRef to append Product Code and ID to GL references
--2004.5.1      :04/05/11 - Cleaned up comments
--2004.5.2      :06/07/11 - Removed writing an Adjustment if On_Hand is changed
--              :           CANNOT find a reason WHY an Adjustment is required
--V6.0	RL	2014-05-13	:Added changes to AP_Inventory_Adjustments if last cost changed
--V6.0	RL	2014-05-13	:Inventory Adjustment is always done useing Last Cost??????????????????????????????????????????
--						 Should it not be done depending on the system option setup of Average Cost, Last Cost or Standard Cost
--------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Update_Inventory_Details]
    (
        @GRV_ID int,
    	@ProductID int,
    	@New_Last_Cost money,
    	@New_On_Hand decimal(9,3),
    	@New_Job_Reserved decimal(9,3),
    	@New_Sales_Order_Reserved decimal(9,3),
    	@New_Quote_Reserved decimal(9,3),
    	@Note varchar(70),
    	@UserID int,
    	@CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @Prev_Last_Cost money,
            @Prev_Average_Cost money,
        	@Prev_On_Hand decimal(9,3),
            @Prev_Average_On_Hand_Value money,
        	@Prev_Job_Reserved decimal(9,3),
        	@Prev_Sales_Order_Reserved Decimal(9,3),
        	@Prev_Quote_Reserved decimal(9,3),
            @New_Average_Cost money,
            @New_Average_On_Hand_Value money,
            @Qty decimal(9,3),
            @COS_Adjust money,
    		@User_Name varchar(40),
            @AdjustmentsID int,
            @ProductDesc varchar(50),
            @ProdCode varchar(20),
            @NextGLTranID int,
            @JNLHeaderID int,
            @Narration varchar(50),
    		@Month tinyint,
    		@Year int,
    		@YearID int,
            @GLControlAccount int,
            @InsertGLTran bit,
            @GLTranDate datetime,
            @GRInventoryCOS varchar(10),
            @RefNo varchar(20),
            @AdjustmentType tinyint,
            @ProductRef varchar(30)


    SET @AdjustmentType = 5    --Intialize as 'Goods Received' type


    BEGIN
    	SELECT @ProductDesc = ISNULL([Description], ''),
               @ProdCode = ISNULL(Product_Code, ''),
               @Prev_Last_Cost = ISNULL(Last_Cost, 0),
    		   @Prev_On_Hand = ISNULL(On_Hand, 0),
    		   @Prev_Job_Reserved = ISNULL(Job_Reserved, 0),
    		   @Prev_Sales_Order_Reserved = ISNULL(Sales_Order_Reserved, 0),
        	   @Prev_Quote_Reserved = ISNULL(Quote_Reserved, 0),
               @Prev_Average_Cost = ISNULL(Average_Cost, 0)
    	FROM AP_Products
    	WHERE AP_Products_ID = @ProductID


        SET @ProductRef = @ProdCode + '(' + CONVERT(varchar(10), @ProductID) + ')'


        SET @Qty = @New_On_Hand - @Prev_On_Hand
        SET @COS_Adjust = 0
        SET @InsertGLTran = 0          --0 = Do Not insert a GL Transaction in JNL Details

		--RL V6.0 Fixed According To Notes Above 26/05/05. Agree. GL Transaction date should be the
		--date the products were received and not the date it was captured.
		SELECT @GLTranDate = Date_Received
		FROM AO_GRV
		WHERE AO_GRV_ID = @GRV_ID

        ------------------------------------------------------------------------
        --> Calculate AVERAGE COST
        ------------------------------------------------------------------------
        --> Initialise Average_Cost
        IF @Prev_Average_Cost = 0
            BEGIN
                SET @Prev_Average_Cost = @New_Last_Cost
            END


        --> If On Hand NEGATIVE then do a Cost Adjustment 
        IF @Prev_On_Hand < 0            -- On_Hand was negative
            BEGIN
                IF @New_On_Hand <= 0    -- On_Hand still negative
                    BEGIN
                        SET @COS_Adjust = ROUND((@New_Last_Cost - @Prev_Average_Cost) * @Qty, 2)
                        SET @New_Average_Cost = @Prev_Average_Cost    -- Don't change Average Cost
                    END
                ELSE                    -- On_Hand comes out of negative
                    BEGIN
                        SET @COS_Adjust = ROUND((@New_Last_Cost - @Prev_Average_Cost) * ABS(@Prev_On_Hand), 2)
                        SET @New_Average_Cost = @New_Last_Cost
                    END
            END
        ELSE                            -- On_Hand was positive
            BEGIN
                IF @New_On_Hand <> 0    -- Create a NEW Average Cost
                    BEGIN
                        SET @New_Average_Cost = ROUND(((@Prev_On_Hand * @Prev_Average_Cost) +
                                                       (@Qty * @New_Last_Cost)) / @New_On_Hand, 2)
                    END
            END
        ------------------------------------------------------------------------

    	UPDATE AP_Products
        SET Last_Cost = @New_Last_Cost,
            Average_Cost = @New_Average_Cost,
            On_Hand = @New_On_Hand,
            Job_Reserved = @New_Job_Reserved,
            Sales_Order_Reserved = @New_Sales_Order_Reserved,
            Quote_Reserved = @New_Quote_Reserved,
            [User_ID] = @UserID
    	WHERE AP_Products_ID = @ProductID


        --> CONTINUOUS INVENTORY ONLY - INSERT a GL COST-OF-SALES adjustment
        --                if item was sold when it was in NEGATIVE On-Hand
        IF @COS_Adjust <> 0
            BEGIN

                --> Get CONTINUOUS INVENTORY parameter setting
                SELECT @GRInventoryCOS = Control_Value
                FROM Sys_AW_Options
                WHERE Control_Type = 'CheckBox' AND
                      Control_Name = 'chkGRVtoInventoryCOS' AND
                      Control_Index = 0 AND
                      AW_User_Companies_ID = @CompanyID


                IF RTRIM(LTRIM(@GRInventoryCOS)) = '1'    --1 = vbChecked (Yes)
                    BEGIN

						--RL V6.0 Fixed According To Notes Above 26/05/05. Agree. GL Transaction date should be the
						--date the products were received and not the date it was captured.
                        --> The above should match the Accounting Period of the GRV !!
                        --SET @Month = DATEPART(mm, getdate())
                        --SET @Year = DATEPART(yy, getdate())
                        SET @Month = DATEPART(mm, @GLTranDate)
                        SET @Year = DATEPART(yy, @GLTranDate)

                        SELECT @YearID = Slu_AW_Years_ID
                        FROM Slu_AW_Years
                        WHERE [Description] = CONVERT(varchar(10), @Year)

                        IF @Month = 0 OR @YearID = 0
                            BEGIN
                                SELECT @Month = Slu_AW_Months_ID,
                                       @YearID = Slu_AW_Years_ID
                                FROM AW_User_Companies
                                WHERE AW_User_Companies_ID = @CompanyID
                            END

                        SET @RefNo = 'GRV ' + CONVERT(varchar(10), @GRV_ID)
                        SET @RefNo = LEFT(@RefNo, 20)

                        SET @Narration = LEFT('GRV C.O.S. Reval/Deval for ' + @ProductRef, 200)
        
                        --> Create NORMAL JOURNAL header for the C.O.S. Adjustment
         				EXEC @NextGLTranID = sp_AB_Next_Transaction_Number
                                15,
                                @CompanyID

                        SET @GLTranDate = getdate()

        				EXEC @JNLHeaderID = sp_AB_Insert_Journal_Header
                                @GLTranDate,
                                @NextGLTranID,
                                @Narration,
                                @Month,
                                @YearID,
                                @UserID,
                                @CompanyID

                        --> Update INVENTORY ADJUSTMENTS CONTROL
        				SELECT @GLControlAccount = AB_Accounts_ID
                        FROM AB_Control_Accounts
                        WHERE Control_Number = 107    --Inventory Adjustments Control
        
                        --> Create JOURNAL DETAIL for Cost Of Sales
                        EXEC sp_AB_Insert_Journal_Detail
                                @JNLHeaderID,
                                @GLControlAccount,
                                @COS_Adjust,
                                @Narration,
                                @UserID,
                                @CompanyID,
                                @InsertGLTran
        
                        --> Create GL TRANSACTION for Cost Of Sales
                        EXEC sp_AB_Insert_GL_Transactions
                                @Narration,
                                15,
                                @GLControlAccount,
                                @GLTranDate,
                                @RefNo,
                                @Month,
                                @YearID,
                                @NextGLTranID,
                                @COS_Adjust,
                                @UserID,
                                @CompanyID
        
                        --> Reverse signs to balance double entry
                        SET @COS_Adjust = @COS_Adjust * -1
        
                        --> Update INVENTORY CONTROL
                        SELECT @GLControlAccount = AB_Accounts_ID
                        FROM AB_Control_Accounts
                        WHERE Control_Number = 601    --Inventory
        
                        --> Create JOURNAL DETAIL for Inventory
                        EXEC sp_AB_Insert_Journal_Detail
                                @JNLHeaderID,
                                @GLControlAccount,
                                @COS_Adjust,
                                @Narration,
                                @UserID,
                                @CompanyID,
                                @InsertGLTran
        
                        --> Create GL TRANSACTION for Inventory
                        EXEC sp_AB_Insert_GL_Transactions
                                @Narration,
                                15,
                                @GLControlAccount,
                                @GLTranDate,
                                @RefNo,
                                @Month,
                                @YearID,
                                @NextGLTranID,
                                @COS_Adjust,
                                @UserID,
                                @CompanyID

                    END
            END


        --> Moved here from sp_AO_Insert_OR_Update_GRV_Detail - Commented 2004.5.2
-- 		IF @Prev_Last_Cost <> @New_Last_Cost OR
--            @Prev_On_Hand <> @New_On_Hand

        -- NEW 2004.5.2 - CANNOT find a reason WHY an Adjustment is required if On_Hand is changed
		IF @Prev_Last_Cost <> @New_Last_Cost


			BEGIN

                --> Assign the Adjustment Type
                IF @Prev_Last_Cost <> @New_Last_Cost
                    BEGIN
                        SET @AdjustmentType = 5    --GRV Reval/Deval
                    END
                ELSE
					--RL V6.0 It will never go in here!!!!!
                    BEGIN
                        SET @AdjustmentType = 4    --GRV Adjustment
                    END


				SELECT @User_Name = ISNULL(FirstName, '')
				FROM AW_Users
				WHERE AW_Users_ID = @UserID


                IF LTRIM(RTRIM(@Note)) = ''
                    BEGIN
                        IF @Prev_Last_Cost <> @New_Last_Cost
                            SET @Note = 'Goods Received Reval/Deval by '
                        ELSE
                            SET @Note = 'Goods Received Adjustment by '
                    END
                ELSE
                IF @Note = 'Goods Received by '    --set in sp_AO_Insert_OR_Update_GRV_Detail
                    BEGIN
                        SET @AdjustmentType = 2    --Goods Received
                    END


				SET @Note = LEFT(@Note + @User_Name + ' ' + @ProductRef, 70) 


                --> Stock Reval/Deval Adjustment for Last_Cost changes
            	INSERT INTO AP_Inventory_Adjustments
                    (
            			AP_Products_ID,
                        Sys_AP_Adjustment_Types_ID,
            			Previous_Last_Cost,
                        Previous_Average_Cost,
            			Previous_On_Hand,
            			Previous_Job_Reserved,
            			Previous_Sales_Order_Reserved,
            			Previous_Quote_Reserved,
            			New_Last_Cost,
                        New_Average_Cost,
            			New_On_Hand,
            			New_Job_Reserved,
            			New_Sales_Order_Reserved,
            			New_Quote_Reserved,
            			Note,
            			Date_Captured,
            			[User_ID],
            			AW_User_Companies_ID
                    )
            	VALUES
                    (
                        @ProductID,
                        @AdjustmentType,
            			@Prev_Last_Cost,
                        @Prev_Average_Cost,
            			@Prev_On_Hand ,
            		    @Prev_Job_Reserved,
            			@Prev_Sales_Order_Reserved,
            		    @Prev_Quote_Reserved,
            			@New_Last_Cost,
                        @New_Average_Cost,
            			@New_On_Hand,
            			@New_Job_Reserved ,
            			@New_Sales_Order_Reserved,
            			@New_Quote_Reserved,
            			@Note,
            			getdate(),
            			@UserID,
            			@CompanyID
                    )

            	SELECT @AdjustmentsID = SCOPE_IDENTITY() 
            
            	RETURN @AdjustmentsID

            END
    END 			


SET NOCOUNT OFF
GO

--5 sp_AS_CSales_Submission_INS
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_CSales_Submission_INS]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_CSales_Submission_INS]
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_CSales_Submission_INS
--Purpose       :Get Sales Submission Data For Insurance
--Parameters    :
--Date          :2014-09-23
--Authors       :RL
--Version       :6.1
--MODS          :
--RL	V6_1	2015-02-17	:Use froam and to Day End dates sent through
--							:Added Inclusion and Exclusion Checks
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_CSales_Submission_INS]
(
        @ExclusionsFilter	varchar(8000),
        @InclusionFilter	varchar(8000),
        @StartDayEndDate	datetime,
        @EndDayEndDate		datetime,
		@CompanyID			int
)
AS

SET NOCOUNT ON

	Declare @CompanyNo			Int,
			@LastDayEnd			DateTime,
			@WhichName			Tinyint,
			@Loop_Ind			Int,
			@ptrval				binary(16),
			@OffSet				Int,
			
			@AS_Transactions_ID	Int,
			@Transaction_Number	Varchar(20),
			@Transaction_Date	Datetime,
			@Customer_Reference	Varchar(15), --Reg No
			@Comment			Varchar(20), --Make
			
			@Quantity			Decimal(9,3),
			@Extended_Amount	Decimal(18,3),
			@Product_Description	Varchar(50),
			@Product_Code		Varchar(20),
			
			@F_Surname			Varchar(50),
			@F_Initials			Varchar(10),
			@F_Title			Varchar(50),
			@F_ID_Number		Varchar(20),
			@F_PostalAddress1	Varchar(40),
			@F_PostalAddress2	Varchar(40),
			@F_PostalAddress3	Varchar(40),
			@F_PostalCode		Varchar(10),
			@F_HomeTelNo		Varchar(20),
			@F_WorkTelNo		Varchar(20),
			@F_MobileTelNo		Varchar(20),
			@F_Vehicle_Desc		Varchar(50),
			@F_Vehicle_Reg_No	Varchar(50),
			@F_Branch_Code		Varchar(20),
			@F_InvoiceNo		Varchar(20),
			@F_NoOfTyres		Varchar(20),
			@F_Price			Decimal(18,2),

			@C_Surname			Varchar(40),
			@C_Initials			Varchar(10),
			@C_Firstnames		Varchar(10),
			@C_Title			Varchar(50),
			@C_ID_Number		Varchar(20),
			@C_PostalAddress1	Varchar(40),
			@C_PostalAddress2	Varchar(40),
			@C_PostalAddress3	Varchar(40),
			@C_PostalCode		Varchar(10),
			@C_HomeTelNo		Varchar(20),
			@C_WorkTelNo		Varchar(20),
			@C_MobileTelNo		Varchar(20),

			@T_Surname			Varchar(50),
			@T_PostalAddress1	Varchar(40),
			@T_PostalAddress2	Varchar(40),
			@T_PostalAddress3	Varchar(40),
			@T_PostalCode		Varchar(10),
			
			@F_TyreData_1		Varchar(4000),
			@F_TyreData_2		Varchar(4000),
			@F_TyreData_3		Varchar(4000),
			@F_TyreData_4		Varchar(4000),
			@F_TyreData_5		Varchar(4000),
			@No_Days			Int,
			@Temp_No_Days		Varchar(20),
			@Details_Found		Int,
			@sql				Varchar(8000)
			
	DECLARE @Tbl_T Table
		(
			AS_Transactions_ID	Int,
			AC_CustomersID		Int,
			Transaction_Number	Varchar(20),
			Transaction_Date	Datetime,
			Customer_Reference	Varchar(15), --Make
			Comment				Varchar(20), --Reg No
		
			C_Surname			Varchar(40),
			C_Initials			Varchar(10),
			C_Firstnames		Varchar(50),
			C_Title				Varchar(50),						
			C_ID_Number			Varchar(20),
			C_PostalAddress1	Varchar(40),			
			C_PostalAddress2	Varchar(40),
			C_PostalAddress3	Varchar(40),
			C_PostalCode		Varchar(10),
			C_HomeTelNo			Varchar(20),
			C_WorkTelNo			Varchar(20),
			C_MobileTelNo		Varchar(20),			

			T_Surname			Varchar(50),
			T_PostalAddress1	Varchar(40),
			T_PostalAddress2	Varchar(40),
			T_PostalAddress3	Varchar(40),
			T_PostalCode		Varchar(10)
		)
		
	DECLARE @Tbl_F Table
		(
			F_TyreData_1 Text,
			F_TyreData_2 Varchar(1),
			F_TyreData_3 Varchar(1),
			F_TyreData_4 Varchar(1),
			F_TyreData_5 Varchar(1)
		)

	SELECT @F_Branch_Code = ISNULL(Network_Identity_Number,'ZZZ') From AW_User_Companies
                      	
	SELECT 
		TOP 1 @WhichName = ISNULL(Control_Value, '0')
	FROM 
		Sys_AW_Options
	WHERE 
		Control_Index = 0 AND
		Control_Type = 'CheckBox' AND
		Control_Name = 'chkPOSPrintTradeName'
	
    SELECT 
		TOP 1 @Temp_No_Days = ISNULL(Control_Value, 14)
    FROM 
		Sys_AW_Options
    WHERE 
		Control_Type = 'TextBox' AND
        Control_Name = 'txtCBillingDays'

	SET @Temp_No_Days = Replace(@Temp_No_Days,',','')	
	IF @Temp_No_Days = ''
		SET @Temp_No_Days = '14'
	
	IF ISNUMERIC(@Temp_No_Days) = 1
		SET @No_Days = @Temp_No_Days
	
	IF ISNUMERIC(@Temp_No_Days) = 0
		SET @No_Days = 14
	
	--RL V6_1 Changed to use dates sent through				
	--If Exists	
	--(
	--	Select 1
	--	From AS_Day_Ends
	--)
	--Begin 
	--	Select @LastDayEnd = MAX(Day_End) From AS_Day_Ends
	--	Select @LastDayEnd = DateAdd(d,(@No_Days*-1),@LastDayEnd)
	--End
	--Else
	--Begin		
	--	Select @LastDayEnd = '1900-01-01'
	--End	

	Set @StartDayEndDate = DateAdd(d,(@No_Days*-1),@StartDayEndDate)

	--Exec (@sql)

	
	--Exec (@sql)

	DECLARE Get_Data CURSOR
	FOR
	SELECT
		DISTINCT t.AS_Transactions_ID, t.Transaction_Number, t.Transaction_Date,
		LTRIM(RTRIM(ISNULL(s.Make,''))), LTRIM(RTRIM(ISNULL(s.Reg_No,''))),
		LTRIM(RTRIM(ISNULL(c.Surname,''))), LTRIM(RTRIM(ISNULL(c.Initials,''))), LTRIM(RTRIM(ISNULL(c.Firstnames,''))),
		LTRIM(RTRIM(ISNULL(x.[Description],''))), LTRIM(RTRIM(ISNULL(c.IDReg_Number,''))),
		LTRIM(RTRIM(ISNULL(c.Post_Box,''))), LTRIM(RTRIM(ISNULL(c.Post_Office,''))), LTRIM(RTRIM(ISNULL(c.City,''))) ,LTRIM(RTRIM(ISNULL(c.Post_Code,''))),
		LTRIM(RTRIM(ISNULL(c.Home_Tel_No,''))), LTRIM(RTRIM(ISNULL(c.Work_Tel_No,''))), LTRIM(RTRIM(ISNULL(c.Cell_No,''))),
		LTRIM(RTRIM(ISNULL(d.Customer_Name,''))), LTRIM(RTRIM(ISNULL(d.Inv_Address1,''))), LTRIM(RTRIM(ISNULL(d.Inv_Address2,''))),
		LTRIM(RTRIM(ISNULL(d.Inv_City,''))), LTRIM(RTRIM(ISNULL(d.Inv_Code,'')))
	FROM
		AS_Transactions t
    		LEFT OUTER JOIN AC_Customers c
    			ON t.AC_Customers_ID = c.AC_Customers_ID
    		LEFT OUTER JOIN AS_Transactions_Address a
    			ON t.AS_Transactions_ID = a.AS_Transactions_ID
    		LEFT OUTER JOIN AS_Transactions_Address_Detail d
    			ON a.AS_Transactions_Address_Detail_ID = d.AS_Transactions_Address_Detail_ID
    		LEFT OUTER JOIN Slu_AW_Titles x
    			ON x.Slu_AW_Titles_ID = c.Slu_AW_Titles_ID
    		LEFT OUTER JOIN AC_Assets s
    			ON s.AS_Transactions_ID = t.AS_Transactions_ID
   	WHERE
    	(t.Sys_AW_Transaction_Types_ID = 3 OR
	   	 t.Sys_AW_Transaction_Types_ID = 4) AND
    	t.Slu_AW_Active_ID = 1 AND
    	ISNULL(t.Total_Amount,0) <> 0 AND
        t.Day_End >=  @StartDayEndDate AND 
        t.Day_End <= @EndDayEndDate AND
        t.AW_User_Companies_ID = @CompanyID
    	Order By t.Transaction_Date

	--Exec (@sql)
	--Select (@sql)

	OPEN Get_Data
	
	 FETCH NEXT FROM Get_Data INTO
		@AS_Transactions_ID, @Transaction_Number, @Transaction_Date, @Customer_Reference, @Comment,
		@C_Surname, @C_Initials, @C_Firstnames, @C_Title, @C_ID_Number,
		@C_PostalAddress1, @C_PostalAddress2, @C_PostalAddress3, @C_PostalCode,
		@C_HomeTelNo, @C_WorkTelNo, @C_MobileTelNo,
		@T_Surname, @T_PostalAddress1, @T_PostalAddress2, @T_PostalAddress3, @T_PostalCode
	
	 WHILE @@FETCH_STATUS = 0
	 BEGIN
--Select @AS_Transactions_ID, @StartDayEndDate, @No_Days
		SET @F_TyreData_1 = ''
		SET @F_TyreData_2 = ''
		SET @F_TyreData_3 = ''
		SET @F_TyreData_4 = ''
		SET @F_TyreData_5 = ''
		
		SET @F_Surname = ''
		SET @F_Initials = ''
		SET @F_Title = ''
		SET @F_ID_Number = ''
		SET @F_PostalAddress1 = ''
		SET @F_PostalAddress2 = ''
		SET @F_PostalAddress3 = ''
		SET @F_PostalCode = ''
		SET @F_HomeTelNo = ''
		SET @F_WorkTelNo = ''
		SET @F_MobileTelNo = ''
		SET @F_Vehicle_Desc = ''
		SET @F_Vehicle_Reg_No = ''
		SET @F_InvoiceNo = ''
		SET @F_NoOfTyres = '0'
				
		--SELECT
		--	@F_NoOfTyres = Convert(Int,SUM(ISNULL(d.Quantity,0)))
		--FROM
		--	AS_Transaction_Details d
		--		LEFT OUTER JOIN AP_Products p
		--			ON d.AP_Products_ID = p.AP_Products_ID
		--WHERE
		--	AS_Transactions_ID = @AS_Transactions_ID AND
		--	ISNULL(d.Extended_Amount,0) <> 0 AND
		--	d.Slu_AW_Active_ID = 1 AND
		--	p.Slu_AW_YesNo_Non_Stock_Item = 0							
		
		IF @T_Surname <> ''
		BEGIN
			IF @WhichName = 1
			BEGIN
				IF RTRIM(LTRIM(@C_Surname)) + ISNULL((', ' + @C_Initials),'') + ' / ' + IsNull(@C_Firstnames,'') = @T_Surname
				BEGIN
					SET @F_Surname = @C_Surname
					SET @F_Initials = @C_Initials
					SET @F_Title = @C_Title
				END
				ELSE
				BEGIN
					SET @F_Surname = @T_Surname
					SET @F_Initials = ''
					SET @F_Title = ''			
				END
			END
			ELSE
			BEGIN
				IF RTRIM(LTRIM(@C_Surname)) + ISNULL((', ' + @C_Initials),'') = @T_Surname
				BEGIN
					SET @F_Surname = @C_Surname
					SET @F_Initials = @C_Initials
					SET @F_Title = @C_Title
				END
				ELSE
				BEGIN
					SET @F_Surname = @T_Surname
					SET @F_Initials = ''
					SET @F_Title = ''			
				END
			END
			
			 IF (@T_PostalAddress1 <> '''' OR @T_PostalAddress2 <> '''' OR @T_PostalAddress3 <> '''' OR @T_PostalCode <> '''')
			 BEGIN
				SET @F_PostalAddress1 = @T_PostalAddress1
				SET @F_PostalAddress2 = @T_PostalAddress2
				SET @F_PostalAddress3 = @T_PostalAddress3
				SET @F_PostalCode = @T_PostalCode
			 END
			 ELSE
			 BEGIN
				SET @F_PostalAddress1 = @C_PostalAddress1
				SET @F_PostalAddress2 = @C_PostalAddress2
				SET @F_PostalAddress3 = @C_PostalAddress3
				SET @F_PostalCode = @C_PostalCode
			 END
		END
		ELSE
		BEGIN
			SET @F_Surname = @C_Surname
			SET @F_Initials = @C_Initials
			SET @F_Title = @C_Title
			SET @F_PostalAddress1 = @C_PostalAddress1
			SET @F_PostalAddress2 = @C_PostalAddress2
			SET @F_PostalAddress3 = @C_PostalAddress3
			SET @F_PostalCode = @C_PostalCode
		END
		
		SET @F_ID_Number = @C_ID_Number
		SET @F_HomeTelNo = @C_HomeTelNo
		SET @F_WorkTelNo = @C_WorkTelNo
		SET @F_MobileTelNo = @C_MobileTelNo
		SET @F_Vehicle_Desc = @Customer_Reference
		SET @F_Vehicle_Reg_No = @Comment
		SET @F_InvoiceNo = @Transaction_Number
				
		SELECT @F_TyreData_1 = '1' + ','+
								REPLACE(@F_Surname,',','~') + ','+
								REPLACE(@F_Initials,',','~') + ','+
								REPLACE(@F_Title,',','~') + ','+
								REPLACE(@F_ID_Number,',','~') + ','+
								REPLACE(@F_PostalAddress1,',','~') + ','+
								REPLACE(@F_PostalAddress2,',','~') + ','+
								REPLACE(@F_PostalAddress3,',','~') + ','+
								REPLACE(@F_PostalCode,',','~') + ','+
								REPLACE(@F_HomeTelNo,',','~') + ','+
								REPLACE(@F_WorkTelNo,',','~') + ','+
								REPLACE(@F_MobileTelNo,',','~') + ','+
								REPLACE(@F_Vehicle_Desc,',','~') + ','+
								REPLACE(@F_Vehicle_Reg_No,',','~') + ','+								
								REPLACE(@F_Branch_Code,',','~') + ','+
								REPLACE(@F_InvoiceNo,',','~') + ','+
								--REPLACE(@F_NoOfTyres,',','~') + ','
								'XXXXXXXXXXXXXXXXX' + ','

		SET @Details_Found = 0
		SET @F_NoOfTyres = '0'
		
	SET @sql = 'DECLARE Get_Detail CURSOR '
	SET @sql = @sql + ' FOR '
	SET @sql = @sql + ' SELECT '
	SET @sql = @sql + '		ISNULL(d.Quantity,0), ISNULL(d.Extended_Amount,0), '
	SET @sql = @sql + '		LTRIM(RTRIM(ISNULL(p.Description,''''))), '
	SET @sql = @sql + '		LTRIM(RTRIM(ISNULL(p.Product_Code,''''))) '
	SET @sql = @sql + ' FROM '
	SET @sql = @sql + '		AS_Transaction_Details d '
	SET @sql = @sql + '		INNER JOIN AP_Products p '
	SET @sql = @sql + '			ON d.AP_Products_ID = p.AP_Products_ID '

    SET @sql = @sql + '		INNER JOIN Lup_AP_Product_Departments pd '
    SET @sql = @sql + '			ON p.Lup_AP_Product_Departments_ID = pd.Lup_AP_Product_Departments_ID '
    SET @sql = @sql + '		INNER JOIN Lup_AP_Product_Groups pg ' 
    SET @sql = @sql + '			ON p.Lup_AP_Product_Groups_ID = pg.Lup_AP_Product_Groups_ID '
    SET @sql = @sql + '		INNER JOIN Lup_AP_Product_Manufacturers pm '
    SET @sql = @sql + '			ON p.Lup_AP_Product_Manufacturers_ID = pm.Lup_AP_Product_Manufacturers_ID '
    SET @sql = @sql + '		INNER JOIN Lup_AP_Product_Types pt '
    SET @sql = @sql + '			ON p.Lup_AP_Product_Types_ID = pt.Lup_AP_Product_Types_ID '
			
	SET @sql = @sql + ' WHERE '
	SET @sql = @sql + '	d.AS_Transactions_ID = ' + CONVERT(varchar(30), @AS_Transactions_ID) + ' AND '
	SET @sql = @sql + '	ISNULL(d.Extended_Amount,0) <> 0 AND '
	SET @sql = @sql + '	d.Slu_AW_Active_ID = 1 AND '
	SET @sql = @sql + '	p.Slu_AW_YesNo_Non_Stock_Item = 0 '
			
	--Exclusions List
    SET @sql = @sql + CONVERT(varchar(8000), @ExclusionsFilter)  
    
	--Inclusions List
    SET @sql = @sql + CONVERT(varchar(8000), @InclusionFilter)  
--Select @sql
	Exec (@sql)
				
	 	OPEN Get_Detail
		
		FETCH NEXT FROM Get_Detail INTO
			@Quantity, @Extended_Amount, @Product_Description, @Product_Code
			
		WHILE @@FETCH_STATUS = 0
		BEGIN
				
--Select 		@AS_Transactions_ID, @Quantity, @Extended_Amount, @Product_Description, @Product_Code

	
			SET @Details_Found = 1
			SET @F_Price = 0
			SET @F_Price = Convert(Decimal(18,2), (@Extended_Amount/ABS(@Quantity)))
			
			SET @Loop_Ind = 1
			
			IF @Quantity < 0
				SET @Quantity = @Quantity * -1
			
			SET @F_NoOfTyres = Convert(Varchar(10), ( Convert(Decimal(9,3),@F_NoOfTyres) + @Quantity ) )
			
			WHILE @Loop_Ind <= @Quantity
			BEGIN
				IF Len(@F_TyreData_1) < 3850
				BEGIN
					SET @F_TyreData_1 = @F_TyreData_1 +
										Convert(Varchar(10),@Transaction_Date,111) + ','+
										Convert(Varchar(20),@F_Price) + ','+
										REPLACE(@Product_Code,',','~') + ','+
										REPLACE(@Product_Description,',','~') + ',,'
				END
				ELSE
				IF (Len(@F_TyreData_1) >= 3850 AND Len(@F_TyreData_2)<3850)
				BEGIN
					SET @F_TyreData_2 = @F_TyreData_2 +
										Convert(Varchar(10),@Transaction_Date,111) + ','+
										Convert(Varchar(20),@F_Price) + ','+
										REPLACE(@Product_Code,',','~') + ','+
										REPLACE(@Product_Description,',','~') + ',,'
				END
				
				SET @Loop_Ind = @Loop_Ind+1
			END
		
			FETCH NEXT FROM Get_Detail INTO
				@Quantity, @Extended_Amount, @Product_Description, @Product_Code
		END
		CLOSE Get_Detail
		Deallocate Get_Detail

		IF NOT (Len(@F_TyreData_1) >= 3850 AND Len(@F_TyreData_2) >= 3850)
		BEGIN
			IF @Details_Found = 1
			BEGIN
				SET @F_TyreData_1 = REPLACE(@F_TyreData_1, 'XXXXXXXXXXXXXXXXX', @F_NoOfTyres)
			
				INSERT INTO @Tbl_F(F_TyreData_1) Values(@F_TyreData_1+@F_TyreData_2+@F_TyreData_3+@F_TyreData_4+@F_TyreData_5)
			END
		END
	
		FETCH NEXT FROM Get_Data INTO
			@AS_Transactions_ID, @Transaction_Number, @Transaction_Date, @Customer_Reference, @Comment,
			@C_Surname, @C_Initials, @C_Firstnames, @C_Title, @C_ID_Number,
			@C_PostalAddress1, @C_PostalAddress2, @C_PostalAddress3, @C_PostalCode,
			@C_HomeTelNo, @C_WorkTelNo, @C_MobileTelNo,
			@T_Surname, @T_PostalAddress1, @T_PostalAddress2, @T_PostalAddress3, @T_PostalCode 
	 END
	 CLOSE Get_Data
	 DEALLOCATE Get_Data

	 SELECT ISNULL(F_TyreData_1,'') AS [F1], ISNULL(F_TyreData_2,'') AS [F2],
			ISNULL(F_TyreData_3,'') AS [F3], ISNULL(F_TyreData_4,'') AS [F4],
			ISNULL(F_TyreData_5,'') AS [F5]
	 FROM @Tbl_F

SET NOCOUNT OFF
GO

--6 sp_AS_CSales_Submission_REW
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_CSales_Submission_REW]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_CSales_Submission_REW]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_CSales_Submission_REW
--Purpose       :Get Sales Submission Data For Rewards Program
--Parameters    :
--Date          :2014-10-15
--Authors       :RL
--Version       :6.0
--MODS          :
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_CSales_Submission_REW]
(
        @ExclusionsFilter	varchar(8000),
        @InclusionFilter	varchar(8000),
        @StartDayEndDate	datetime,
        @EndDayEndDate		datetime,
		@CompanyID			int
)
AS

SET NOCOUNT ON

	DECLARE @LastDayEnd				DateTime,
			@Temp_No_Days			Varchar(20),	
			@No_Days				Int,
			@F_Branch_Code			Varchar(5),
			@Transaction_Type		Varchar(2),
			@Transaction_Number		Varchar(20),
			@Transaction_Date		Varchar(8),
			@Transaction_Time		Varchar(5),
			@Rep_ID					Varchar(5),
			@Rep_Name				Varchar(30),
			@Product_Code			Varchar(20),
			@Product_Description	Varchar(50),
			@Quantity				Varchar(20),
			@OLD_Transaction_Number	Varchar(20),
			@sql					Varchar(8000)
		
	DECLARE @Tbl_F Table
		(
			[Rec] Text
		)

	--SELECT @F_Branch_Code = ISNULL(Network_Identity_Number,'ZZZ') FROM AW_User_Companies
     
    SET @OLD_Transaction_Number = '' 
                      	
   SELECT 
		TOP 1 @Temp_No_Days = ISNULL(Control_Value, 14)
    FROM 
		Sys_AW_Options
    WHERE 
		Control_Type = 'TextBox' AND
        Control_Name = 'txtCBillingDays'

	SET @Temp_No_Days = Replace(@Temp_No_Days,',','')	
	IF @Temp_No_Days = ''
		SET @Temp_No_Days = '14'
	
	IF ISNUMERIC(@Temp_No_Days) = 1
		SET @No_Days = @Temp_No_Days
	
	IF ISNUMERIC(@Temp_No_Days) = 0
		SET @No_Days = 14
			
	Set @StartDayEndDate = DateAdd(d,(@No_Days*-1),@StartDayEndDate)
	
	SET @sql = '        DECLARE Get_Data CURSOR FOR '
	SET @sql = @sql + '	SELECT '
	SET @sql = @sql + '		CASE IsNull(t.Sys_AW_Transaction_Types_ID,0) '		--Transaction Rep
	SET @sql = @sql + '		WHEN 3 THEN ''' + 'IN' +  ''' '
	SET @sql = @sql + '		WHEN 4 THEN ''' + 'CN' +  ''' '
	SET @sql = @sql + '		ELSE ''' + 'UN' +  ''' '
	SET @sql = @sql + '		END, '
	SET @sql = @sql + '		ISNULL(t.Transaction_Number,''''), '					--Transaction Number
	SET @sql = @sql + '		CONVERT(Varchar(10),t.Transaction_Date,112), '		--Transaction Date
	SET @sql = @sql + '		CONVERT(Varchar(5),t.Transaction_Date,108), '			--Transaction Time
	SET @sql = @sql + '		CONVERT(VARCHAR(20),IsNull(t.Lup_AS_Reps_ID,0)), '	--Transaction Rep ID
	SET @sql = @sql + '		CASE IsNull(t.Lup_AS_Reps_ID,0) '					--Transaction Rep
	SET @sql = @sql + '		WHEN 0 THEN ''' + '<UNKNOWN>' +  ''' '     
	SET @sql = @sql + '		ELSE IsNull(r.[Description],'''') '	
	SET @sql = @sql + '		END, '
	SET @sql = @sql + '		ISNULL(p.Product_Code,''''), '							--Product Code
	SET @sql = @sql + '		ISNULL(p.[Description],''''), '							--Product Description
	SET @sql = @sql + '		CONVERT(Varchar(20),ISNULL(d.Quantity,0)) '			--Quantity
	SET @sql = @sql + '		FROM ' 
	SET @sql = @sql + '		AS_Transactions t '
	SET @sql = @sql + '		INNER JOIN AS_Transaction_Details d '
	SET @sql = @sql + '			ON t.AS_Transactions_ID = d.AS_Transactions_ID '
	SET @sql = @sql + '		LEFT OUTER JOIN AP_Products p '
	SET @sql = @sql + '			ON d.AP_Products_ID = p.AP_Products_ID '
	SET @sql = @sql + '		LEFT OUTER JOIN Lup_AS_Reps r '
	SET @sql = @sql + '			ON t.Lup_AS_Reps_ID = r.Lup_AS_Reps_ID '

    SET @sql = @sql + '		INNER JOIN Lup_AP_Product_Departments pd '
    SET @sql = @sql + '			ON p.Lup_AP_Product_Departments_ID = pd.Lup_AP_Product_Departments_ID '
    SET @sql = @sql + '		INNER JOIN Lup_AP_Product_Groups pg ' 
    SET @sql = @sql + '			ON p.Lup_AP_Product_Groups_ID = pg.Lup_AP_Product_Groups_ID '
    SET @sql = @sql + '		INNER JOIN Lup_AP_Product_Manufacturers pm '
    SET @sql = @sql + '			ON p.Lup_AP_Product_Manufacturers_ID = pm.Lup_AP_Product_Manufacturers_ID '
    SET @sql = @sql + '		INNER JOIN Lup_AP_Product_Types pt '
    SET @sql = @sql + '			ON p.Lup_AP_Product_Types_ID = pt.Lup_AP_Product_Types_ID '			
	
	SET @sql = @sql + '	WHERE ' 
	SET @sql = @sql + '		(t.Sys_AW_Transaction_Types_ID = 3  OR '      -- Invoices
	SET @sql = @sql + '		 t.Sys_AW_Transaction_Types_ID = 4)  AND '    -- Refunds	
	SET @sql = @sql + '     t.AW_User_Companies_ID = ' + CONVERT(varchar(30), @CompanyID) + ' AND '   			
	SET @sql = @sql + '		t.Slu_AW_Active_ID = 1 AND '
	SET @sql = @sql + '		d.Slu_AW_Active_ID = 1 AND '
	SET @sql = @sql + '		t.Total_Amount <> 0 AND '
	SET @sql = @sql + '		p.Slu_AW_YesNo_Non_Stock_Item = 0 AND'	
    SET @sql = @sql + '		t.Day_End >= ''' + CONVERT(varchar(30), @StartDayEndDate) + ''' AND '
    SET @sql = @sql + '		t.Day_End <= ''' + CONVERT(varchar(30), @EndDayEndDate ) + ''' '		

	--Exclusions List
    SET @sql = @sql + CONVERT(varchar(8000), @ExclusionsFilter)  
    
	--Inclusions List
    SET @sql = @sql + CONVERT(varchar(8000), @InclusionFilter)  
    
	SET @sql = @sql + '	ORDER BY t.Transaction_Date ' 	  	
--	Select @sql
	Exec (@sql)
	
	OPEN Get_Data
	
	FETCH NEXT FROM Get_Data INTO 
		@Transaction_Type,	@Transaction_Number, @Transaction_Date, @Transaction_Time,
		@Rep_ID, @Rep_Name, @Product_Code, @Product_Description, @Quantity

	WHILE @@FETCH_STATUS = 0
	BEGIN
	
		SELECT @Rep_Name = Replace(@Rep_Name,',',' ')
		SELECT @Product_Code = Replace(@Product_Code,',',' ')
		SELECT @Product_Description = Replace(@Product_Description,',',' ')				
		
		IF @OLD_Transaction_Number != @Transaction_Number
		BEGIN
			--Insert Header Sales Records
			INSERT INTO @Tbl_F
			(
				[Rec]
			)
			VALUES
			(
				'H' + ',' +
				@Transaction_Number + ',' +
				@Transaction_Date + ',' +
				@Transaction_Time + ',' +
				@Transaction_Type + ',' +
				@Rep_ID + ' - ' + @Rep_Name + ','
			)
		END
		
		SET @OLD_Transaction_Number = @Transaction_Number		
		
		IF @OLD_Transaction_Number = @Transaction_Number
		BEGIN
			--Insert Header Sales Records
			INSERT INTO @Tbl_F
			(
				[Rec]
			)
			VALUES
			(
				'D' + ',' +
				@Transaction_Number + ',' +
				@Product_Code + ',' +
				@Quantity + ',' + 
				@Transaction_Type + ',' +
				@Transaction_Date + ',' +
				@Transaction_Time + ',' +				
				@Product_Description + ','
			)
		END			
				
		FETCH NEXT FROM Get_Data INTO 
			@Transaction_Type,	@Transaction_Number, @Transaction_Date, @Transaction_Time,
			@Rep_ID, @Rep_Name, @Product_Code, @Product_Description, @Quantity	
	END	
	CLOSE Get_Data
	Deallocate Get_Data

	SELECT [Rec] FROM @Tbl_F

SET NOCOUNT OFF
GO

--7 sp_RPT_Customer_Delivery_Details
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_RPT_Customer_Delivery_Details]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_RPT_Customer_Delivery_Details]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_RPT_Customer_Delivery_Details
--Purpose       :Get Customer Delivery Details
--Parameters    :
--Date          :2014-10-30
--Authors       :RL
--Version       :6.0
--MODS          :
-------------------------------------------------------------------------------

 
CREATE PROCEDURE [dbo].[sp_RPT_Customer_Delivery_Details]
	@FromDate			DateTime,
	@ToDate				DateTime,
	@AC_Customer_ID		Int,
	@Sales_Rep_ID		Int,
	@Customer_Rep_ID	Int,
	@Cashier_ID			Int,
	@Sales_Area_ID		Int,
	@Invoice			Int,
	@Refunds			Int,
	@Quotes				Int,
	@Sales_Orders		Int,
	@ProFormas			Int,
	@CompanyID			Int
AS

SET NOCOUNT ON

	DECLARE @WhichName			Tinyint
		
	DECLARE @Tbl_T Table
		(
			AS_Transaction_Details_ID	Int,
			AS_Transactions_ID		Int,
			AC_CustomersID			Int,
			Transaction_Number		Varchar(20),
			Transaction_Date		Datetime,
			Quantity				Money,
			Unit_Cost				Money,
			Tax_Amount				Money,
			Extended_Amount			Money,
			AP_Products_ID			Int,
			P_Description			Varchar(50),
			Lup_AS_Sales_Reps_ID	Int,
			Sales_Rep				Varchar(50),
			Lup_AS_Cashiers_ID		Int,
			Cashier					Varchar(50),
			Lup_AS_Customer_Reps_ID	Int,
			Customer_Rep			Varchar(50),	
			Lup_AC_Sales_Areas_ID	Int,
			Customer_Sales_Area		Varchar(50),			
			
			C_AC_Customers_ID		Int,
			C_Surname				Varchar(40),
			C_Initials				Varchar(10),
			C_Firstnames			Varchar(50),
			C_Title					Varchar(50),						
			C_ID_Number				Varchar(20),
			C_PostalAddress1		Varchar(40),			
			C_PostalAddress2		Varchar(40),
			C_PostalCode			Varchar(10),
			C_HomeTelNo				Varchar(20),
			C_WorkTelNo				Varchar(20),
			C_MobileTelNo			Varchar(20),
			C_Street_Address		Varchar(40),
			C_Suburb				Varchar(30),
			C_City					Varchar(30),
			C_Street_Post_Code		Varchar(10),
			C_Delivery_Address		Varchar(40),
			C_Delivery_Suburb		Varchar(40),
			C_Delivery_City			Varchar(30),
			C_Delivery_Post_Code	Varchar(10),

			T_Surname				Varchar(50),
			T_Inv_Address1			Varchar(40),
			T_Inv_Address2			Varchar(40),
			T_Inv_City				Varchar(40),
			T_Inv_Code				Varchar(10),
			T_Delivery_Address		Varchar(40),
			T_Delivery_Suburb		Varchar(40),
			T_Delivery_City			Varchar(30),
			T_PostalCode			Varchar(10)
		)		
                      	
	SELECT TOP 1 @WhichName = ISNULL(Control_Index, '0')
	FROM Sys_AW_Options
	WHERE Control_Type = 'OptionButton' AND
	Control_Name = 'optPOSPrintAddress' AND
	Control_Value = 'True'			  

	--Insert Sales Records
	INSERT INTO @Tbl_T
	(
		AS_Transaction_Details_ID, AS_Transactions_ID, AC_CustomersID, Transaction_Number, Transaction_Date, 		
		Quantity, Unit_Cost, Tax_Amount, Extended_Amount, 
		
		AP_Products_ID, P_Description,
		Lup_AS_Sales_Reps_ID, Sales_Rep, 
		Lup_AS_Cashiers_ID, Cashier, 
		Lup_AS_Customer_Reps_ID, Customer_Rep, 
		Lup_AC_Sales_Areas_ID, Customer_Sales_Area,	

		C_AC_Customers_ID,
		C_Surname, C_Initials, C_Firstnames,
		C_Title, C_ID_Number, C_PostalAddress1, 
		C_PostalAddress2, C_PostalCode, 
		C_HomeTelNo, C_WorkTelNo, C_MobileTelNo,	
		C_Street_Address, C_Suburb,	C_City,	C_Street_Post_Code,
		
		C_Delivery_Address,	C_Delivery_Suburb, C_Delivery_City,	C_Delivery_Post_Code,
		T_Surname, T_Inv_Address1, T_Inv_Address2,
		T_Inv_City, T_Inv_Code,
		T_Delivery_Address, T_Delivery_Suburb, 
		T_Delivery_City, T_PostalCode
	)
	SELECT
		DISTINCT td.AS_Transaction_Details_ID, tt.AS_Transactions_ID, tt.AC_Customers_ID, tt.Transaction_Number, tt.Transaction_Date,		
		ISNULL(td.Quantity,0), ISNULL(td.Unit_Cost,0), ISNULL(td.Tax_Amount,0), ISNULL(td.Extended_Amount,0),	
		td.AP_Products_ID, LTRIM(RTRIM(ISNULL(p.[Description],''))),
		tt.Lup_AS_Reps_ID, LTRIM(RTRIM(ISNULL(sr.[Description],''))),
		tt.Lup_AS_Cashiers_ID, LTRIM(RTRIM(ISNULL(u.FirstName,''))) + ' ' + LTRIM(RTRIM(ISNULL(u.Surname,''))), 
		c.Lup_AS_Reps_ID, LTRIM(RTRIM(ISNULL(cr.[Description],''))),
		c.Lup_AC_Sales_Areas_ID, LTRIM(RTRIM(ISNULL(sa.[Description],''))),
		
		c.AC_Customers_ID,
		LTRIM(RTRIM(ISNULL(c.Surname,''))), LTRIM(RTRIM(ISNULL(c.Initials,''))), LTRIM(RTRIM(ISNULL(c.Firstnames,''))),
		LTRIM(RTRIM(ISNULL(x.[Description],''))), LTRIM(RTRIM(ISNULL(c.IDReg_Number,''))), LTRIM(RTRIM(ISNULL(c.Post_Box,''))),
		LTRIM(RTRIM(ISNULL(c.Post_Office,''))),	LTRIM(RTRIM(ISNULL(c.Post_Code,''))),
		LTRIM(RTRIM(ISNULL(c.Home_Tel_No,''))), LTRIM(RTRIM(ISNULL(c.Work_Tel_No,''))), LTRIM(RTRIM(ISNULL(c.Cell_No,''))),
		LTRIM(RTRIM(ISNULL(c.Street_Address,''))),	LTRIM(RTRIM(ISNULL(c.Suburb,''))), LTRIM(RTRIM(ISNULL(c.City,''))), LTRIM(RTRIM(ISNULL(c.Street_Post_Code,''))),
				
		LTRIM(RTRIM(ISNULL(c.Delivery_Address,''))), LTRIM(RTRIM(ISNULL(c.Delivery_Suburb,''))), LTRIM(RTRIM(ISNULL(c.Delivery_City,''))), LTRIM(RTRIM(ISNULL(c.Delivery_Post_Code,''))),
		LTRIM(RTRIM(ISNULL(d.Customer_Name,''))), LTRIM(RTRIM(ISNULL(d.Inv_Address1,''))), LTRIM(RTRIM(ISNULL(d.Inv_Address2,''))),
		LTRIM(RTRIM(ISNULL(d.Inv_City,''))), LTRIM(RTRIM(ISNULL(d.Inv_Code,''))),
		LTRIM(RTRIM(ISNULL(d.Delivery_Address,''))), LTRIM(RTRIM(ISNULL(d.Delivery_Suburb,''))),
		LTRIM(RTRIM(ISNULL(d.Delivery_City,''))), LTRIM(RTRIM(ISNULL(d.Delivery_Post_Code,'')))
	FROM 
		AS_Transactions tt
		INNER JOIN AS_Transaction_Details td
			ON tt.AS_Transactions_ID = td.AS_Transactions_ID
		LEFT OUTER JOIN AC_Customers c
			ON tt.AC_Customers_ID = c.AC_Customers_ID
		LEFT OUTER JOIN AS_Transactions_Address a
			ON tt.AS_Transactions_ID = a.AS_Transactions_ID
		LEFT OUTER JOIN AS_Transactions_Address_Detail d
			ON a.AS_Transactions_Address_Detail_ID = d.AS_Transactions_Address_Detail_ID			
		LEFT OUTER JOIN Slu_AW_Titles x
			ON x.Slu_AW_Titles_ID = c.Slu_AW_Titles_ID
		LEFT OUTER JOIN AP_Products p
			ON td.AP_Products_ID = p.AP_Products_ID
		LEFT OUTER JOIN Lup_AS_Reps sr
			ON tt.Lup_AS_Reps_ID = sr.Lup_AS_Reps_ID
		LEFT OUTER JOIN Lup_AS_Reps cr
			ON c.Lup_AS_Reps_ID = sr.Lup_AS_Reps_ID
		LEFT OUTER JOIN AW_Users u
			ON tt.[User_ID] = u.AW_Users_ID
		LEFT OUTER JOIN Lup_AC_Sales_Areas sa
			ON c.Lup_AC_Sales_Areas_ID = sa.Lup_AC_Sales_Areas_ID		
	WHERE 
		tt.Slu_AW_Active_ID = 1 AND
		tt.AW_User_Companies_ID = @CompanyID AND
--		(tt.Sys_AW_Transaction_Types_ID = 3  OR      -- Invoices
--		 tt.Sys_AW_Transaction_Types_ID = 4)  AND    -- Refunds			 
		 tt.Transaction_Date BETWEEN @FromDate AND @ToDate AND
		 --tt.Transaction_Date BETWEEN '2014-01-01' AND '2014-07-01' AND
		 tt.Total_Amount <> 0
		 AND tt.Sys_AW_Transaction_Types_ID IN (1,3,4,13,16)
		--AND t.AS_Transactions_ID = 49757
	

	SELECT
		CASE C_Firstnames
			WHEN '' THEN C_Surname + '(' + Convert(Varchar(10),C_AC_Customers_ID) + ')*** ' +	CASE LTRIM(RTRIM(T_Delivery_Address + ', ' + T_Delivery_Suburb + ', ' + T_Delivery_City + ', ' + T_PostalCode))
													WHEN ',,,' THEN REPLACE(REPLACE( LTRIM(RTRIM(C_Delivery_Address + ', ' + C_Delivery_Suburb + ', ' + C_Delivery_City + ', ' + C_Delivery_Post_Code)) ,',,,',','),',,',',')
													ELSE REPLACE(REPLACE( LTRIM(RTRIM(T_Delivery_Address + ', ' + T_Delivery_Suburb + ', ' + T_Delivery_City + ', ' + T_PostalCode)) ,',,,',','),',,',',')
												END
			ELSE C_Firstnames + ', ' + C_Surname + '(' + Convert(Varchar(10),C_AC_Customers_ID) + ')*** ' +	CASE LTRIM(RTRIM(T_Delivery_Address + ', ' + T_Delivery_Suburb + ', ' + T_Delivery_City + ', ' + T_PostalCode))
																	WHEN ',,,' THEN REPLACE(REPLACE( LTRIM(RTRIM(C_Delivery_Address + ', ' + C_Delivery_Suburb + ', ' + C_Delivery_City + ', ' + C_Delivery_Post_Code)) ,',,,',','),',,',',')
																	ELSE REPLACE(REPLACE( LTRIM(RTRIM(T_Delivery_Address + ', ' + T_Delivery_Suburb + ', ' + T_Delivery_City + ', ' + T_PostalCode)) ,',,,',','),',,',',')
																END
		END AS [Customer_Delivery],
		
		CASE C_Firstnames
			WHEN '' THEN C_Surname
			ELSE C_Firstnames + ', ' + C_Surname 
		END AS [Customer],	
		CASE T_Surname
			WHEN '' THEN C_Firstnames + ' ' + C_Surname
			ELSE T_Surname
		END AS [InoicedTo],
		
		CASE @WhichName
			WHEN 0 THEN
				CASE LTRIM(RTRIM(T_Inv_Address1 + ', ' + T_Inv_Address2 + ', ' + T_Delivery_City + ', ' + T_Inv_Code))
					WHEN ',,,' THEN REPLACE(REPLACE( LTRIM(RTRIM(C_PostalAddress1 + ', ' + C_PostalAddress2 + ', ' + C_PostalCode)) ,',,,',','),',,',',') 
					ELSE REPLACE(REPLACE( LTRIM(RTRIM(T_Inv_Address1 + ', ' + T_Inv_Address2 + ', ' + T_Delivery_City + ', ' + T_Inv_Code)) ,',,,',','),',,',',')
				END
			ELSE
				CASE LTRIM(RTRIM(T_Inv_Address1 + ', ' + T_Inv_Address2 + ', ' + T_Delivery_City + ', ' + T_Inv_Code))
					WHEN ',,,' THEN  REPLACE(REPLACE( LTRIM(RTRIM(C_Street_Address + ', ' + C_Suburb + ', ' + C_City + ', ' + C_Street_Post_Code)) ,',,,',','),',,',',')
					ELSE REPLACE(REPLACE( LTRIM(RTRIM(T_Inv_Address1 + ', ' + T_Inv_Address2 + ', ' + T_Delivery_City + ', ' + T_Inv_Code)) ,',,,',','),',,',',')
				END
		END	AS [Invoice_Address],
		
		CASE LTRIM(RTRIM(T_Delivery_Address + ', ' + T_Delivery_Suburb + ', ' + T_Delivery_City + ', ' + T_PostalCode))
			WHEN ',,,' THEN  REPLACE(REPLACE( LTRIM(RTRIM(C_Delivery_Address + ', ' + C_Delivery_Suburb + ', ' + C_Delivery_City + ', ' + C_Delivery_Post_Code)) ,',,,',','),',,',',')
			ELSE REPLACE(REPLACE( LTRIM(RTRIM(T_Delivery_Address + ', ' + T_Delivery_Suburb + ', ' + T_Delivery_City + ', ' + T_PostalCode)) ,',,,',','),',,',',')
		END AS [Delivery_Address],
		
		P_Description,
		CONVERT(money,(Quantity) ) AS [Quantity],
		CONVERT(money,(Extended_Amount - Tax_Amount) - (Quantity * Unit_Cost) ) AS [GP],
		CASE 
			WHEN dbo.fn_AS_Calc_Act_Sales_Value(Extended_Amount, Tax_Amount) <> 0 
			THEN CONVERT(money,((dbo.fn_AS_Calc_Act_GP(Extended_Amount, Tax_Amount, Quantity, Unit_Cost)) / dbo.fn_AS_Calc_Act_Sales_Value(Extended_Amount, Tax_Amount) * 100)) 
			ELSE 0.00 
		END AS [Act GP%],
		(Extended_Amount - Tax_Amount) AS [NetSales],
		Sales_Rep AS [Sales_Rep],
		Cashier AS [Cashier],
		Customer_Rep AS [Customer_Rep],
		Customer_Sales_Area AS [Customer_Sales_Area],
		Transaction_Date				
	FROM @Tbl_T	
	ORDER BY	CASE C_Firstnames
					WHEN '' THEN C_Surname + ' *** ' +	CASE LTRIM(RTRIM(T_Delivery_Address + ', ' + T_Delivery_Suburb + ', ' + T_Delivery_City + ', ' + T_PostalCode))
															WHEN ',,,' THEN REPLACE(REPLACE( LTRIM(RTRIM(C_Delivery_Address + ', ' + C_Delivery_Suburb + ', ' + C_Delivery_City + ', ' + C_Delivery_Post_Code)) ,',,,',','),',,',',')
															ELSE REPLACE(REPLACE( LTRIM(RTRIM(T_Delivery_Address + ', ' + T_Delivery_Suburb + ', ' + T_Delivery_City + ', ' + T_PostalCode)) ,',,,',','),',,',',')
														END
				ELSE C_Firstnames + ', ' + C_Surname + ' *** ' +	CASE LTRIM(RTRIM(T_Delivery_Address + ', ' + T_Delivery_Suburb + ', ' + T_Delivery_City + ', ' + T_PostalCode))
																		WHEN ',,,' THEN REPLACE(REPLACE( LTRIM(RTRIM(C_Delivery_Address + ', ' + C_Delivery_Suburb + ', ' + C_Delivery_City + ', ' + C_Delivery_Post_Code)) ,',,,',','),',,',',')
																		ELSE REPLACE(REPLACE( LTRIM(RTRIM(T_Delivery_Address + ', ' + T_Delivery_Suburb + ', ' + T_Delivery_City + ', ' + T_PostalCode)) ,',,,',','),',,',',')
																	END
		END
	
--	Transaction_Date, C_Firstnames + ', ' + C_Surname, Customer_Rep, Customer_Sales_Area
	 
SET NOCOUNT OFF
GO

--8 sp_RPT_AS_Low_Profit_Sales
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_RPT_AS_Low_Profit_Sales]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_RPT_AS_Low_Profit_Sales]
GO
-------------------------------------------------------------------------------
--Description   :sp_RPT_AS_Low_Profit_Sales
--Purpose       :DayEnd Sales lower than @GPThreshold by Filter by Product
--Functionality :
--Date          :2008/11/07
--Authors       :TB
--MODS:         :
--2004.4.7      :16/09/09 - Replaced 'Location' filter with 'Cashier' - TW
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_RPT_AS_Low_Profit_Sales]
    (
        @GPThreshold decimal(12,3),
        @AcctType tinyint,
        @Option varchar(30),
        @DayEndFromDate datetime,
        @DayEndToDate datetime,
        @CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000)


-- SET @GPThreshold = 5
-- SET @AcctType = 1
-- SET @Option = 'Department'
-- SET @DayEndFromDate = '2008/10/01 16:56:00'
-- SET @DayEndToDate = '2008/10/30 16:53:00'
-- SET @CompanyID = 1


    SET @sql = ' SELECT '

    IF @Option = 'Type'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Types_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Option = 'Group'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Groups_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Option = 'Department'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Departments_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Option = 'Supplier'
        SET @sql = @sql +
            ' o.AO_Suppliers_ID AS [HeaderID], ' +
            ' o.[Supplier_Name] AS [Filter], '
    ELSE
    IF @Option = 'Manufacturer'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Manufacturers_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Option = 'Cashier'
        SET @sql = @sql +
            ' o.AW_Users_ID AS [HeaderID], ' +
            ' o.UserName AS [Filter], '
    ELSE
    IF @Option = 'Sales Area'
        SET @sql = @sql +
            ' o.Lup_AC_Sales_Areas_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Option = 'Sales Person'
        SET @sql = @sql +
            ' o.Lup_AS_Reps_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '
    ELSE
    IF @Option = 'Salesperson'
        SET @sql = @sql +
            ' o.Lup_AS_Reps_ID AS [HeaderID], ' +
            ' o.[Description] AS [Filter], '


    SET @sql = @sql + ' ISNULL(c.Surname, '''') + '' '' + '
    SET @sql = @sql + ' ISNULL(c.Firstnames, '''') '
    SET @sql = @sql + ' + '' ('' + CONVERT(varchar(10), c.AC_Customers_ID) + '')'' AS [Customer], '

    SET @sql = @sql + ' c.Sys_AC_Account_Types_ID AS [AcctTypeID], '

    SET @sql = @sql + ' p.AP_Products_ID AS [ProdID], '
    SET @sql = @sql + ' p.Description AS [Product], '
    SET @sql = @sql + ' p.Product_Code AS [Code], '

    SET @sql = @sql + ' CASE WHEN h.Sys_AW_Transaction_Types_ID = 3 '
    SET @sql = @sql + '          THEN ''INV'' '
    SET @sql = @sql + '      WHEN h.Sys_AW_Transaction_Types_ID = 4 '
    SET @sql = @sql + '          THEN ''C/N'' '
    SET @sql = @sql + '          ELSE ''INV'' '
    SET @sql = @sql + '      END AS [TranType], '
    SET @sql = @sql + ' LEFT(CONVERT(CHAR(10), h.Transaction_Date, 121), 10) AS [TranDate], '
    SET @sql = @sql + ' h.Transaction_Number AS [DocNo], '
    SET @sql = @sql + ' CONVERT(money, d.Quantity) AS [Qty], '
    SET @sql = @sql + ' CONVERT(money, d.Original_Price) AS [DealerPrice], '
    SET @sql = @sql + ' CASE WHEN (d.Original_Price * d.Quantity) <> 0 '
    SET @sql = @sql + '      THEN ABS(CONVERT(money, (((d.Original_Price * d.Quantity) - (d.Extended_Amount - d.Tax_Amount)) / (d.Original_Price * d.Quantity)) * 100)) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Disc%], '
    SET @sql = @sql + ' CONVERT(money, d.Unit_Price) AS [UnitSelling], '
    SET @sql = @sql + ' CONVERT(money, d.Extended_Amount - d.Tax_Amount) AS [TotalNetSales], '
    SET @sql = @sql + ' CONVERT(money, d.Unit_Cost) AS [UnitCost], '
    SET @sql = @sql + ' CONVERT(money, d.Unit_Cost * d.Quantity) AS [TotalCost], '
    SET @sql = @sql + ' CONVERT(money, (d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) AS [GP], '
    SET @sql = @sql + ' CASE WHEN dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money,((dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, d.Quantity, d.Unit_Cost)) / dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) * 100)) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Act GP%], '
    SET @sql = @sql + ' CONVERT(money, p.Standard_Cost) AS [StdUnitCost], '
    SET @sql = @sql + ' CONVERT(money, p.Standard_Cost * d.Quantity) AS [TotalStdCost], '
    SET @sql = @sql + ' CONVERT(money, (d.Extended_Amount - d.Tax_Amount) - (d.Quantity * p.Standard_Cost)) AS [TotalStdGP], '
    SET @sql = @sql + ' CASE WHEN dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money,((dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, d.Quantity, p.Standard_Cost)) / dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) * 100)) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Std GP%], '
    SET @sql = @sql + ' u.UserName AS [User] '
    
    SET @sql = @sql + ' FROM AS_Transaction_Details d '
    SET @sql = @sql + '      INNER JOIN AS_Transactions h '
    SET @sql = @sql + '          ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '      INNER JOIN AP_Products p '
    SET @sql = @sql + '          ON d.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + '      INNER JOIN AC_Customers c '
    SET @sql = @sql + '          ON c.AC_Customers_ID = h.AC_Customers_ID '
    SET @sql = @sql + '      LEFT JOIN Sys_AW_Transaction_Types tt '
    SET @sql = @sql + '          ON h.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID '
    SET @sql = @sql + '      LEFT JOIN AW_Users u '
    SET @sql = @sql + '          ON h.User_ID = u.AW_Users_ID '


    IF @Option = 'Type'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Types o ' +
            '        ON p.Lup_AP_Product_Types_ID = o.Lup_AP_Product_Types_ID '
    ELSE
    IF @Option = 'Group'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Groups o ' +
            '        ON p.Lup_AP_Product_Groups_ID = o.Lup_AP_Product_Groups_ID '
    ELSE
    IF @Option = 'Department'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Departments o ' +
            '        ON p.Lup_AP_Product_Departments_ID = o.Lup_AP_Product_Departments_ID '
    ELSE
    IF @Option = 'Supplier'
        SET @sql = @sql +
            '    LEFT JOIN AO_Suppliers o ' +
            '        ON p.Default_Supplier_ID = o.AO_Suppliers_ID '
    ELSE
    IF @Option = 'Manufacturer'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Manufacturers o ' +
            '        ON p.Lup_AP_Product_Manufacturers_ID = o.Lup_AP_Product_Manufacturers_ID '
    ELSE
    IF @Option = 'Cashier'
        SET @sql = @sql +
            '    LEFT JOIN AW_Users o ' +
            '        ON h.User_ID = o.AW_Users_ID '
    ELSE
    IF @Option = 'Sales Area'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AC_Sales_Areas o ' +
            '        ON c.Lup_AC_Sales_Areas_ID = o.Lup_AC_Sales_Areas_ID '
    ELSE
    IF @Option = 'Sales Person'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AS_Reps o ' +
            '        ON c.Lup_AS_Reps_ID = o.Lup_AS_Reps_ID '
    IF @Option = 'Salesperson'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AS_Reps o ' +
            '        ON c.Lup_AS_Reps_ID = o.Lup_AS_Reps_ID '

    SET @sql = @sql +
        ' WHERE d.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND ' +
        '      (h.Day_End >= ''' + CONVERT(varchar(30), @DayEndFromDate) + ''' AND ' +
        '       h.Day_End <= ''' + CONVERT(varchar(30), @DayEndToDate) + ''') AND ' +
        '      (h.Sys_AW_Transaction_Types_ID = 3 OR ' +
        '       h.Sys_AW_Transaction_Types_ID = 4) AND '

    SET @sql = @sql + ' CASE WHEN dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money,((dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, d.Quantity, d.Unit_Cost)) / dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) * 100)) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END <= ' + CONVERT(varchar(30), @GPThreshold) + ' '


    IF @AcctType = 2
        BEGIN
            SET @sql = @sql + '    AND c.Sys_AC_Account_Types_ID = 3 '
        END

    ELSE
    IF @AcctType = 3
        BEGIN
            SET @sql = @sql + '    AND c.Sys_AC_Account_Types_ID <> 3 '
        END



    SET @sql = @sql +
        ' ORDER BY [Filter], [Product], [DocNo], [TranDate] '

--PRINT @sql

EXEC (@sql)
GO

--9 Update_AP_Products_Audit_User_ID
UPDATE AP_Products_Audit
SET [User_ID] = -1
WHERE [User_ID] IS NULL
Go

--10 fn_AP_BFWD_Inventory_On_Hand
IF EXISTS
(
	SELECT 1
	FROM dbo.sysobjects 
	WHERE id = object_id(N'[dbo].[fn_AP_BFWD_Inventory_On_Hand]')
	AND xtype in (N'FN', N'IF', N'TF')
)
DROP FUNCTION [dbo].[fn_AP_BFWD_Inventory_On_Hand]
GO
----------------------------------------------------------------------------
--Description   :dbo.fn_AP_BFWD_Inventory_On_Hand
--Purpose       :Retrieves Opening Inventory On Hand BEFORE a date
--Parameters    :
--Date          :2004/10/09
--Authors       :TB
--Version       :1.0.0
--MODS          :
--RL	V6.0	2014-12-05	:Added transaction type 23 - Stock Transfer to sales query
----------------------------------------------------------------------------

CREATE FUNCTION [dbo].[fn_AP_BFWD_Inventory_On_Hand]
    (
        @ProductID int,
        @OpeningDate datetime
    )

RETURNS float

AS

    BEGIN

        DECLARE @GRV float,
                @ADJ float,
                @SALES float,
                @BFWD float

    -------------------------------------------------------------------------------
    -- GOODS RECEIVED
    -------------------------------------------------------------------------------
        SELECT @GRV = ISNULL(SUM(Qty), 0)
        FROM AO_GRV_Details
        WHERE AP_Products_ID = @ProductID AND
              Date_Captured < @OpeningDate AND
              ISNULL(Qty, 0) <> 0
    -------------------------------------------------------------------------------
    -- ADJUSTMENTS
    -------------------------------------------------------------------------------
        SELECT @ADJ = ISNULL(SUM(ISNULL(New_On_Hand, 0) - ISNULL(Previous_On_Hand, 0)), 0)
        FROM AP_Inventory_Adjustments
        WHERE AP_Products_ID = @ProductID AND
              Date_Captured < @OpeningDate AND
             (Sys_AP_Adjustment_Types_ID = 1 OR
              Sys_AP_Adjustment_Types_ID = 6) AND
              ISNULL(New_On_Hand, 0) - ISNULL(Previous_On_Hand, 0) <> 0
    -------------------------------------------------------------------------------
    -- SALES
    -------------------------------------------------------------------------------
        SELECT @SALES = ISNULL(SUM(d.Quantity), 0)
        FROM AS_Transaction_Details d
            INNER JOIN AS_Transactions h
                ON d.AS_Transactions_ID = h.AS_Transactions_ID
        WHERE d.AP_Products_ID = @ProductID AND
              h.Date_Captured < @OpeningDate AND
             (h.Sys_AW_Transaction_Types_ID = 3 OR
              h.Sys_AW_Transaction_Types_ID = 4 OR
              h.Sys_AW_Transaction_Types_ID = 23) AND
              ISNULL(d.Quantity, 0) <> 0
    -------------------------------------------------------------------------------


        SET @BFWD = @GRV + @ADJ - @SALES


        RETURN(@BFWD)

    
    END
GO

--11 sp_AP_Clear_Product_Catalog_Non_Stock
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AP_Clear_Product_Catalog_Non_Stock]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AP_Clear_Product_Catalog_Non_Stock]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---------------------------------------------------------------------------------
--Description   :sp_AP_Clear_Product_Catalog_Non_Stock
--Purpose       :CLEAR On Hand for all Non-Stock Products in Catalog
--Functionality :
--Date          :2009/04/30
--Authors       :TB
--MODS          :
--RL	V6.0	2014-12-05	:Added Product Audit Trail
---------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AP_Clear_Product_Catalog_Non_Stock]
    (
        @CompanyID int,
        @UserID int
    )

AS

SET NOCOUNT ON

    DECLARE @ProductID int,
            @ProductCode varchar(20),
    		@User_Name varchar(40),
            @LastCost money,
            @AverageCost money,
            @StandardCost money,
            @OnHand decimal(9,3),
            @AdjustmentType tinyint,
            @AdjustDate datetime,
            @Note varchar(70),
            @RetCode int


	SELECT @User_Name = ISNULL(FirstName, '')
	FROM AW_Users
	WHERE AW_Users_ID = @UserID


    SET @RetCode = 0
    SET @AdjustmentType = 1    --Intialize as 'Adjustment' type
    SET @AdjustDate = getdate()
    SET @Note = LEFT('Non-Stock Qty Adjust by ' + @User_Name, 70)


    ------------------------------------------------------------------------------
    --> ZERO the Stock On Hand
    ------------------------------------------------------------------------------
	DECLARE Product_Cursor CURSOR FOR
        (
            SELECT AP_Products_ID,
                   Product_Code,
                   Last_Cost,
                   Average_Cost,
                   On_Hand
            FROM AP_Products
            WHERE AW_User_Companies_ID =  @CompanyID AND
                  Slu_AW_YesNo_Non_Stock_Item = 1 AND
                  On_Hand <> 0
        )

	OPEN Product_Cursor

    	FETCH NEXT FROM Product_Cursor 
    	INTO
            @ProductID,
            @ProductCode,
            @LastCost,
            @AverageCost,
        	@OnHand


    	WHILE @@FETCH_STATUS = 0
    	BEGIN


            UPDATE AP_Products
            SET On_Hand = 0,
            [User_ID] = @UserID            
            WHERE AP_Products_ID =  @ProductID


        	INSERT INTO AP_Inventory_Adjustments
                (
        			AP_Products_ID,
                    Sys_AP_Adjustment_Types_ID,
        			Previous_Last_Cost,
                    Previous_Average_Cost,
        			Previous_On_Hand,
        			Previous_Job_Reserved,
        			Previous_Sales_Order_Reserved,
        			Previous_Quote_Reserved,
        			New_Last_Cost,
                    New_Average_Cost,
        			New_On_Hand,
        			New_Job_Reserved,
        			New_Sales_Order_Reserved,
        			New_Quote_Reserved,
        			Note,
        			Date_Captured,
        			[User_ID],
        			AW_User_Companies_ID
                )
        	VALUES
                (
                    @ProductID,
                    @AdjustmentType,
        			@LastCost,
                    @AverageCost,
        			@OnHand,
        		    0,
        			0,
        		    0,
        			@LastCost,
                    @AverageCost,
        			0,
        			0 ,
        			0,
        			0,
        			@Note,
        			@AdjustDate,
        			@UserID,
        			@CompanyID
                )

            SELECT @RetCode = SCOPE_IDENTITY()
    
    
        	FETCH NEXT FROM Product_Cursor 
        	INTO
                @ProductID,
                @ProductCode,
                @LastCost,
                @AverageCost,
            	@OnHand

        END
    	
	CLOSE Product_Cursor

	DEALLOCATE Product_Cursor


RETURN @RetCode


SET NOCOUNT OFF
GO

--12 sp_AS_Filter_Enterprise_Sales
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_Filter_Enterprise_Sales]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_Filter_Enterprise_Sales]
GO
--sp_AS_Filter_Enterprise_Sales 1, '2007/03/01 12:00:01 AM ', '2007/03/12 11:59:59 PM', 'Dunlop', '', '', '', '', '', 1, 1 
-------------------------------------------------------------------------------
--Description   :sp_AS_Filter_Enterprise_Sales
--Purpose       :FILTER Enterprise Sales
--Functionality :Uses filter DESCRIPTIONS
--Date          :2007/03/12
--Authors       :TB
--MODS:         :
--2004.4.8      :03/07/10 - Added @ExclInterCo parameter
--RL	V6.0	2014-12-08 :Removed Filter check. I can't see any reason to force a Filter
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_Filter_Enterprise_Sales]
	(
        @CompanyID int,
        @StartDate datetime,
        @EndDate datetime,
        @Manuf varchar(50) = '',
        @Type varchar(50) = '',
        @Group varchar(50) = '',
        @Department varchar(50) = '',
        @Supplier varchar(50) = '',
        @Location varchar(50) = '',
        @FetchType tinyint,
        @ExclInterCo tinyint,
        @Sort tinyint,
        @NonStock tinyint
	)

AS

SET NOCOUNT ON

	DECLARE @ManufID int,
            @TypeID int,
            @GroupID int,
            @DepartmentID int,
            @SupplierID int,
            @LocationID int,
            @Filter varchar(4000),
            @sql varchar(8000),
            @RetCode int


	SET @Filter = ''
    SET @sql = ''


--> Manufacturer
	IF @Manuf <> ''
		BEGIN
            --> Get Manufacturer ID
            SELECT TOP 1 @ManufID = Lup_AP_Product_Manufacturers_ID
            FROM Lup_AP_Product_Manufacturers
            WHERE AW_User_Companies_ID = @CompanyID AND
                 [Description] = @Manuf AND
                 Slu_AW_Active_ID = 1
        
            IF @ManufID IS NULL OR @ManufID = 0
                BEGIN
                    SET @Manuf = ''
                END
        END

--> Supplier
	IF @Supplier <> ''
		BEGIN
            --> Get Supplier ID
            SELECT TOP 1 @SupplierID = AO_Suppliers_ID
            FROM AO_Suppliers
            WHERE AW_User_Companies_ID = @CompanyID AND
                  Supplier_Name = @Supplier AND
                  Slu_AW_Active_ID = 1
        
            IF @SupplierID IS NULL OR @SupplierID = 0
                BEGIN
                    SET @Supplier = ''
                END
        END

--> Type
	IF @Type <> ''
		BEGIN
            --> Get Product Type ID
            SELECT TOP 1 @TypeID = Lup_AP_Product_Types_ID
            FROM Lup_AP_Product_Types
            WHERE AW_User_Companies_ID = @CompanyID AND
                 [Description] = @Type AND
                  Slu_AW_Active_ID = 1
        
            IF @TypeID IS NULL OR @TypeID = 0
                BEGIN
                    SET @Type = ''
                END
        END

--> Group
	IF @Group <> ''
		BEGIN
            --> Get Product Group ID
            SELECT TOP 1 @GroupID = Lup_AP_Product_Groups_ID
            FROM Lup_AP_Product_Groups
            WHERE AW_User_Companies_ID = @CompanyID AND
                 [Description] = @Group AND
                  Slu_AW_Active_ID = 1
        
            IF @GroupID IS NULL OR @GroupID = 0
                BEGIN
                    SET @Group = ''
                END
        END

--> Department
	IF @Department <> ''
		BEGIN
            --> Get Product Department ID
            SELECT TOP 1 @DepartmentID = Lup_AP_Product_Departments_ID
            FROM Lup_AP_Product_Departments
            WHERE AW_User_Companies_ID = @CompanyID AND
                 [Description] = @Department AND
                  Slu_AW_Active_ID = 1
        
            IF @DepartmentID IS NULL OR @DepartmentID = 0
                BEGIN
                    SET @Department = ''
                END
        END

--> Location
	IF @Location <> ''
		BEGIN
            --> Get Product Location ID
            SELECT TOP 1 @LocationID = Lup_AP_Product_Locations_ID
            FROM Lup_AP_Product_Locations
            WHERE AW_User_Companies_ID = @CompanyID AND
                 [Description] = @Location AND
                  Slu_AW_Active_ID = 1
        
            IF @LocationID IS NULL OR @LocationID = 0
                BEGIN
                    SET @Location = ''
                END
        END



--> Manufacturer
	IF @Manuf <> ''
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Manufacturers_ID = ' +
                                convert(varchar(20), @ManufID)
			ELSE
				SET @Filter = @Filter + ' AND p.Lup_AP_Product_Manufacturers_ID = ' +
                                convert(varchar(20), @ManufID)
		END
--> Type
	IF @Type <> ''
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Types_ID = ' +
                                convert(varchar(20), @TypeID)
			ELSE
				SET @Filter = @Filter + ' AND p.Lup_AP_Product_Types_ID = ' +
                                convert(varchar(20), @TypeID)
		END
--> Group
	IF @Group <> ''
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Groups_ID = ' +
                                convert(varchar(20), @GroupID)
			ELSE
				SET @Filter = @Filter + ' AND p.Lup_AP_Product_Groups_ID = ' +
                                convert(varchar(20), @GroupID)
		END
--> Department
	IF @Department <> ''
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Departments_ID = ' +
                                convert(varchar(20), @DepartmentID)
			ELSE
				SET @Filter = @Filter + ' AND p.Lup_AP_Product_Departments_ID = ' +
                                convert(varchar(20), @DepartmentID)
		END
--> Supplier
	IF @Supplier <> ''
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE ' + ' p.Default_Supplier_ID = ' +
                                convert(varchar(20), @SupplierID)
			ELSE
				SET @Filter = @Filter + ' AND p.Default_Supplier_ID = ' +
                                convert(varchar(20), @SupplierID)
		END
--> Location
	IF @Location <> ''
		BEGIN
			IF @Filter = ''
				SET @Filter = ' WHERE ' + ' p.Lup_AP_Product_Locations_ID = ' +
                                convert(varchar(20), @LocationID)
			ELSE
				SET @Filter = @Filter + ' AND p.Lup_AP_Product_Locations_ID = ' +
                                convert(varchar(20), @LocationID)
		END


--> Company
	IF @Filter = ''
		SET @Filter = ' WHERE ' + ' p.AW_User_Companies_ID = ' +
                        convert(varchar(20), @CompanyID)
	ELSE
		SET @Filter = @Filter + ' AND p.AW_User_Companies_ID = ' +
                        convert(varchar(20), @CompanyID)


    SET @sql = ' SELECT '
    SET @sql = @sql + ' p.Description AS [Product], '
    SET @sql = @sql + ' p.Product_Code AS [Code], '
    SET @sql = @sql + ' p.Pack_Size AS [Size], '

    IF @FetchType = 0
        BEGIN
            SET @sql = @sql + ' ISNULL(td.Quantity, 0) AS [Value], '
        END

    ELSE
    IF @FetchType = 1
        BEGIN
            SET @sql = @sql + ' ISNULL(td.Extended_Amount, 0) - ISNULL(Tax_Amount, 0) AS [Value], '
        END

    SET @sql = @sql + ' m.[Description] AS [Manuf], '
    SET @sql = @sql + ' t.[Description] AS [Type], '
    SET @sql = @sql + ' g.[Description] AS [Group], '
    SET @sql = @sql + ' d.[Description] AS [Department], '
    SET @sql = @sql + ' s.[Supplier_Name] AS [Supplier], '
    SET @sql = @sql + ' l.[Description] AS [Location] '


    SET @sql = @sql + ' FROM AS_Transactions th '
    SET @sql = @sql + ' LEFT JOIN AS_Transaction_Details td '
    SET @sql = @sql + '     ON td.AS_Transactions_ID = th.AS_Transactions_ID '


    IF @ExclInterCo = 1
        BEGIN
            SET @sql = @sql + ' INNER JOIN AC_Customers c '
            SET @sql = @sql + '     ON th.AC_Customers_ID = c.AC_Customers_ID '
        END


    SET @sql = @sql + ' LEFT JOIN AP_Products p '
    SET @sql = @sql + '     ON p.AP_Products_ID = td.AP_Products_ID '
    SET @sql = @sql + ' LEFT JOIN Lup_AP_Product_Manufacturers m '
    SET @sql = @sql + '     ON p.Lup_AP_Product_Manufacturers_ID = m.Lup_AP_Product_Manufacturers_ID '
    SET @sql = @sql + ' LEFT JOIN Lup_AP_Product_Types t '
    SET @sql = @sql + '     ON p.Lup_AP_Product_Types_ID = t.Lup_AP_Product_Types_ID '
    SET @sql = @sql + ' LEFT JOIN Lup_AP_Product_Groups g '
    SET @sql = @sql + '     ON p.Lup_AP_Product_Groups_ID = g.Lup_AP_Product_Groups_ID '
    SET @sql = @sql + ' LEFT JOIN Lup_AP_Product_Departments d '
    SET @sql = @sql + '     ON p.Lup_AP_Product_Departments_ID = d.Lup_AP_Product_Departments_ID '
    SET @sql = @sql + ' LEFT JOIN AO_Suppliers s '
    SET @sql = @sql + '     ON p.Default_Supplier_ID = s.AO_Suppliers_ID '
    SET @sql = @sql + ' LEFT JOIN Lup_AP_Product_Locations l '
    SET @sql = @sql + '     ON p.Lup_AP_Product_Locations_ID = l.Lup_AP_Product_Locations_ID '


    SET @sql = @sql + @Filter

    SET @sql = @sql + ' AND  th.Transaction_Date >= ' + '''' + CONVERT(varchar(30), @StartDate) + '''' + ' '
    SET @sql = @sql + ' AND  th.Transaction_Date <= ' + '''' + CONVERT(varchar(30), @EndDate) + '''' + ' '
    SET @sql = @sql + ' AND (th.Sys_AW_Transaction_Types_ID = 3  '
    SET @sql = @sql + '  OR  th.Sys_AW_Transaction_Types_ID = 4) '


    IF @ExclInterCo = 1
        BEGIN
            SET @sql = @sql + ' AND c.Sys_AC_Account_Types_ID <> 3 '
        END


    IF @NonStock = 1
        BEGIN
            SET @sql = @sql + ' AND p.Slu_AW_YesNo_Non_Stock_Item <> 1 '
        END


    IF @Sort = 1
        BEGIN
            SET @sql = @sql + ' ORDER BY [Manuf], [Type], [Group], [Department], [Supplier], [Location], [Code] '
        END
    ELSE
        BEGIN
            SET @sql = @sql + ' ORDER BY [Manuf], [Type], [Group], [Department], [Supplier], [Location], [Product] '
        END

	--V6.0 Removed check. I can't see any reason to force a Filter
    ----------------------------------
    -- If NO FILTERS FOUND then EXIT    
    ----------------------------------
    --IF @Manuf = '' AND
    --   @Type = '' AND
    --   @Group = '' AND
    --   @Department = '' AND
    --   @Supplier = '' AND
    --   @Location = ''

    --    RETURN
    ----------------------------------


--PRINT @sql

EXEC (@sql)



SET NOCOUNT OFF	
GO

--13 sp_AW_9960
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AW_9960]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AW_9960]
GO
-------------------------------------------------------------------------------
--Description   :sp_AW_9960
--Purpose       :Wipe all CUSTOMER Transaction tables
--              :
--Parameters    :
--Date          :2002/02/11
--Authors       :TB
--MODS          :
--2004.5.5      :10/11/11 - Refreshed with latest table defs - 2004.5.5
--2015.6.0      :2015-02-02 - Refreshed with latest table defs - 2015.6.0
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AW_9960]

AS

SET NOCOUNT ON

    DECLARE @ReturnValue bit

    SET @ReturnValue = 0


    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_AS_Transactions_AW_Comments]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
    ALTER TABLE [dbo].[AS_Transactions] DROP CONSTRAINT FK_AS_Transactions_AW_Comments

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_Assets]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_Assets]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_Contract_Prices]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_Contract_Prices]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_Enterprise_Ageing_Temp]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_Enterprise_Ageing_Temp]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_Enterprise_Customer_Ageing]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_Enterprise_Customer_Ageing]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_History_Associates]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_History_Associates]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_History_Auditors]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_History_Auditors]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_History_Balance_Sheets]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_History_Balance_Sheets]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_History_Bankers]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_History_Bankers]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_History_Bonds]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_History_Bonds]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_History_Credit_Limits]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_History_Credit_Limits]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_History_Default]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_History_Default]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_History_ITCScores]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_History_ITCScores]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_History_Income_Statements]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_History_Income_Statements]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_History_Info_Reports]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_History_Info_Reports]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_History_Judgements]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_History_Judgements]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_History_KIScores]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_History_KIScores]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_History_Motion_Roll]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_History_Motion_Roll]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_History_Notarial_Bonds]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_History_Notarial_Bonds]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_History_Principal_Properties]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_History_Principal_Properties]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_History_Principals]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_History_Principals]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_History_Properties]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_History_Properties]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_History_RD_Cheques]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_History_RD_Cheques]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_History_Ratings]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_History_Ratings]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_History_Shareholders]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_History_Shareholders]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_History_Status]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_History_Status]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_History_Trade_References]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_History_Trade_References]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_Periodic_Billing_Detail]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_Periodic_Billing_Detail]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_Periodic_Billing_Detail_Splits]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_Periodic_Billing_Detail_Splits]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_Periodic_Billing_Header]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_Periodic_Billing_Header]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_Statement_Details]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_Statement_Details]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_Statement_Details_Temp]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_Statement_Details_Temp]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_Statements]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_Statements]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AC_Statements_Temp]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AC_Statements_Temp]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AW_Comments]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AW_Comments]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Log_AC_Master_Controller]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[Log_AC_Master_Controller]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Log_AC_Messages]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[Log_AC_Messages]

    
    CREATE TABLE [dbo].[AC_Assets] (
    	[AC_Assets_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NULL ,
    	[Make] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Model] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Model_Year] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Lup_AC_Asset_Types_ID] [smallint] NULL ,
    	[Reg_No] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Engine_No] [varchar] (24) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Chassis_No] [varchar] (24) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[VIN_No] [varchar] (24) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Mileage] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Mileage_Date] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Tyre_Size] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Tyre_Qty] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[AS_Transactions_ID] [int] NULL,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL    	
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_Contract_Prices] (
    	[AC_Contract_Prices_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NULL ,
    	[AP_Products_ID] [int] NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Product_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Start_Date] [datetime] NULL ,
    	[End_Date] [datetime] NULL ,
    	[Pack_Size] [decimal](9, 3) NULL ,
    	[Unit_Price] [money] NULL ,
    	[Discount_Perc] [decimal](9, 3) NULL ,
    	[Discount_Amount] [money] NULL ,
    	[MinSaleQty] [decimal](9, 3) NULL,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NOT NULL    	
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_Enterprise_Ageing_Temp] (
    	[AC_Enterprise_Ageing_Temp_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Filter] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[AC_Customers_ID] [int] NULL ,
    	[FullName] [varchar] (92) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Customer_Number] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Amount] [money] NULL ,
    	[Payment] [money] NULL ,
    	[Account_Balance] [money] NULL ,
    	[Current] [money] NULL ,
    	[30Days] [money] NULL ,
    	[60Days] [money] NULL ,
    	[90Days] [money] NULL ,
    	[120Days] [money] NULL ,
    	[150Days] [money] NULL ,
    	[180+Days] [money] NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_Enterprise_Customer_Ageing] (
    	[AC_Enterprise_Customer_Ageing_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[CompanyID] [int] NULL ,
    	[SourceDB] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Filter] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Customer] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[CustNo] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Total] [money] NULL ,
    	[Balance] [money] NULL ,
    	[Days0] [money] NULL ,
    	[Days30] [money] NULL ,
    	[Days60] [money] NULL ,
    	[Days90] [money] NULL ,
    	[Days120] [money] NULL ,
    	[Days150] [money] NULL ,
    	[Days180] [money] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_History_Associates] (
    	[AC_History_Associates_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NOT NULL ,
    	[Associate_Name] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Slu_AC_Association_Types_ID] [smallint] NULL ,
    	[Shareholding_Percentage] [decimal](7, 2) NULL ,
    	[Slu_AC_Shareholding_Types_ID] [smallint] NULL ,
    	[Date_Acquired] [datetime] NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_History_Auditors] (
    	[AC_History_Auditors_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NOT NULL ,
    	[Firm_Name] [varchar] (120) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Audit_Manager] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Registration_Date] [datetime] NULL ,
    	[Slu_AC_Profession_Types_ID] [smallint] NULL ,
    	[Slu_AC_Auditor_Rankings_ID] [smallint] NULL ,
    	[Profession_Number] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Profession_Date_Changed] [datetime] NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_History_Balance_Sheets] (
    	[AC_History_Balance_Sheets_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NOT NULL ,
    	[Statement_Date] [datetime] NULL ,
    	[Property_Plant_and_Equipment] [money] NULL ,
    	[Investment_Property] [money] NULL ,
    	[Investments_and_Loans] [money] NULL ,
    	[Investments_and_Finance_Leases] [money] NULL ,
    	[Forward_Exchange_Contract_Asset] [money] NULL ,
    	[Inventories] [money] NULL ,
    	[Trade_and_Other_Receivables] [money] NULL ,
    	[Prepayments] [money] NULL ,
    	[Cash_and_Cash_Equivalents] [money] NULL ,
    	[Issued_Capital] [money] NULL ,
    	[Reserves] [money] NULL ,
    	[Accumulated_Profit_Loss] [money] NULL ,
    	[Interest_Bearing_Borrowings] [money] NULL ,
    	[Deferred_Taxation] [money] NULL ,
    	[Retirement_Benefit_Obligations] [money] NULL ,
    	[Trade_and_Other_Payables] [money] NULL ,
    	[Taxation] [money] NULL ,
    	[Dividend_Declared] [money] NULL ,
    	[Bank_Overdraft] [money] NULL ,
    	[Overdraft_Facility] [money] NULL ,
    	[Current_portion_of_Interest_Bearing_Borrowings] [money] NULL ,
    	[Warranty_Provision] [money] NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_History_Bankers] (
    	[AC_History_Bankers_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NOT NULL ,
    	[Slu_AW_Banks_ID] [smallint] NULL ,
    	[Bank_Branch] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Bank_Branch_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Account_Name] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Account_Number] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Slu_AC_Bank_Codes_ID] [tinyint] NULL ,
    	[Bank_Code_Amount] [money] NULL ,
    	[Slu_AW_Credit_Terms_ID] [tinyint] NULL ,
    	[Banker_Comments] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Opened] [datetime] NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_History_Bonds] (
    	[AC_History_Bonds_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NOT NULL ,
    	[Bond_Account_Number] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Bond_Holder] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Bond_Amount] [money] NULL ,
    	[Slu_AC_Bond_Types_ID] [smallint] NULL ,
    	[Repayment_Period] [decimal](3, 0) NULL ,
    	[Repayment_Amount] [money] NULL ,
    	[Effective_Date] [datetime] NULL ,
    	[Date_Registered] [datetime] NULL ,
    	[Collateral_Provider] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_History_Credit_Limits] (
    	[AC_History_Credit_Limits_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NOT NULL ,
    	[Slu_AW_Credit_Terms_ID] [tinyint] NULL ,
    	[Sys_AC_Credit_Term_Types_ID] [int] NULL ,
    	[New_Limit] [money] NULL ,
    	[Limit_Reason] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Changed] [datetime] NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_History_Default] (
    	[AC_History_Default_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NOT NULL ,
    	[Slu_AC_Adverse_Reasons_ID] [int] NULL ,
    	[Adverse_Source] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Reported] [datetime] NULL ,
    	[Dispute_Amount] [money] NULL ,
    	[Days_Overdue] [int] NULL ,
    	[Adverse_Comments] [varchar] (500) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_History_ITCScores] (
    	[AC_History_ITCScores_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NOT NULL ,
    	[Slu_AC_ITC_Scores_ID] [smallint] NULL ,
    	[Notes] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,    	
    	[Effective_Date] [datetime] NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_History_Income_Statements] (
    	[AC_History_Income_Statements_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NOT NULL ,
    	[Statement_Date] [datetime] NULL ,
    	[Revenue] [money] NULL ,
    	[Cost_of_Sales] [money] NULL ,
    	[Other_Income] [money] NULL ,
    	[Fleet_Rental] [money] NULL ,
    	[Distribution_Expenses] [money] NULL ,
    	[Auditors_Remuneration] [money] NULL ,
    	[Depreciation] [money] NULL ,
    	[Prepayments] [money] NULL ,
    	[Profit_Loss_on_disposal_of_Assets] [money] NULL ,
    	[Permanent_decline_in_value_of_Investment_Property] [money] NULL ,
    	[Fees_for_Services] [money] NULL ,
    	[Rental_on_Operating_Leases] [money] NULL ,
    	[Forex_Gains_Losses] [money] NULL ,
    	[Staff_Costs] [money] NULL ,
    	[Other_Long_Term_Employee_Benefits] [money] NULL ,
    	[Directors_Emoluments] [money] NULL ,
    	[Other_Expenses] [money] NULL ,
    	[Financing_Costs] [money] NULL ,
    	[Financing_Costs_Capitalized] [money] NULL ,
    	[Taxation] [money] NULL ,
    	[Extraordinary_Items] [money] NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_History_Info_Reports] (
    	[AC_History_Info_Reports_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NOT NULL ,
    	[Slu_AW_Info_Report_Types_ID] [smallint] NULL ,
    	[Report_Date] [datetime] NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_History_Judgements] (
    	[AC_History_Judgements_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NOT NULL ,
    	[Slu_AW_Nature_Of_Action_ID] [smallint] NULL ,
    	[Slu_AW_Courts_ID] [smallint] NULL ,
    	[Defendant_Name] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Plaintiff_Name] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Judgement_Amount] [money] NULL ,
    	[Case_Number] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Of_Judgement] [datetime] NULL ,
    	[Default_Judgement] [bit] NULL ,
    	[Date_Rescinded] [datetime] NULL ,
    	[Rescindment_Reason] [varchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Abandoned] [datetime] NULL ,
    	[Abandonment_Reason] [varchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_History_KIScores] (
    	[AC_History_KIScores_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NOT NULL ,
    	[Slu_AC_KI_Scores_ID] [smallint] NULL ,
    	[Notes] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Effective_Date] [datetime] NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_History_Motion_Roll] (
    	[AC_History_Motion_Roll_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NOT NULL ,
    	[Slu_AW_Nature_Of_Action_ID] [smallint] NULL ,
    	[Slu_AW_Lawsuit_Types_ID] [smallint] NULL ,
    	[Slu_AW_Courts_ID] [smallint] NULL ,
    	[Respondent_Name] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Applicant] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Application_Amount] [money] NULL ,
    	[Case_Number] [varchar] (16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Item_Number] [tinyint] NULL ,
    	[Hearing_Date] [datetime] NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_History_Notarial_Bonds] (
    	[AC_History_Notarial_Bonds_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NOT NULL ,
    	[Bond_Holder] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Bond_Amount] [money] NULL ,
    	[Effective_date] [datetime] NULL ,
    	[Date_Registered] [datetime] NULL ,
    	[Collateral_Provider] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Slu_AC_Bond_Types_ID] [smallint] NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_History_Principal_Properties] (
    	[AC_History_Principal_Properties_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NOT NULL ,
    	[AC_History_Principals_ID] [int] NULL ,
    	[Description] [varchar] (110) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Registered_Owner] [varchar] (110) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Title_Deed_Number] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Property_Size] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Purchased] [datetime] NULL ,
    	[Purchase_Price] [money] NULL ,
    	[Address1] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Address2] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Suburb] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[City] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Post_Code] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_History_Principals] (
    	[AC_History_Principals_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NOT NULL ,
    	[Name] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[ID_Number] [varchar] (16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Slu_AC_Principal_Types_ID] [smallint] NULL ,
    	[Home_Tel_No] [varchar] (16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Cell_No] [varchar] (16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[E_Mail] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Home_Address] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Appointed] [datetime] NULL ,
    	[Date_Terminated] [datetime] NULL ,
    	[Primary_Function] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Principal_Comments] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Status_Ind] [varchar] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Status_Date] [datetime] NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_History_Properties] (
    	[AC_History_Properties_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NOT NULL ,
    	[Slu_AC_Bond_Types_ID] [smallint] NULL ,
    	[Description] [varchar] (110) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Title_Deed_Number] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Registered_Owner] [varchar] (110) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Property_Size] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Purchased] [datetime] NULL ,
    	[Purchase_Price] [money] NULL ,
    	[Address1] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Address2] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Suburb] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[City] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Post_Code] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_History_RD_Cheques] (
    	[AC_History_RD_Cheques_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NOT NULL ,
    	[Date_Reported] [datetime] NULL ,
    	[Cheque_Amount] [money] NULL ,
    	[Comments] [varchar] (500) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_History_Ratings] (
    	[AC_History_Ratings_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NOT NULL ,
    	[Slu_AC_Ratings_ID] [smallint] NULL ,
    	[Rating_Notes] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Effective_Date] [datetime] NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_History_Shareholders] (
    	[AC_History_Shareholders_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NOT NULL ,
    	[Shareholder_Name] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Interest_Percent] [decimal](7, 2) NULL ,
    	[Number_Of_Shares] [int] NULL ,
    	[Slu_AC_Shareholding_Types_ID] [smallint] NULL ,
    	[Members_Contribution] [money] NULL ,
    	[Par_Value_Of_Holding] [money] NULL ,
    	[Estimated_Valuation] [money] NULL ,
    	[Controlling_Shareholder] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Parent_Company] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Holding_Company] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_History_Status] (
    	[AC_History_Status_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NOT NULL ,
    	[Sys_AC_Account_Status_ID] [smallint] NULL ,
    	[Status_Reason] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Changed] [datetime] NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_History_Trade_References] (
    	[AC_History_Trade_References_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NOT NULL ,
    	[Slu_AC_Security_Types_ID] [smallint] NULL ,
    	[Date_of_Reference] [datetime] NULL ,
    	[Supplier_Name] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Contact_Name] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Contact_Position] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Telephone_Number] [varchar] (16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Fax_Number] [varchar] (16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Period_Known] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Average_per_Month] [money] NULL ,
    	[Reference_Comments] [varchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Highest_Amount] [money] NULL ,
    	[Account_Limit] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Terms_Given] [smallint] NULL ,
    	[Terms_Taken] [smallint] NULL ,
    	[Current_Balance] [money] NULL ,
    	[Days_30] [money] NULL ,
    	[Days_60] [money] NULL ,
    	[Days_90] [money] NULL ,
    	[Days_120] [money] NULL ,
    	[Days_150] [money] NULL ,
    	[Days_180] [money] NULL ,
    	[Past_Due_Amount] [money] NULL ,
    	[Limit_Of_Guarantee] [money] NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_Periodic_Billing_Detail] (
    	[AC_Periodic_Billing_Detail_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Periodic_Billing_Header_ID] [int] NOT NULL ,
    	[Post] [bit] NOT NULL ,
    	[Transaction_Date] [datetime] NOT NULL ,
    	[Ref_No] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
    	[AC_Customers_ID] [int] NOT NULL ,
    	[Sys_AW_Transaction_Types_ID] [tinyint] NOT NULL ,
    	[Sys_AW_Tax_Methods_ID] [tinyint] NOT NULL ,
    	[Amount] [money] NOT NULL ,
    	[Tax_Amount] [money] NOT NULL ,
    	[Net_Amount] [money] NOT NULL ,
    	[AB_Accounts_ID] [int] NOT NULL ,
    	[Comment] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Notes] [varchar] (250) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Email] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_Periodic_Billing_Detail_Splits] (
    	[AC_Periodic_Billing_Detail_Splits_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Periodic_Billing_Header_ID] [int] NOT NULL ,
    	[AC_Periodic_Billing_Detail_ID] [int] NOT NULL ,
    	[AP_Products_ID] [int] NOT NULL ,
    	[Quantity] [decimal](9, 3) NULL ,
    	[Unit_Price] [money] NULL ,
    	[Sys_AW_Tax_Methods_ID] [tinyint] NOT NULL ,
    	[Amount] [money] NOT NULL ,
    	[Tax_Amount] [money] NOT NULL ,
    	[Net_Amount] [money] NOT NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_Periodic_Billing_Header] (
    	[AC_Periodic_Billing_Header_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Posting_Type] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Posted] [datetime] NOT NULL ,
    	[Slu_AW_Months_ID] [tinyint] NOT NULL ,
    	[Slu_AW_Years_ID] [smallint] NOT NULL ,
    	[Import_Filename] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_Statement_Details] (
    	[AC_Statement_Details_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Statements_ID] [int] NULL ,
    	[AS_Transactions_ID] [int] NULL ,
    	[Transaction_Date] [datetime] NULL ,
    	[Sys_AW_Transaction_Types_ID] [int] NULL ,
    	[Transaction_Number] [varchar] (19) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Amount] [money] NULL ,
    	[Payment] [money] NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL     	
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_Statement_Details_Temp] (
    	[AC_Statement_Details_Temp_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Statements_Temp_ID] [int] NULL ,
    	[Transaction_Date] [datetime] NULL ,
    	[Sys_AW_Transaction_Types_ID] [int] NULL ,
    	[Transaction_Number] [varchar] (19) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Amount] [money] NULL ,
    	[Payment] [money] NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_Statements] (
    	[AC_Statements_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AW_Period_Procedures_ID] [int] NULL ,
    	[AC_Customers_ID] [int] NULL ,
    	[FullName] [varchar] (92) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Customer_Number] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Post_Address] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Post_Office] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Post_Code] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Work_Email] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Amount] [money] NULL ,
    	[Payment] [money] NULL ,
    	[Account_Balance] [money] NULL ,
    	[Current] [money] NULL ,
    	[30Days] [money] NULL ,
    	[60Days] [money] NULL ,
    	[90Days] [money] NULL ,
    	[120Days] [money] NULL ,
    	[150Days] [money] NULL ,
    	[180+Days] [money] NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AC_Statements_Temp] (
    	[AC_Statements_Temp_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AW_Period_Procedures_ID] [int] NULL ,
    	[AC_Customers_ID] [int] NULL ,
    	[FullName] [varchar] (92) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Customer_Number] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Post_Address] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Post_Office] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Post_Code] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Work_Email] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Amount] [money] NULL ,
    	[Payment] [money] NULL ,
    	[Account_Balance] [money] NULL ,
    	[Current] [money] NULL ,
    	[30Days] [money] NULL ,
    	[60Days] [money] NULL ,
    	[90Days] [money] NULL ,
    	[120Days] [money] NULL ,
    	[150Days] [money] NULL ,
    	[180+Days] [money] NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AW_Comments] (
    	[AW_Comments_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Actor_ID] [int] NULL ,
    	[Sys_AT_Actor_Types_ID] [int] NULL ,
    	[Comment] [varchar] (500) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[Log_AC_Master_Controller] (
    	[Log_AC_Master_Controller_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Actor_ID] [int] NOT NULL ,
    	[Sys_AT_Actor_Types_ID] [int] NOT NULL ,
    	[AW_Messages_ID] [int] NULL ,
    	[Message] [varchar] (500) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Sys_AC_Severity_Levels_ID] [tinyint] NULL ,
    	[Sys_AC_Message_Types_ID] [smallint] NULL ,
    	[Sys_AW_Delivery_Methods_ID] [tinyint] NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[Log_AC_Messages] (
    	[Log_AC_Messages_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NULL ,
    	[Message_Date] [datetime] NULL ,
    	[Dispatch_Date] [datetime] NULL ,
    	[User_CRM_ID] [int] NULL ,
    	[User_Controller_ID] [int] NULL ,
    	[Addressee] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Send_To] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Balance] [money] NULL ,
    	[Overdue] [money] NULL ,
    	[Credit_Terms] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Terms_Of_Sale] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Delivery_Method] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Subject] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[AW_Messages_ID] [int] NULL ,
    	[Message] [varchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Address_List] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Errors] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL 
    ) ON [PRIMARY]

    
    ALTER TABLE [dbo].[AC_History_Auditors] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AC_History_Auditors] PRIMARY KEY  CLUSTERED 
    	(
    		[AC_History_Auditors_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_History_Balance_Sheets] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AC_History_Balance_Sheets] PRIMARY KEY  CLUSTERED 
    	(
    		[AC_History_Balance_Sheets_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_History_Bankers] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AC_History_Bankers] PRIMARY KEY  CLUSTERED 
    	(
    		[AC_History_Bankers_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_History_Bonds] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AC_History_Bonds] PRIMARY KEY  CLUSTERED 
    	(
    		[AC_History_Bonds_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_History_Credit_Limits] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AC_History_Credit_Limits] PRIMARY KEY  CLUSTERED 
    	(
    		[AC_History_Credit_Limits_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_History_Default] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AC_History_Default] PRIMARY KEY  CLUSTERED 
    	(
    		[AC_History_Default_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_History_ITCScores] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AC_History_ITCScores] PRIMARY KEY  CLUSTERED 
    	(
    		[AC_History_ITCScores_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_History_Income_Statements] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AC_History_Income_Statements] PRIMARY KEY  CLUSTERED 
    	(
    		[AC_History_Income_Statements_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_History_Info_Reports] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AC_History_Info_Reports] PRIMARY KEY  CLUSTERED 
    	(
    		[AC_History_Info_Reports_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_History_KIScores] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AC_History_KIScores] PRIMARY KEY  CLUSTERED 
    	(
    		[AC_History_KIScores_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_History_Ratings] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AC_History_Ratings] PRIMARY KEY  CLUSTERED 
    	(
    		[AC_History_Ratings_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_History_Status] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AC_History_Status] PRIMARY KEY  CLUSTERED 
    	(
    		[AC_History_Status_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_History_Trade_References] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AC_History_Trade_References] PRIMARY KEY  CLUSTERED 
    	(
    		[AC_History_Trade_References_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_Periodic_Billing_Detail] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AC_Periodic_Billing_Detail] PRIMARY KEY  CLUSTERED 
    	(
    		[AC_Periodic_Billing_Detail_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_Periodic_Billing_Detail_Splits] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AC_Periodic_Billing_Detail_Splits] PRIMARY KEY  CLUSTERED 
    	(
    		[AC_Periodic_Billing_Detail_Splits_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_Periodic_Billing_Header] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AC_Periodic_Billing_Header] PRIMARY KEY  CLUSTERED 
    	(
    		[AC_Periodic_Billing_Header_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AW_Comments] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AW_Comments] PRIMARY KEY  CLUSTERED 
    	(
    		[AW_Comments_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[Log_AC_Master_Controller] WITH NOCHECK ADD 
    	CONSTRAINT [PK_Log_AC_Master_Controller] PRIMARY KEY  CLUSTERED 
    	(
    		[Log_AC_Master_Controller_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[Log_AC_Messages] WITH NOCHECK ADD 
    	CONSTRAINT [PK_Log_AC_Messages] PRIMARY KEY  CLUSTERED 
    	(
    		[Log_AC_Messages_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
     CREATE  CLUSTERED  INDEX [CI_Customer_Assets] ON [dbo].[AC_Assets]([AC_Customers_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [CI_AC_Contract_Customers_Products] ON [dbo].[AC_Contract_Prices]([AC_Customers_ID], [AP_Products_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [IX_AC_Enterprise_Ageing_Temp] ON [dbo].[AC_Enterprise_Ageing_Temp]([Filter], [FullName], [Customer_Number]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [IX_AC_Enterprise_Customer_Ageing] ON [dbo].[AC_Enterprise_Customer_Ageing]([Filter], [Customer], [CustNo]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  UNIQUE  CLUSTERED  INDEX [PK_AC_Statement_Details] ON [dbo].[AC_Statement_Details]([AC_Statement_Details_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  UNIQUE  CLUSTERED  INDEX [PK_AC_Statement_Details_Temp] ON [dbo].[AC_Statement_Details_Temp]([AC_Statement_Details_Temp_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  UNIQUE  CLUSTERED  INDEX [PK_AC_Statements_ID] ON [dbo].[AC_Statements]([AC_Statements_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  UNIQUE  CLUSTERED  INDEX [PK_AC_Statements_Temp] ON [dbo].[AC_Statements_Temp]([AC_Statements_Temp_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
    ALTER TABLE [dbo].[AC_Assets] ADD 
    	CONSTRAINT [PK_AC_Assets] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AC_Assets_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_Contract_Prices] ADD 
    	CONSTRAINT [PK_AC_Contract_Prices] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AC_Contract_Prices_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
     CREATE  INDEX [IX_Contract_Prices_Customers_ID] ON [dbo].[AC_Contract_Prices]([AC_Customers_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
    ALTER TABLE [dbo].[AC_Enterprise_Ageing_Temp] ADD 
    	CONSTRAINT [PK_AC_Enterprise_Ageing_Temp] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AC_Enterprise_Ageing_Temp_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_Enterprise_Customer_Ageing] ADD 
    	CONSTRAINT [PK_AC_Enterprise_Customer_Ageing] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AC_Enterprise_Customer_Ageing_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_History_Associates] ADD 
    	CONSTRAINT [PK_AC_History_Associates] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AC_History_Associates_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_History_Judgements] ADD 
    	CONSTRAINT [PK_AC_History_Judgements] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AC_History_Judgements_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_History_Motion_Roll] ADD 
    	CONSTRAINT [PK_AC_History_Motion_Roll] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AC_History_Motion_Roll_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_History_Notarial_Bonds] ADD 
    	CONSTRAINT [PK_AC_History_Notarial_Bonds] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AC_History_Notarial_Bonds_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_History_Principal_Properties] ADD 
    	CONSTRAINT [PK_AC_History_Principal_Properties] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AC_History_Principal_Properties_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_History_Principals] ADD 
    	CONSTRAINT [PK_AC_History_Principals] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AC_History_Principals_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_History_Properties] ADD 
    	CONSTRAINT [PK_AC_History_Properties] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AC_History_Properties_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_History_RD_Cheques] ADD 
    	CONSTRAINT [PK_AC_History_RD_Cheques] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AC_History_RD_Cheques_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AC_History_Shareholders] ADD 
    	CONSTRAINT [PK_AC_History_Shareholders] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AC_History_Shareholders_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
     CREATE  INDEX [IX_AC_Statement_Details_Key] ON [dbo].[AC_Statement_Details]([AC_Statements_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  INDEX [IX_AC_Statements_Customers_ID] ON [dbo].[AC_Statements]([AC_Customers_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
    setuser

    --Defaults AC_Assets
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_Assets].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_Assets].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_Assets].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_Assets].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    --Defaults AC_Contract_Prices
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_Contract_Prices].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_Contract_Prices].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_Contract_Prices].[AW_User_Companies_ID]'

    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_Contract_Prices].[Slu_AW_Active_ID]'
    
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Contract_Prices].[Discount_Amount]'

    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Contract_Prices].[Discount_Perc]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Contract_Prices].[Pack_Size]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Contract_Prices].[Unit_Price]'
   
    setuser

    
    setuser
    --Defaults AC_Enterprise_Ageing_Temp
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_Enterprise_Ageing_Temp].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_Enterprise_Ageing_Temp].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_Enterprise_Ageing_Temp].[AW_User_Companies_ID]'
    
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Enterprise_Ageing_Temp].[Amount]'
   
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Enterprise_Ageing_Temp].[Payment]'   
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Enterprise_Ageing_Temp].[Account_Balance]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Enterprise_Ageing_Temp].[Current]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Enterprise_Ageing_Temp].[30Days]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Enterprise_Ageing_Temp].[60Days]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Enterprise_Ageing_Temp].[90Days]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Enterprise_Ageing_Temp].[120Days]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Enterprise_Ageing_Temp].[150Days]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Enterprise_Ageing_Temp].[180+Days]'  
    
    setuser

    
    setuser
    --Defaults AC_Enterprise_Customer_Ageing
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Enterprise_Customer_Ageing].[CompanyID]'

    setuser

    
    setuser
    --Defaults AC_History_Associates
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_History_Associates].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_History_Associates].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_History_Associates].[AW_User_Companies_ID]'

    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_History_Associates].[Slu_AW_Active_ID]'
    
    setuser

   
    setuser
    --Defaults AC_History_Auditors
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_History_Auditors].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_History_Auditors].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_History_Auditors].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_History_Auditors].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    --Defaults AC_History_Balance_Sheets
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_History_Balance_Sheets].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_History_Balance_Sheets].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_History_Balance_Sheets].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_History_Balance_Sheets].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    --Defaults AC_History_Bankers
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_History_Bankers].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_History_Bankers].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_History_Bankers].[AW_User_Companies_ID]'

	EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_History_Bankers].[Slu_AW_Active_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_History_Bankers].[Bank_Code_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_History_Bankers].[Slu_AC_Bank_Codes_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_History_Bankers].[Slu_AW_Credit_Terms_ID]'
    
    setuser

    
    setuser
    --Defaults AC_History_Bonds
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_History_Bonds].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_History_Bonds].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_History_Bonds].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_History_Bonds].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    --Defaults AC_History_Credit_Limits
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_History_Credit_Limits].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_History_Credit_Limits].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_History_Credit_Limits].[AW_User_Companies_ID]'
   
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_History_Credit_Limits].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    --Defaults AC_History_Default
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_History_Default].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_History_Default].[AW_User_Companies_ID]'

    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_History_Default].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_History_Default].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    --Defaults AC_History_ITCScores
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_History_ITCScores].[Date_Captured]'

    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_History_ITCScores].[User_ID]'

    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_History_ITCScores].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_History_ITCScores].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    --Defaults AC_History_Income_Statements
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_History_Income_Statements].[Date_Captured]'

    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_History_Income_Statements].[User_ID]'

    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_History_Income_Statements].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_History_Income_Statements].[Slu_AW_Active_ID]'
   
    setuser

    
    setuser
    --Defaults AC_History_Info_Reports
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_History_Info_Reports].[Date_Captured]'

    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_History_Info_Reports].[User_ID]'

    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_History_Info_Reports].[AW_User_Companies_ID]'

    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_History_Info_Reports].[Slu_AW_Active_ID]'

    setuser

    
    setuser
    --Defaults AC_History_Judgements
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_History_Judgements].[Date_Captured]'

    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_History_Judgements].[User_ID]'

    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_History_Judgements].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_History_Judgements].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    --Defaults AC_History_KIScores
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_History_KIScores].[Date_Captured]'

    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_History_KIScores].[User_ID]'

    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_History_KIScores].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_History_KIScores].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    --Defaults AC_History_Motion_Roll
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_History_Motion_Roll].[Date_Captured]'

    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_History_Motion_Roll].[User_ID]'

    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_History_Motion_Roll].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_History_Motion_Roll].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    --Defaults AC_History_Notarial_Bonds
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_History_Notarial_Bonds].[Date_Captured]'

    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_History_Notarial_Bonds].[User_ID]'

    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_History_Notarial_Bonds].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_History_Notarial_Bonds].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    --Defaults AC_History_Principal_Properties
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_History_Principal_Properties].[Date_Captured]'

    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_History_Principal_Properties].[User_ID]'

    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_History_Principal_Properties].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_History_Principal_Properties].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    --Defaults AC_History_Principals
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_History_Principals].[Date_Captured]'

    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_History_Principals].[User_ID]'

    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_History_Principals].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_History_Principals].[Slu_AW_Active_ID]'

    setuser

    
    setuser
    --Defaults AC_History_Properties
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_History_Properties].[Date_Captured]'

    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_History_Properties].[User_ID]'

    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_History_Properties].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_History_Properties].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    --Defaults AC_History_RD_Cheques
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_History_RD_Cheques].[Date_Captured]'

    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_History_RD_Cheques].[User_ID]'

    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_History_RD_Cheques].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_History_RD_Cheques].[Slu_AW_Active_ID]'

    setuser

    
    setuser
    --Defaults AC_History_Ratings
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_History_Ratings].[Date_Captured]'

    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_History_Ratings].[User_ID]'

    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_History_Ratings].[AW_User_Companies_ID]'

    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_History_Ratings].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    --Defaults AC_History_Shareholders
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_History_Shareholders].[Date_Captured]'

    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_History_Shareholders].[User_ID]'

    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_History_Shareholders].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_History_Shareholders].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    --Defaults AC_History_Status
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_History_Status].[Date_Captured]'

    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_History_Status].[User_ID]'

    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_History_Status].[AW_User_Companies_ID]'

    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_History_Status].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    --Defaults AC_History_Trade_References
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_History_Trade_References].[Date_Captured]'

    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_History_Trade_References].[User_ID]'

    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_History_Trade_References].[AW_User_Companies_ID]'

    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_History_Trade_References].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    --Defaults AC_Periodic_Billing_Detail
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_Periodic_Billing_Detail].[Date_Captured]'

    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_Periodic_Billing_Detail].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_Periodic_Billing_Detail].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_Periodic_Billing_Detail].[Slu_AW_Active_ID]'
    
        

    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Periodic_Billing_Detail].[AB_Accounts_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Periodic_Billing_Detail].[AC_Customers_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Periodic_Billing_Detail].[Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AC_Periodic_Billing_Detail].[Comment]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AC_Periodic_Billing_Detail].[Email]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Periodic_Billing_Detail].[Net_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AC_Periodic_Billing_Detail].[Notes]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AC_Periodic_Billing_Detail].[Ref_No]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Three]', N'[AC_Periodic_Billing_Detail].[Sys_AW_Tax_Methods_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Periodic_Billing_Detail].[Sys_AW_Transaction_Types_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Periodic_Billing_Detail].[Tax_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_Periodic_Billing_Detail].[Transaction_Date]'
    
    setuser

    
    setuser
    --Defaults AC_Periodic_Billing_Detail_Splits
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_Periodic_Billing_Detail_Splits].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_Periodic_Billing_Detail_Splits].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_Periodic_Billing_Detail_Splits].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_Periodic_Billing_Detail_Splits].[Slu_AW_Active_ID]'
    
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Periodic_Billing_Detail_Splits].[Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Periodic_Billing_Detail_Splits].[AP_Products_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Periodic_Billing_Detail_Splits].[Net_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AC_Periodic_Billing_Detail_Splits].[Quantity]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Three]', N'[AC_Periodic_Billing_Detail_Splits].[Sys_AW_Tax_Methods_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Periodic_Billing_Detail_Splits].[Tax_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Periodic_Billing_Detail_Splits].[Unit_Price]'
    
    setuser

    
    setuser
    --Defaults AC_Periodic_Billing_Header
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_Periodic_Billing_Header].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_Periodic_Billing_Header].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_Periodic_Billing_Header].[AW_User_Companies_ID]'

    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AC_Periodic_Billing_Header].[Slu_AW_Active_ID]'    

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_Periodic_Billing_Header].[Date_Posted]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AC_Periodic_Billing_Header].[Import_Filename]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AC_Periodic_Billing_Header].[Posting_Type]'
    
    EXEC sp_bindefault N'[dbo].[df_Current_Month]', N'[AC_Periodic_Billing_Header].[Slu_AW_Months_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Current_Year]', N'[AC_Periodic_Billing_Header].[Slu_AW_Years_ID]'
    
    setuser


    setuser
    --Defaults AC_Statement_Details
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_Statement_Details].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_Statement_Details].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_Statement_Details].[AW_User_Companies_ID]'
    

    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statement_Details].[Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statement_Details].[Payment]'
    
    setuser

    
    setuser
    --Defaults AC_Statement_Details_Temp
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_Statement_Details_Temp].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_Statement_Details_Temp].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_Statement_Details_Temp].[AW_User_Companies_ID]'
    

    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statement_Details_Temp].[Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statement_Details_Temp].[Payment]'
    
    setuser

    
    setuser
    --Defaults AC_Statements
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_Statements].[Date_Captured]'

    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_Statements].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_Statements].[AW_User_Companies_ID]'
    
    setuser

    
    setuser
    --Defaults AC_Statements_Temp
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AC_Statements_Temp].[Date_Captured]'
   
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AC_Statements_Temp].[User_ID]' 
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AC_Statements_Temp].[AW_User_Companies_ID]'
    

    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statements_Temp].[Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statements_Temp].[Payment]'

	EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statements_Temp].[Current]'
	
	EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statements_Temp].[Account_Balance]'
	
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statements_Temp].[30Days]'

    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statements_Temp].[60Days]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statements_Temp].[90Days]'

    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statements_Temp].[120Days]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statements_Temp].[150Days]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AC_Statements_Temp].[180+Days]'
    
    setuser

    
    setuser
    --Defaults AW_Comments
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AW_Comments].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AW_Comments].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AW_Comments].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AW_Comments].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    --Defaults Log_AC_Master_Controller
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[Log_AC_Master_Controller].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[Log_AC_Master_Controller].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[Log_AC_Master_Controller].[AW_User_Companies_ID]'

      
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[Log_AC_Master_Controller].[Sys_AC_Message_Types_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[Log_AC_Master_Controller].[Sys_AW_Delivery_Methods_ID]'

    setuser

    
    setuser
    --Defaults Log_AC_Messages
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[Log_AC_Messages].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[Log_AC_Messages].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[Log_AC_Messages].[AW_User_Companies_ID]'
    
    setuser

  
    SET @ReturnValue = 1
 
RETURN @ReturnValue

SET NOCOUNT OFF    
GO

--14 sp_AW_9900
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AW_9900]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AW_9900]
GO
-------------------------------------------------------------------------------
--Description   :sp_AW_9900
--Purpose       :Wipe all SALES Transaction tables
--              :
--Parameters    :
--Date          :2002/04/19
--Authors       :TB
--MODS          :
--2004.5.5      :10/11/11 - Refreshed with latest table defs - 2004.5.5
--2015.6.0      :2015-02-02 - Refreshed with latest table defs - 2015.6.0
-------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[sp_AW_9900]
AS

SET NOCOUNT ON

DECLARE @ReturnValue bit

    SET @ReturnValue = 0

BEGIN

    --First wipe the customer balances
    UPDATE AC_Customers SET Account_Balance = 0,
                            Current_Balance = 0,
                            Days_30 = 0,
                            Days_60 = 0,
                            Days_90 = 0,
                            Days_120 = 0,
                            Days_150 = 0,
                            Days_180 = 0
 

    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_AP_Promotion_Products_AP_Promotions]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
    ALTER TABLE [dbo].[AP_Promotion_Products] DROP CONSTRAINT FK_AP_Promotion_Products_AP_Promotions

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Promotion_Products]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Promotion_Products]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Promotions]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Promotions]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AS_Cash_Ups]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AS_Cash_Ups]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AS_Day_Ends]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AS_Day_Ends]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AS_Enterprise_Customer_Sales]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AS_Enterprise_Customer_Sales]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AS_Enterprise_GP]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AS_Enterprise_GP]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AS_Enterprise_Sales]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AS_Enterprise_Sales]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AS_Enterprise_Sales_All]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AS_Enterprise_Sales_All]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AS_Sales_Order_Details]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AS_Sales_Order_Details]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AS_Till_Payouts]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AS_Till_Payouts]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AS_Transaction_Details]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AS_Transaction_Details]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AS_Transaction_Payments]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AS_Transaction_Payments]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AS_Transaction_Sources]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AS_Transaction_Sources]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AS_Transactions]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AS_Transactions]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AS_Transactions_CBilling]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AS_Transactions_CBilling]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AS_Transactions_CBilling_Temp]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AS_Transactions_CBilling_Temp]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AS_Transactions_Transactions]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AS_Transactions_Transactions]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AS_Transactions_Xref]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AS_Transactions_Xref]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AS_Transactions_Xref_Sources]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AS_Transactions_Xref_Sources]


    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AS_Transactions_Address]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AS_Transactions_Address]

    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AS_Transactions_Address_Detail]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AS_Transactions_Address_Detail]
    
    CREATE TABLE [dbo].[AP_Promotion_Products] (
    	[AP_Promotion_Products_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AP_Promotions_ID] [int] NULL ,
    	[AP_Products_ID] [int] NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Product_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Start_Date] [datetime] NULL ,
    	[End_Date] [datetime] NULL ,
    	[Slu_AW_Credit_Terms_ID] [tinyint] NULL ,
    	[Selling_Price] [money] NULL ,
    	[Qty_Projected_Sales] [decimal](9, 3) NULL ,
    	[Qty_Cutoff] [decimal](9, 3) NULL ,
    	[Qty_Sold] [decimal](9, 3) NULL ,
    	[Max_Per_Customer] [decimal](9, 3) NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NOT NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Promotions] (
    	[AP_Promotions_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Start_Date] [datetime] NULL ,
    	[End_Date] [datetime] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AS_Cash_Ups] (
    	[AS_Cash_Ups_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Cashier_ID] [int] NULL ,
    	[Lup_AS_Tills_ID] [int] NULL ,
    	[Sys_AW_Payment_Methods_ID] [int] NULL ,
    	[Slu_AS_Coinage_ID] [int] NULL ,
    	[Amount] [money] NULL ,
    	[Cashed_Up] [smalldatetime] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[Slu_AW_Active_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AS_Day_Ends] (
    	[AS_Day_Ends_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Day_End] [smalldatetime] NOT NULL ,
    	[AB_Transaction_Date] [datetime] NOT NULL ,
    	[Slu_AW_Months_ID] [int] NULL ,
    	[Slu_AW_Years_ID] [int] NULL ,
    	[AB_Transaction_Ref] [int] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AS_Enterprise_Customer_Sales] (
    	[AS_Enterprise_Customer_Sales_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Customer] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[CustNo] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Total] [money] NULL ,
    	[Filter] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AS_Enterprise_GP] (
    	[AS_Enterprise_GP_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Product_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Pack_Size] [decimal](9, 3) NULL ,
    	[TotalSales] [money] NULL ,
    	[TotalCost] [money] NULL ,
    	[Total] [money] NULL ,
    	[Filter] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AS_Enterprise_Sales] (
    	[AS_Enterprise_Sales_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Product_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Pack_Size] [decimal](9, 3) NULL ,
    	[Quantity] [decimal](12, 3) NULL ,
    	[Total] [money] NULL ,
    	[Filter] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AS_Enterprise_Sales_All] (
    	[AS_Enterprise_Sales_All_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Product_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Pack_Size] [decimal](9, 3) NULL ,
    	[Total] [money] NULL ,
    	[Filter] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AS_Sales_Order_Details] (
    	[AS_Sales_Order_Details_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NULL ,
    	[AP_Products_ID] [int] NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Product_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Quantity] [decimal](9, 3) NULL ,
    	[Back_Order] [decimal](9, 3) NULL ,
    	[Original_Price] [money] NULL ,
    	[Unit_Price] [money] NULL ,
    	[Discount_Amount] [money] NULL ,
    	[Amount] [money] NULL ,
    	[Shipping_Cost] [money] NULL ,
    	[Tax_Rate] [decimal](9, 3) NULL ,
    	[Tax_Amount] [money] NULL ,
    	[Extended_Amount] [money] NULL ,
    	[Unit_Cost] [money] NULL ,
    	[AP_Promotion_Products_ID] [int] NULL ,
    	[Promo_Price] [money] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AS_Till_Payouts] (
    	[AS_Till_Payouts_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Payout_Type_ID] [tinyint] NULL ,
    	[AB_Account_DR_ID] [int] NULL ,
    	[AB_Account_CR_ID] [int] NULL ,
    	[AO_Suppliers_ID] [int] NULL ,
    	[Sys_AB_Transaction_Types_ID] [tinyint] NULL ,
    	[Description] [varchar] (36) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Narration] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Payout_Number] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Payout_Date] [datetime] NULL ,
    	[Slu_AW_Months_ID] [tinyint] NULL ,
    	[Slu_AW_Years_ID] [int] NULL ,
    	[Amount] [money] NULL ,
    	[Day_End] [smalldatetime] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL,
    	[TillID] [int] NOT NULL ,
    	[Cashup_Date] [datetime] NULL
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AS_Transaction_Details] (
    	[AS_Transaction_Details_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AS_Transactions_ID] [int] NULL ,
    	[AP_Products_ID] [int] NULL ,
    	[Quantity] [decimal](9, 3) NULL ,
    	[Unit_Cost] [money] NULL ,
    	[Unit_Price] [money] NULL ,
    	[Original_Price] [money] NULL ,
    	[Original_Discount] [money] NULL ,
    	[Discount_Amount] [money] NULL ,
    	[Tax_Amount] [money] NULL ,
    	[Extended_Amount] [money] NULL ,
    	[Commission_Amount] [money] NULL ,
    	[AP_Promotion_Products_ID] [int] NULL ,
    	[AS_Job_References_ID] [int] NULL ,
    	[Serial_No] [varchar] (13) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Make] [varchar] (6) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Customer] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Back_Order] [decimal](9, 3) NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL ,
    	[TDHeader] [varchar] (256) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[TDDetail] [varchar] (256) COLLATE SQL_Latin1_General_CP1_CI_AS NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AS_Transaction_Payments] (
    	[AS_Transaction_Payments_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AS_Transactions_ID] [int] NULL ,
    	[Sys_AW_Payment_Methods_ID] [tinyint] NULL ,
    	[Slu_AS_Card_Institutions_ID] [int] NULL ,
    	[Payor_Name] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Card_Expiry_Date] [varchar] (6) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Card_Number] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Authorisation_Number] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Amount] [money] NULL ,
    	[Banked] [smalldatetime] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AS_Transaction_Sources] (
    	[AS_Transaction_Sources_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AS_Transactions_ID] [int] NULL ,
    	[Transaction_Numbers] [varchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AS_Transactions] (
    	[AS_Transactions_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NULL ,
    	[AB_Accounts_ID] [int] NULL ,
    	[Sys_AW_Transaction_Types_ID] [tinyint] NULL ,
    	[Transaction_Date] [datetime] NULL ,
    	[Transaction_Number] [varchar] (19) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Total_Cost] [money] NULL ,
    	[Amount] [money] NULL ,
    	[Total_Tax_Amount] [money] NULL ,
    	[Total_Discount_Amount] [money] NULL ,
    	[Total_Amount] [money] NULL ,
    	[Payment_Amount] [money] NULL ,
    	[Expiry_Date] [smalldatetime] NULL ,
    	[Version_Number] [smallint] NULL ,
    	[Customer_Reference] [varchar] (15) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Comment] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[AW_Comments_ID] [int] NULL ,
    	[Lup_AS_Marketing_Indicators_ID] [int] NULL ,
    	[Lup_AW_Stores_ID] [smallint] NULL ,
    	[Lup_AW_Workstations_ID] [smallint] NULL ,
    	[Lup_AS_Tills_ID] [smallint] NULL ,
    	[Lup_AS_Cashiers_ID] [smallint] NULL ,
    	[Lup_AS_Reps_ID] [smallint] NULL ,
    	[Slu_AW_Currencies_ID] [smallint] NULL ,
    	[Old_Sys_AW_Transaction_Types_ID] [tinyint] NULL ,
    	[Cancelled_User_ID] [int] NULL ,
    	[Cancelled_DateTime] [datetime] NULL ,
    	[Cashed_Up] [smalldatetime] NULL ,
    	[Day_End] [smalldatetime] NULL ,
    	[Transmitted] [datetime] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AS_Transactions_CBilling] (
    	[AS_Transactions_CBilling_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AS_Transactions_ID] [int] NULL ,
    	[Lup_AS_CBilling_Providers_ID] [smallint] NULL ,
    	[Customer_Number] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Network_Identity_Number] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Sys_AW_Transaction_Types_ID] [tinyint] NULL ,
    	[Transaction_Number] [varchar] (19) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Original_Number] [varchar] (19) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Transaction_Date] [datetime] NULL ,
    	[Manufacturer_Code] [varchar] (18) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Quantity] [decimal](9, 3) NULL ,
    	[Extended_Amount] [money] NULL ,
    	[Tax_Amount] [money] NULL ,
    	[Discount_Amount] [money] NULL ,
    	[Lup_AP_Fail_Reasons_ID] [smallint] NULL ,
    	[Item_No] [smallint] NULL ,
    	[Authorization_No] [varchar] (24) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Registration_No] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Odometer_Reading] [varchar] (7) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Make] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Model] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Model_Year] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Client_ID_No] [varchar] (13) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Engine_No] [varchar] (24) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Chassis_No] [varchar] (24) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Lup_AP_Claim_Codes_ID] [smallint] NULL ,
    	[Xmit_Date] [datetime] NULL ,
    	[Xmit_File] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AS_Transactions_CBilling_Temp] (
    	[AS_Transactions_CBilling_Temp_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AS_Transactions_ID] [int] NULL ,
    	[Lup_AS_CBilling_Providers_ID] [smallint] NULL ,
    	[cat_code] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[drs_acc] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[trs_ref] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[trs_date] [datetime] NULL ,
    	[qty] [decimal](9, 3) NULL ,
    	[amount] [money] NULL ,
    	[gls_acc] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[narr] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[stock_group] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[drs_apply] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[sys_code] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[updated] [varchar] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[interfaced] [varchar] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[drs_age_month] [smallint] NULL ,
    	[stock_code] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[area] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[drs_alpha] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[branch] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[vat_amount] [money] NULL ,
    	[cost_amount] [money] NULL ,
    	[rep_comm] [money] NULL ,
    	[process_type] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[rep_code] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[acct_type] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[disc_amnt] [money] NULL ,
    	[std_sell_price] [money] NULL ,
    	[drs_trs_code] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[trs_type] [smallint] NULL ,
    	[acc_month] [smallint] NULL ,
    	[acc_year] [smallint] NULL ,
    	[con_acct_no] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[zz_int01] [smallint] NULL ,
    	[cntno] [smallint] NULL ,
    	[line_disc1] [decimal](9, 3) NULL ,
    	[line_disc2] [decimal](9, 3) NULL ,
    	[stock_sell1] [money] NULL ,
    	[no_of_deals] [smallint] NULL ,
    	[zz_date01] [datetime] NULL ,
    	[zz_date02] [datetime] NULL ,
    	[zz_date03] [datetime] NULL ,
    	[special_instr] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[deals_flag] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[deals_number] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[vat_exempt_member] [varchar] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[cmonth] [smallint] NULL ,
    	[cyear] [smallint] NULL ,
    	[rep_call_status] [varchar] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[drsdiv_code] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[crs_acc] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[creation_date] [datetime] NULL ,
    	[creation_time] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[creation_userid] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[creation_proc] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[item_number] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[rep_code2] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[qty2] [decimal](9, 3) NULL ,
    	[deposit_amount] [decimal](9, 3) NULL ,
    	[job_number] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[line_disc_amnt] [decimal](9, 3) NULL ,
    	[carhire_cntno] [smallint] NULL ,
    	[currency] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[exch_rate] [money] NULL ,
    	[cyear_month] [smallint] NULL ,
    	[zz_date04] [datetime] NULL ,
    	[zz_date05] [datetime] NULL ,
    	[zz_int02] [smallint] NULL ,
    	[zz_int03] [smallint] NULL ,
    	[zz_int04] [smallint] NULL ,
    	[zz_int05] [smallint] NULL ,
    	[zz_dec01] [decimal](9, 3) NULL ,
    	[zz_dec02] [decimal](9, 3) NULL ,
    	[zz_dec03] [decimal](9, 3) NULL ,
    	[zz_dec04] [decimal](9, 3) NULL ,
    	[zz_dec05] [decimal](9, 3) NULL ,
    	[zz_log01] [varchar] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[zz_log02] [varchar] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[zz_log03] [varchar] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[zz_log04] [varchar] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[zz_log05] [varchar] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[zz_log06] [varchar] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[zz_log07] [varchar] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[zz_char01] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[zz_char02] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[zz_char03] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[zz_char04] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[zz_char05] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[key_glstrs] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[key_history] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[dumped] [varchar] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[company_name] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[branch_name] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[drs_name] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[crs_name] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[prd_grp_descr] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[stk_descry] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[status_ind] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[customer_ref] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[comments1] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[comments2] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[comments3] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[comments4] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[comments5] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[comments6] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[comments7] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[comments8] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[database_id] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[system_id] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[vat_reg_no] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[email] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[customer_cell_number] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[customer_email_address] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AS_Transactions_Transactions] (
    	[AS_Transactions_Transactions_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Source_AS_Transactions_ID] [int] NULL ,
    	[Destination_AS_Transactions_ID] [int] NULL ,
    	[Amount] [money] NULL ,
    	[AB_Accounts_ID] [int] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AS_Transactions_Xref] (
    	[AS_Transactions_Xref_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AS_Transactions_ID] [int] NULL ,
    	[AW_YesNo_Checked_ID] [tinyint] NULL ,
    	[Checked_User_ID] [int] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AS_Transactions_Xref_Sources] (
    	[AS_Transactions_Xref_Sources_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AS_Transactions_Xref_ID] [int] NULL ,
    	[AS_Transactions_ID] [int] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]



	CREATE TABLE [dbo].[AS_Transactions_Address](
		[AS_Transactions_Address_ID] [int] IDENTITY(1,1) NOT NULL,
		[AS_Transactions_ID] [int] NOT NULL,
		[AS_Transactions_Address_Detail_ID] [int] NOT NULL,
		[Date_Captured] [datetime] NOT NULL,
		[User_ID] [int] NOT NULL,
		[AW_User_Companies_ID] [int] NOT NULL,
		[Touched] [timestamp] NULL
	) ON [PRIMARY]


	CREATE TABLE [dbo].[AS_Transactions_Address_Detail](
		[AS_Transactions_Address_Detail_ID] [int] IDENTITY(1,1) NOT NULL,
		[AC_Customers_ID] [int] NOT NULL,
		[Inv_Address1] [varchar](40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
		[Inv_Address2] [varchar](40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
		[Inv_City] [varchar](30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
		[Inv_Code] [varchar](10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
		[Delivery_Address] [varchar](40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
		[Delivery_Suburb] [varchar](40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
		[Delivery_City] [varchar](30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
		[Delivery_Post_Code] [varchar](10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
		[Date_Captured] [datetime] NOT NULL,
		[User_ID] [int] NOT NULL,
		[AW_User_Companies_ID] [int] NOT NULL,
		[Touched] [timestamp] NULL,
		[Customer_Name] [varchar](50) NULL,
		[Tax_Number] [varchar](16) NULL,
		[AW_YesNo_Delivery_Address] [tinyint] NULL,
		[AW_YesNo_Invoice] [tinyint] NULL
	) ON [PRIMARY]  
  
    
    ALTER TABLE [dbo].[AP_Promotions] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AP_Promotions] PRIMARY KEY  CLUSTERED 
    	(
    		[AP_Promotions_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AS_Cash_Ups] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AS_Cash_Ups] PRIMARY KEY  CLUSTERED 
    	(
    		[AS_Cash_Ups_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AS_Day_Ends] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AS_Day_Ends] PRIMARY KEY  CLUSTERED 
    	(
    		[AS_Day_Ends_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AS_Till_Payouts] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AS_Till_Payouts] PRIMARY KEY  CLUSTERED 
    	(
    		[AS_Till_Payouts_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AS_Transaction_Payments] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AS_Payments] PRIMARY KEY  CLUSTERED 
    	(
    		[AS_Transaction_Payments_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AS_Transaction_Sources] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AS_Transaction_Sources] PRIMARY KEY  CLUSTERED 
    	(
    		[AS_Transaction_Sources_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AS_Transactions_CBilling] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AS_Transactions_CBilling] PRIMARY KEY  CLUSTERED 
    	(
    		[AS_Transactions_CBilling_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AS_Transactions_CBilling_Temp] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AS_Transactions_CBilling_Temp] PRIMARY KEY  CLUSTERED 
    	(
    		[AS_Transactions_CBilling_Temp_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AS_Transactions_Transactions] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AS_Quotes_Sales] PRIMARY KEY  CLUSTERED 
    	(
    		[AS_Transactions_Transactions_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AS_Transactions_Xref] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AS_Transactions_Xref] PRIMARY KEY  CLUSTERED 
    	(
    		[AS_Transactions_Xref_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AS_Transactions_Xref_Sources] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AS_Transactions_Xref_Sources] PRIMARY KEY  CLUSTERED 
    	(
    		[AS_Transactions_Xref_Sources_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 


    ALTER TABLE [dbo].[AS_Transactions_Address] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AS_Transactions_Address_ID] PRIMARY KEY  CLUSTERED 
    	(
    		[AS_Transactions_Address_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 


    ALTER TABLE [dbo].[AS_Transactions_Address_Detail] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AS_Transactions_Address_Detail] PRIMARY KEY  CLUSTERED 
    	(
    		[AS_Transactions_Address_Detail_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 
   
   
  
    
     CREATE  CLUSTERED  INDEX [IX_AP_Promotion_Products_AP_Products_ID] ON [dbo].[AP_Promotion_Products]([AP_Products_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [IX_AS_Enterprise_Customer_Sales_Search] ON [dbo].[AS_Enterprise_Customer_Sales]([Filter], [Customer], [CustNo]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [IX_AS_Enterprise_GP_Search] ON [dbo].[AS_Enterprise_GP]([Filter], [Product_Code], [Pack_Size]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [IX_AS_Enterprise_Sales_Search] ON [dbo].[AS_Enterprise_Sales]([Filter], [Product_Code], [Pack_Size]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [IX_AS_Enterprise_Sales_All_Search] ON [dbo].[AS_Enterprise_Sales_All]([Filter], [Product_Code], [Pack_Size]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [CI_AS_Sales_Order_Details] ON [dbo].[AS_Sales_Order_Details]([AC_Customers_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [CI_AS_Transaction_Details] ON [dbo].[AS_Transaction_Details]([AS_Transactions_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [CI_AS_Transactions] ON [dbo].[AS_Transactions]([AC_Customers_ID], [AS_Transactions_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
    ALTER TABLE [dbo].[AP_Promotion_Products] ADD 
    	CONSTRAINT [PK_AP_Promotion_Products] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AP_Promotion_Products_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
     CREATE  INDEX [IX_AP_Promotion_Products_AP_Promotions] ON [dbo].[AP_Promotion_Products]([AP_Promotions_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  INDEX [IX_AS_Day_Ends_Key] ON [dbo].[AS_Day_Ends]([Day_End] DESC ) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
    ALTER TABLE [dbo].[AS_Enterprise_Customer_Sales] ADD 
    	CONSTRAINT [PK_AS_Enterprise_Customer_Sales] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AS_Enterprise_Customer_Sales_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AS_Enterprise_GP] ADD 
    	CONSTRAINT [PK_AS_Enterprise_GP] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AS_Enterprise_GP_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AS_Enterprise_Sales] ADD 
    	CONSTRAINT [PK_AS_Enterprise_Sales] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AS_Enterprise_Sales_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AS_Enterprise_Sales_All] ADD 
    	CONSTRAINT [PK_AS_Enterprise_Sales_All] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AS_Enterprise_Sales_All_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AS_Sales_Order_Details] ADD 
    	CONSTRAINT [PK_AS_Sales_Order_Details] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AS_Sales_Order_Details_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
     CREATE  INDEX [IX_AS_Sales_Order_Details_AP_Products_ID] ON [dbo].[AS_Sales_Order_Details]([AP_Products_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
    ALTER TABLE [dbo].[AS_Transaction_Details] ADD 
    	CONSTRAINT [PK_AS_Transaction_Details] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AS_Transaction_Details_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
     CREATE  INDEX [IX_AS_Transaction_Details_AP_Products_ID] ON [dbo].[AS_Transaction_Details]([AP_Products_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  INDEX [IX_PaymentsTranID] ON [dbo].[AS_Transaction_Payments]([AS_Transactions_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  INDEX [IX_TranSourcesTranID] ON [dbo].[AS_Transaction_Sources]([AS_Transactions_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
    ALTER TABLE [dbo].[AS_Transactions] ADD 
    	CONSTRAINT [PK_AS_Transactions] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AS_Transactions_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
     CREATE  INDEX [IX_AS_Transactions_Date_Captured] ON [dbo].[AS_Transactions]([Date_Captured]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  INDEX [IX_AS_Transactions_Transaction_Type] ON [dbo].[AS_Transactions]([Sys_AW_Transaction_Types_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  INDEX [IX_AS_Transactions_Comment] ON [dbo].[AS_Transactions]([Comment]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  INDEX [IX_AS_ActiveJobSalesOrders] ON [dbo].[AS_Transactions]([Sys_AW_Transaction_Types_ID], [Slu_AW_Active_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  INDEX [IX_AS_Transaction_Date_Type] ON [dbo].[AS_Transactions]([Transaction_Date], [Sys_AW_Transaction_Types_ID], [AW_User_Companies_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  INDEX [IX_CBilling_Tran_ID] ON [dbo].[AS_Transactions_CBilling]([AS_Transactions_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
    ALTER TABLE [dbo].[AS_Transactions_CBilling_Temp] ADD 
    	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_drs_acc] DEFAULT ('SPIRAL') FOR [drs_acc],
    	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_gls_acc] DEFAULT ('N/A') FOR [gls_acc],
    	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_sys_code] DEFAULT ('SPI') FOR [sys_code],
    	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_updated] DEFAULT ('no') FOR [updated],
    	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_interfaced] DEFAULT ('no') FOR [interfaced],
    	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_area] DEFAULT ('N/A') FOR [area],
    	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_acct_type] DEFAULT ('N/A') FOR [acct_type],
    	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_drs_trs_code] DEFAULT ('100') FOR [drs_trs_code],
    	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_vat_exempt_member] DEFAULT ('no') FOR [vat_exempt_member],
    	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_rep_call_status] DEFAULT ('no') FOR [rep_call_status],
    	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_zz_log01] DEFAULT ('no') FOR [zz_log01],
    	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_zz_log02] DEFAULT ('no') FOR [zz_log02],
    	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_zz_log03] DEFAULT ('no') FOR [zz_log03],
    	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_zz_log04] DEFAULT ('no') FOR [zz_log04],
    	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_zz_log05] DEFAULT ('no') FOR [zz_log05],
    	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_zz_log06] DEFAULT ('no') FOR [zz_log06],
    	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_zz_log07] DEFAULT ('no') FOR [zz_log07],
    	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_dumped] DEFAULT ('no') FOR [dumped],
    	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_status_ind] DEFAULT ('NE') FOR [status_ind],
    	CONSTRAINT [DF_AS_Transactions_CBilling_Temp_database_id] DEFAULT ('SPIRAL') FOR [database_id]

    
     CREATE  INDEX [IX_SourceTranID] ON [dbo].[AS_Transactions_Transactions]([Source_AS_Transactions_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  INDEX [IX_DestinationTranID] ON [dbo].[AS_Transactions_Transactions]([Destination_AS_Transactions_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  INDEX [IX_Xref_Tran_ID] ON [dbo].[AS_Transactions_Xref]([AS_Transactions_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  INDEX [IX_Xref_Source_Tran_ID] ON [dbo].[AS_Transactions_Xref_Sources]([AS_Transactions_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
    setuser
    --Defaults AP_Promotion_Products
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Promotion_Products].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Promotion_Products].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Promotion_Products].[AW_User_Companies_ID]'

	EXEC sp_bindefault N'[dbo].[df_Active]', N'[AP_Promotion_Products].[Slu_AW_Active_ID]'    
    
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Promotion_Products].[Max_Per_Customer]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Promotion_Products].[Qty_Cutoff]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Promotion_Products].[Qty_Projected_Sales]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Promotion_Products].[Qty_Sold]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Promotion_Products].[Selling_Price]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Promotion_Products].[Slu_AW_Credit_Terms_ID]'
    
    setuser

    
    setuser
    --Defaults AP_Promotions
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Promotions].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Promotions].[User_ID]'

    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Promotions].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AP_Promotions].[Slu_AW_Active_ID]'

    setuser

    
    setuser
	--Defaults AS_Cash_Ups    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AS_Cash_Ups].[Date_Captured]'

	EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AS_Cash_Ups].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AS_Cash_Ups].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    --Defaults AS_Day_Ends    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AS_Day_Ends].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AS_Day_Ends].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AS_Day_Ends].[AW_User_Companies_ID]'

    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AS_Day_Ends].[Slu_AW_Active_ID]'
    

    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Day_Ends].[AB_Transaction_Ref]'
    
    setuser

    
    setuser
	--Defaults AS_Enterprise_GP        
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AS_Enterprise_GP].[Pack_Size]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Enterprise_GP].[Total]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Enterprise_GP].[TotalCost]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Enterprise_GP].[TotalSales]'

    setuser

    
    setuser
	--Defaults AS_Enterprise_Sales            
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AS_Enterprise_Sales].[Pack_Size]'
    
    setuser

    
    setuser
    --Defaults AS_Enterprise_Sales_All            
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AS_Enterprise_Sales_All].[Pack_Size]'

    setuser

    
    setuser
	--Defaults AS_Sales_Order_Details
	EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AS_Sales_Order_Details].[Date_Captured]'
	
	EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AS_Sales_Order_Details].[User_ID]'
	
	EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AS_Sales_Order_Details].[AW_User_Companies_ID]'
	
	EXEC sp_bindefault N'[dbo].[df_Active]', N'[AS_Sales_Order_Details].[Slu_AW_Active_ID]'

	    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Sales_Order_Details].[Amount]'
        
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Sales_Order_Details].[Back_Order]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Sales_Order_Details].[Discount_Amount]'
   
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Sales_Order_Details].[Extended_Amount]'

    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Sales_Order_Details].[Original_Price]'
   
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Sales_Order_Details].[Quantity]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Sales_Order_Details].[Shipping_Cost]'
   
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Sales_Order_Details].[Tax_Amount]'
   
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Sales_Order_Details].[Tax_Rate]'
   
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Sales_Order_Details].[Unit_Cost]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Sales_Order_Details].[Unit_Price]'
    
    setuser

    
    setuser
	--Defaults AS_Till_Payouts
	EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AS_Till_Payouts].[Date_Captured]'
	
	EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AS_Till_Payouts].[User_ID]'
	
	EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AS_Till_Payouts].[AW_User_Companies_ID]'
	
	EXEC sp_bindefault N'[dbo].[df_Active]', N'[AS_Till_Payouts].[Slu_AW_Active_ID]'
	
	
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Till_Payouts].[Amount]'
   
    setuser

    
    setuser
	--Defaults AS_Transaction_Details
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AS_Transaction_Details].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AS_Transaction_Details].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AS_Transaction_Details].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AS_Transaction_Details].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transaction_Details].[Back_Order]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transaction_Details].[Commission_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transaction_Details].[Discount_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transaction_Details].[Extended_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transaction_Details].[Original_Discount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transaction_Details].[Original_Price]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transaction_Details].[Quantity]'
   
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transaction_Details].[Tax_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transaction_Details].[Unit_Cost]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transaction_Details].[Unit_Price]'
    
    setuser

    
    setuser
	--Defaults AS_Transaction_Payments
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AS_Transaction_Payments].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AS_Transaction_Payments].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AS_Transaction_Payments].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AS_Transaction_Payments].[Slu_AW_Active_ID]'
    
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transaction_Payments].[Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AS_Transaction_Payments].[Slu_AS_Card_Institutions_ID]'
    
    setuser

    
    setuser
	--Defaults AS_Transaction_Sources        
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AS_Transaction_Sources].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AS_Transaction_Sources].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AS_Transaction_Sources].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AS_Transaction_Sources].[Slu_AW_Active_ID]'
   
    setuser

    
    setuser
	--Defaults AS_Transactions  
	EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AS_Transactions].[Date_Captured]'
	
	EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AS_Transactions].[User_ID]'
	
	EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AS_Transactions].[AW_User_Companies_ID]'
	 
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AS_Transactions].[Slu_AW_Active_ID]'   
    
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transactions].[Amount]'
  
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AS_Transactions].[Lup_AS_Cashiers_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AS_Transactions].[Lup_AS_Reps_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AS_Transactions].[Lup_AS_Tills_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AS_Transactions].[Lup_AW_Stores_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AS_Transactions].[Lup_AW_Workstations_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transactions].[Payment_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transactions].[Total_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transactions].[Total_Cost]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transactions].[Total_Discount_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transactions].[Total_Tax_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AS_Transactions].[Transaction_Date]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AS_Transactions].[Version_Number]'
    
    setuser

    
    setuser
	--Defaults AS_Transactions_CBilling
	EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AS_Transactions_CBilling].[Date_Captured]'
	
	EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AS_Transactions_CBilling].[User_ID]'
	
	EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AS_Transactions_CBilling].[AW_User_Companies_ID]'
	
	EXEC sp_bindefault N'[dbo].[df_Active]', N'[AS_Transactions_CBilling].[Slu_AW_Active_ID]'
	

    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_CBilling].[Authorization_No]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_CBilling].[Chassis_No]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_CBilling].[Client_ID_No]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_CBilling].[Customer_Number]'    
       
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transactions_CBilling].[Discount_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_CBilling].[Engine_No]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transactions_CBilling].[Extended_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transactions_CBilling].[Item_No]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AS_Transactions_CBilling].[Lup_AP_Claim_Codes_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AS_Transactions_CBilling].[Lup_AP_Fail_Reasons_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_CBilling].[Make]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_CBilling].[Manufacturer_Code]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_CBilling].[Model]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_CBilling].[Model_Year]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_CBilling].[Network_Identity_Number]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_CBilling].[Odometer_Reading]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_CBilling].[Original_Number]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transactions_CBilling].[Quantity]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_CBilling].[Registration_No]'
       
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transactions_CBilling].[Tax_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_CBilling].[Transaction_Number]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_CBilling].[Xmit_File]'
   
    setuser

    
    setuser
	--Defaults AS_Transactions_CBilling_Temp
	EXEC sp_bindefault N'[dbo].[df_Date_Updated]', N'[AS_Transactions_CBilling_Temp].[Date_Captured]'
	
	EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AS_Transactions_CBilling_Temp].[User_ID]'
		    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AS_Transactions_CBilling_Temp].[AW_User_Companies_ID]'

    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AS_Transactions_CBilling_Temp].[Slu_AW_Active_ID]'    

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AS_Transactions_CBilling_Temp].[drs_age_month]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AS_Transactions_CBilling_Temp].[trs_type]'
    
    setuser

    
    setuser
	--Defaults AS_Transactions_Transactions
	EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AS_Transactions_Transactions].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AS_Transactions_Transactions].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AS_Transactions_Transactions].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AS_Transactions_Transactions].[Slu_AW_Active_ID]'
    
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transactions_Transactions].[Amount]'
    
    setuser

    
    setuser
	--Defaults AS_Transactions_Xref
	EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AS_Transactions_Xref].[Date_Captured]'
	
	EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AS_Transactions_Xref].[User_ID]'
	    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AS_Transactions_Xref].[AW_User_Companies_ID]'

    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AS_Transactions_Xref].[Slu_AW_Active_ID]'
    
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AS_Transactions_Xref].[AW_YesNo_Checked_ID]'

    setuser

    
    setuser
	--Defaults AS_Transactions_Xref_Sources
	EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AS_Transactions_Xref_Sources].[Date_Captured]'
	
	EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AS_Transactions_Xref_Sources].[User_ID]'
	    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AS_Transactions_Xref_Sources].[AW_User_Companies_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AS_Transactions_Xref_Sources].[Slu_AW_Active_ID]'
    
    setuser


    setuser
	--Defaults AS_Transactions_Address    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AS_Transactions_Address].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AS_Transactions_Address].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AS_Transactions_Address].[AW_User_Companies_ID]'
           
    setuser    


    setuser
    --Defaults AS_Transactions_Address    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AS_Transactions_Address_Detail].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AS_Transactions_Address_Detail].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AS_Transactions_Address_Detail].[AW_User_Companies_ID]'
           
           
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_Address_Detail].[Inv_Address1]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_Address_Detail].[Inv_Address2]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_Address_Detail].[Inv_City]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_Address_Detail].[Inv_Code]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_Address_Detail].[Delivery_Address]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_Address_Detail].[Delivery_Suburb]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_Address_Detail].[Delivery_City]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_Address_Detail].[Delivery_Post_Code]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_Address_Detail].[Customer_Name]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AS_Transactions_Address_Detail].[Tax_Number]'
    
    setuser

    ALTER TABLE [dbo].[AP_Promotion_Products] ADD 
    	CONSTRAINT [FK_AP_Promotion_Products_AP_Promotions] FOREIGN KEY 
    	(
    		[AP_Promotions_ID]
    	) REFERENCES [dbo].[AP_Promotions] (
    		[AP_Promotions_ID]
    	)

    
    ALTER TABLE [dbo].[AS_Transaction_Payments] ADD 
    	CONSTRAINT [FK_AS_Payments_Lup_AW_Payment_Methods] FOREIGN KEY 
    	(
    		[Sys_AW_Payment_Methods_ID]
    	) REFERENCES [dbo].[Sys_AW_Payment_Methods] (
    		[Sys_AW_Payment_Methods_ID]
    	)

    
    ALTER TABLE [dbo].[AS_Transactions] ADD 
    	CONSTRAINT [FK_AS_Transactions_AW_Comments] FOREIGN KEY 
    	(
    		[AW_Comments_ID]
    	) REFERENCES [dbo].[AW_Comments] (
    		[AW_Comments_ID]
    	) NOT FOR REPLICATION ,
    	CONSTRAINT [FK_AS_Transactions_Lup_AS_Tills] FOREIGN KEY 
    	(
    		[Lup_AS_Tills_ID]
    	) REFERENCES [dbo].[Lup_AS_Tills] (
    		[Lup_AS_Tills_ID]
    	),
    	CONSTRAINT [FK_AS_Transactions_Lup_AW_Stores] FOREIGN KEY 
    	(
    		[Lup_AW_Stores_ID]
    	) REFERENCES [dbo].[Lup_AW_Stores] (
    		[Lup_AW_Stores_ID]
    	),
    	CONSTRAINT [FK_AS_Transactions_Lup_AW_Workstations] FOREIGN KEY 
    	(
    		[Lup_AW_Workstations_ID]
    	) REFERENCES [dbo].[Lup_AW_Workstations] (
    		[Lup_AW_Workstations_ID]
    	),
    	CONSTRAINT [FK_AS_Transactions_Sys_AW_Transaction_Types] FOREIGN KEY 
    	(
    		[Sys_AW_Transaction_Types_ID]
    	) REFERENCES [dbo].[Sys_AW_Transaction_Types] (
    		[Sys_AW_Transaction_Types_ID]
    	)

    
    Alter Table [dbo].[AS_Transactions] nocheck constraint [FK_AS_Transactions_AW_Comments]

    SET @ReturnValue = 1

END

RETURN @ReturnValue
GO

--15 sp_AW_9910
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AW_9910]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AW_9910]
GO
-------------------------------------------------------------------------------
--Description   :sp_AW_9910
--Purpose       :Wipe all SUPPLIER Account Balances & Transaction tables
--Date          :2001/10/14
--Authors       :TB
--MODS          :
--2004.5.5      :10/11/11 - Refreshed with latest table defs - 2004.5.5
--2015.6.0      :2015-02-02 - Refreshed with latest table defs - 2015.6.0
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AW_9910]

AS

SET NOCOUNT ON

DECLARE @ReturnValue bit
SET @ReturnValue = 0

BEGIN

    UPDATE AO_Suppliers
    SET Account_Balance = 0,
        Current_Balance = 0,
        Days_30 = 0,
        Days_60 = 0,
        Days_90 = 0,
        Days_120 = 0,
        Days_150 = 0,
        Days_180 = 0


    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_AO_Order_Items_AO_Orders]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
    ALTER TABLE [dbo].[AO_Order_Details] DROP CONSTRAINT FK_AO_Order_Items_AO_Orders

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AO_Enterprise_Ageing_Temp]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AO_Enterprise_Ageing_Temp]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AO_Enterprise_Supplier_Ageing]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AO_Enterprise_Supplier_Ageing]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AO_GRV]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AO_GRV]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AO_GRV_Details]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AO_GRV_Details]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AO_Order_Candidates]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AO_Order_Candidates]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AO_Order_Candidates_Temp]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AO_Order_Candidates_Temp]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AO_Order_Details]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AO_Order_Details]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AO_Orders]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AO_Orders]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AO_Remittance_Details_Temp]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AO_Remittance_Details_Temp]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AO_Remittances_Temp]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AO_Remittances_Temp]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AO_Statement_Details]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AO_Statement_Details]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AO_Statements]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AO_Statements]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AO_Supplier_Contracts]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AO_Supplier_Contracts]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AO_Supplier_Product_Discounts]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AO_Supplier_Product_Discounts]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AO_Transaction_Payments]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AO_Transaction_Payments]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AO_Transactions]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AO_Transactions]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AO_Transactions_Log]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AO_Transactions_Log]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AO_Transactions_Transactions]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AO_Transactions_Transactions]

    
    CREATE TABLE [dbo].[AO_Enterprise_Ageing_Temp] (
    	[AO_Enterprise_Ageing_Temp_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Filter] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[AO_Suppliers_ID] [int] NULL ,
    	[Supplier_Name] [varchar] (92) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Supplier_Number] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Amount] [money] NULL ,
    	[Payment] [money] NULL ,
    	[Account_Balance] [money] NULL ,
    	[Current] [money] NULL ,
    	[30Days] [money] NULL ,
    	[60Days] [money] NULL ,
    	[90Days] [money] NULL ,
    	[120Days] [money] NULL ,
    	[150Days] [money] NULL ,
    	[180+Days] [money] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AO_Enterprise_Supplier_Ageing] (
    	[AO_Enterprise_Supplier_Ageing_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[CompanyID] [int] NULL ,
    	[SourceDB] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Filter] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Supplier] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[SuppNo] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Total] [money] NULL ,
    	[Balance] [money] NULL ,
    	[Days0] [money] NULL ,
    	[Days30] [money] NULL ,
    	[Days60] [money] NULL ,
    	[Days90] [money] NULL ,
    	[Days120] [money] NULL ,
    	[Days150] [money] NULL ,
    	[Days180] [money] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AO_GRV] (
    	[AO_GRV_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Sys_AW_Transaction_Types_ID] [tinyint] NULL ,
    	[AO_Suppliers_ID] [int] NULL ,
    	[AO_Orders_ID] [int] NULL ,
    	[Date_Received] [datetime] NULL ,
    	[Delivery_Note_Number] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Supplier_Reference] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Trade_Discount_Total] [money] NULL ,
    	[Rebate_Discount_Total] [money] NULL ,
    	[Other_Discount_Total] [money] NULL ,
    	[Net_Amount] [money] NULL ,
    	[Total_Tax_Amount] [money] NULL ,
    	[Total_Amount] [money] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AO_GRV_Details] (
    	[AO_GRV_Details_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AO_GRV_ID] [int] NOT NULL ,
    	[AP_Products_ID] [int] NULL ,
    	[AB_Accounts_ID] [int] NULL ,
    	[Qty] [decimal](12, 3) NULL ,
    	[Unit_Price] [money] NULL ,
    	[Trade_Discount_Amount] [money] NULL ,
    	[Rebate_Discount_Amount] [money] NULL ,
    	[Other_Discount_Amount] [money] NULL ,
    	[Net_Amount] [money] NULL ,
    	[Sys_AW_Tax_Codes_ID] [int] NULL ,
    	[Tax_Amount] [money] NULL ,
    	[Total_Cost] [money] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AO_Order_Candidates] (
    	[AO_Order_Candidates_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Ready] [bit] NULL ,
    	[AP_Products_ID] [int] NULL ,
    	[AO_Suppliers_ID] [int] NULL ,
    	[Order_Date] [datetime] NULL ,
    	[Qty] [decimal](9, 3) NULL ,
    	[Last_Cost] [money] NULL ,
    	[Notes] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Reviews] [int] NULL ,
    	[Originator] [int] NULL ,
    	[AW_Remote_Access_ID] [int] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AO_Order_Candidates_Temp] (
    	[AO_Order_Candidates_Temp_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Order_Item] [bit] NULL ,
    	[AW_Remote_Access_ID] [int] NULL ,
    	[AO_Suppliers_ID] [int] NULL ,
    	[AP_Products_ID] [int] NOT NULL ,
    	[Product_Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Product_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[On_Hand] [decimal](9, 3) NULL ,
    	[Order_Qty] [decimal](9, 3) NULL ,
    	[Selling] [money] NULL ,
    	[Trade_Discount] [money] NULL ,
    	[Cost] AS (round(([Selling] - [Selling] * [Trade_Discount] / 100),2)) ,
    	[Total_Cost] AS (round(([Order_Qty] * ([Selling] - [Selling] * [Trade_Discount] / 100)),2)) ,
    	[Last_Cost] [money] NULL ,
    	[Outstanding_Order_Qty] [decimal](9, 3) NULL ,
    	[Pending_Order_Qty] [decimal](9, 3) NULL ,
    	[Last_Order_Date] [datetime] NULL ,
    	[Last_Sale_Date] [datetime] NULL ,
    	[Service_Level] [decimal](9, 3) NULL ,
    	[Min_Stock_Level] [decimal](9, 3) NULL ,
    	[Max_Order_Qty] [decimal](9, 3) NULL ,
    	[Min_Order_Qty] [decimal](9, 3) NULL ,
    	[Sales_Order_Reserved] [decimal](9, 3) NULL ,
    	[Job_Reserved] [decimal](9, 3) NULL ,
    	[Notes] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AO_Order_Details] (
    	[AO_Order_Details_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AO_Orders_ID] [int] NOT NULL ,
    	[AP_Products_ID] [int] NULL ,
    	[Lead_Time] [smallint] NULL ,
    	[Order_Qty] [decimal](9, 3) NULL ,
    	[Free_Qty] [decimal](9, 3) NULL ,
    	[Back_Order_Qty] [decimal](9, 3) NULL ,
    	[Receipt_Date] [datetime] NULL ,
    	[Received_Qty] [decimal](9, 3) NULL ,
    	[Unit_Price] [money] NULL ,
    	[Trade_Discount_Formula_ID] [smallint] NULL ,
    	[Trade_Discount_Amount] [money] NULL ,
    	[Trade_Discount_Percentage] [decimal](19, 4) NULL ,
    	[Rebate_Formula_ID] [smallint] NULL ,
    	[Rebate_Discount_Amount] [money] NULL ,
    	[Rebate_Discount_Percentage] [decimal](19, 4) NULL ,
    	[Other_Discount_Formula_ID] [smallint] NULL ,
    	[Other_Discount_Amount] [money] NULL ,
    	[Other_Discount_Percentage] [decimal](19, 4) NULL ,
    	[Net_Amount] [money] NULL ,
    	[Sys_AW_Tax_Codes_ID] [int] NULL ,
    	[Tax_Amount] [money] NULL ,
    	[Total_Cost] [money] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AO_Orders] (
    	[AO_Orders_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Order_Number] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Order_Date] [datetime] NULL ,
    	[Version] [tinyint] NULL ,
    	[AW_Remote_Access_ID] [int] NULL ,
    	[AO_Suppliers_ID] [int] NULL ,
    	[Supplier_Rep] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Supplier_Type] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Ordered] [datetime] NULL ,
    	[Confirmation] [tinyint] NULL ,
    	[Confirmation_Date] [datetime] NULL ,
    	[Our_Ref] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Supplier_Reference] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Invoice_Type] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Invoice_Total] [money] NULL ,
    	[Admin_Fee] [money] NULL ,
    	[Trade_Discount_Total] [money] NULL ,
    	[Rebate_Discount_Total] [money] NULL ,
    	[Other_Discount_Total] [money] NULL ,
    	[Net_Amount] [money] NULL ,
    	[Tax_Total] [money] NULL ,
    	[Order_Total] [money] NULL ,
    	[Sys_AO_Delivery_Methods_ID] [int] NULL ,
    	[Send_To_Address] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Delivery_Addr1] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Delivery_Addr2] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Delivery_Addr3] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Postal_Code] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Complete] [bit] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AO_Remittance_Details_Temp] (
    	[AO_Remittance_Details_Temp_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AO_Remittances_Temp_ID] [int] NULL ,
    	[AO_Transactions_ID] [int] NULL ,
    	[AB_Accounts_ID] [int] NULL ,
    	[Transaction_Date] [datetime] NULL ,
    	[Sys_AW_Transaction_Types_ID] [int] NULL ,
    	[Transaction_Number] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Amount] [money] NULL ,
    	[Payment] [money] NULL ,
    	[Settlement_Discount] [money] NULL ,
    	[To_Be_Paid] [bit] NULL ,
    	[To_Be_Paid_Amount] [money] NULL ,
    	[Remittance_Balance] [money] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AO_Remittances_Temp] (
    	[AO_Remittances_Temp_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AW_Period_Procedures_ID] [int] NULL ,
    	[AO_Suppliers_ID] [int] NULL ,
    	[Supplier] [varchar] (92) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Supplier_Number] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Credit_Limit] [money] NULL ,
    	[Credit_Terms] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Default_Settlement_Discount] [decimal](7, 2) NULL ,
    	[Supplier_Contact] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Supplier_Telephone] [varchar] (12) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Contact_Cellphone] [varchar] (12) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Supplier_Fax] [varchar] (12) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Post_Box] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Post_Office] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Post_Code] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Email_Address] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Amount] [money] NULL ,
    	[Payment] [money] NULL ,
    	[Account_Balance] [money] NULL ,
    	[To_Be_Paid_Total] [money] NULL ,
    	[Current] [money] NULL ,
    	[30Days] [money] NULL ,
    	[60Days] [money] NULL ,
    	[90Days] [money] NULL ,
    	[120Days] [money] NULL ,
    	[150Days] [money] NULL ,
    	[180+Days] [money] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AO_Statement_Details] (
    	[AO_Statement_Details_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AO_Statements_ID] [int] NULL ,
    	[AO_Transactions_ID] [int] NULL ,
    	[AO_Suppliers_ID] [int] NULL ,
    	[AB_Accounts_ID] [int] NULL ,
    	[Supplier_Reference] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Sys_AW_Transaction_Types_ID] [tinyint] NULL ,
    	[Document_Number] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Document_Date] [datetime] NULL ,
    	[Slu_AW_Months_ID] [tinyint] NULL ,
    	[Slu_AW_Years_ID] [int] NULL ,
    	[AO_GRV_ID] [int] NULL ,
    	[Comment] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[AW_Comments_ID] [int] NULL ,
    	[Trade_Discount_Total] [money] NULL ,
    	[Rebate_Discount_Total] [money] NULL ,
    	[Other_Discount_Total] [money] NULL ,
    	[Net_Amount] [money] NULL ,
    	[Total_Tax_Amount] [money] NULL ,
    	[Total_Amount] [money] NULL ,
    	[Payment_Amount] [money] NULL ,
    	[Settlement_Discount] [money] NULL ,
    	[To_Be_Paid] [bit] NULL ,
    	[To_Be_Paid_Amount] [money] NULL ,
    	[Remittance_Balance] [money] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AO_Statements] (
    	[AO_Statements_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AW_Period_Procedures_ID] [int] NULL ,
    	[AO_Suppliers_ID] [int] NULL ,
    	[FullName] [varchar] (92) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Supplier_Number] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Post_Address] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Post_Office] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Post_Code] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Email_Address] [varchar] (40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Amount] [money] NULL ,
    	[Payment] [money] NULL ,
    	[Account_Balance] [money] NULL ,
    	[Current] [money] NULL ,
    	[30Days] [money] NULL ,
    	[60Days] [money] NULL ,
    	[90Days] [money] NULL ,
    	[120Days] [money] NULL ,
    	[150Days] [money] NULL ,
    	[180+Days] [money] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AO_Supplier_Contracts] (
    	[AO_Supplier_Contracts_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AO_Suppliers_ID] [int] NULL ,
    	[AP_Products_ID] [int] NULL ,
    	[Start_Date] [datetime] NULL ,
    	[End_Date] [datetime] NULL ,
    	[Packs_Contract_Price] [money] NULL ,
    	[Packs_Contract_Qty] [decimal](6, 3) NULL ,
    	[Packs_Purchased] [decimal](6, 3) NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [int] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AO_Supplier_Product_Discounts] (
    	[AO_Supplier_Product_Discounts_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Description] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[AO_Suppliers_ID] [int] NULL ,
    	[AP_Products_ID] [int] NULL ,
    	[Lup_AO_Discount_Types_ID] [int] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AO_Transaction_Payments] (
    	[AO_Transaction_Payments_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AO_Transactions_ID] [int] NULL ,
    	[Sys_AW_Payment_Methods_ID] [tinyint] NULL ,
    	[AW_Company_Banks_ID] [int] NULL ,
    	[Number] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Amount] [money] NULL ,
    	[Tran_Ref_No] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AO_Transactions] (
    	[AO_Transactions_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AO_Suppliers_ID] [int] NULL ,
    	[AB_Accounts_ID] [int] NULL ,
    	[Supplier_Reference] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Sys_AW_Transaction_Types_ID] [tinyint] NULL ,
    	[Document_Number] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Document_Date] [datetime] NULL ,
    	[Slu_AW_Months_ID] [tinyint] NULL ,
    	[Slu_AW_Years_ID] [int] NULL ,
    	[AO_GRV_ID] [int] NULL ,
    	[Comment] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[AW_Comments_ID] [int] NULL ,
    	[Trade_Discount_Total] [money] NULL ,
    	[Rebate_Discount_Total] [money] NULL ,
    	[Other_Discount_Total] [money] NULL ,
    	[Net_Amount] [money] NULL ,
    	[Total_Tax_Amount] [money] NULL ,
    	[Total_Amount] [money] NULL ,
    	[Payment_Amount] [money] NULL ,
    	[Settlement_Discount] [money] NULL ,
    	[To_Be_Paid] [bit] NULL ,
    	[To_Be_Paid_Amount] [money] NULL ,
    	[Remittance_Balance] [money] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AO_Transactions_Log] (
    	[AO_Transactions_Log_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AO_Suppliers_ID] [int] NULL ,
    	[AO_Transactions_ID] [int] NULL ,
    	[AO_GRV_ID] [int] NULL ,
    	[Posted_Month_ID] [tinyint] NULL ,
    	[Posted_Year_ID] [int] NULL ,
    	[Current_Month_ID] [tinyint] NULL ,
    	[Current_Year_ID] [int] NULL ,
    	[LastME_Month_ID] [tinyint] NULL ,
    	[LastME_Year_ID] [int] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AO_Transactions_Transactions] (
    	[AO_Transactions_Transactions_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Source_AO_Transactions_ID] [int] NULL ,
    	[Destination_AO_Transactions_ID] [int] NULL ,
    	[Amount] [money] NULL ,
    	[AB_Accounts_ID] [int] NULL ,
    	[Tran_Ref_No] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    ALTER TABLE [dbo].[AO_GRV] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AO_GRV] PRIMARY KEY  CLUSTERED 
    	(
    		[AO_GRV_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AO_GRV_Details] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AO_GRV_Details] PRIMARY KEY  CLUSTERED 
    	(
    		[AO_GRV_Details_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AO_Order_Candidates] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AO_Order_Candidates] PRIMARY KEY  CLUSTERED 
    	(
    		[AO_Order_Candidates_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AO_Order_Candidates_Temp] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AO_Order_Candidates_Temp] PRIMARY KEY  CLUSTERED 
    	(
    		[AO_Order_Candidates_Temp_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AO_Orders] WITH NOCHECK ADD 
    	CONSTRAINT [PK_Orders] PRIMARY KEY  CLUSTERED 
    	(
    		[AO_Orders_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AO_Supplier_Contracts] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AO_Supplier_Contracts] PRIMARY KEY  CLUSTERED 
    	(
    		[AO_Supplier_Contracts_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AO_Supplier_Product_Discounts] WITH NOCHECK ADD 
    	CONSTRAINT [PK_Supplier_Discounts] PRIMARY KEY  CLUSTERED 
    	(
    		[AO_Supplier_Product_Discounts_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AO_Transaction_Payments] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AO_Purchase_Transaction_Payments] PRIMARY KEY  CLUSTERED 
    	(
    		[AO_Transaction_Payments_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AO_Transactions] WITH NOCHECK ADD 
    	CONSTRAINT [PK_Purchase_Transactions] PRIMARY KEY  CLUSTERED 
    	(
    		[AO_Transactions_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AO_Transactions_Log] WITH NOCHECK ADD 
    	CONSTRAINT [PK_Purchase_Transactions_Log] PRIMARY KEY  CLUSTERED 
    	(
    		[AO_Transactions_Log_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AO_Transactions_Transactions] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AO_Purchase_Transactions_Transactions] PRIMARY KEY  CLUSTERED 
    	(
    		[AO_Transactions_Transactions_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
     CREATE  CLUSTERED  INDEX [IX_AO_Enterprise_Ageing_Temp] ON [dbo].[AO_Enterprise_Ageing_Temp]([Filter], [Supplier_Name], [Supplier_Number]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [IX_AO_Enterprise_Supplier_Ageing] ON [dbo].[AO_Enterprise_Supplier_Ageing]([Filter], [Supplier], [SuppNo]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [CI_Order_Items_Orders_ID] ON [dbo].[AO_Order_Details]([AO_Orders_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  UNIQUE  CLUSTERED  INDEX [PK_AO_Remittance_Details_Temp] ON [dbo].[AO_Remittance_Details_Temp]([AO_Remittance_Details_Temp_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  UNIQUE  CLUSTERED  INDEX [PK_AO_Remittances_Temp] ON [dbo].[AO_Remittances_Temp]([AO_Remittances_Temp_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  UNIQUE  CLUSTERED  INDEX [PK_AO_Statement_Details] ON [dbo].[AO_Statement_Details]([AO_Statement_Details_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  UNIQUE  CLUSTERED  INDEX [PK_AO_Statements] ON [dbo].[AO_Statements]([AO_Statements_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
    ALTER TABLE [dbo].[AO_Enterprise_Ageing_Temp] ADD 
    	CONSTRAINT [PK_AO_Enterprise_Ageing_Temp] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AO_Enterprise_Ageing_Temp_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AO_Enterprise_Supplier_Ageing] ADD 
    	CONSTRAINT [PK_AO_Enterprise_Supplier_Ageing] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AO_Enterprise_Supplier_Ageing_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
     CREATE  INDEX [IX_AO_GRV_AW_Transaction_Types_ID] ON [dbo].[AO_GRV]([Sys_AW_Transaction_Types_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  INDEX [IX_AO_Order_Candidates_AP_Products_ID] ON [dbo].[AO_Order_Candidates]([AP_Products_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  INDEX [IX_AO_Order_Candidates_Temp_AP_Products_ID] ON [dbo].[AO_Order_Candidates_Temp]([AP_Products_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
    ALTER TABLE [dbo].[AO_Order_Details] ADD 
    	CONSTRAINT [PK_Order_Items] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AO_Order_Details_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
     CREATE  INDEX [IX_AO_Order_Items_AP_Products_ID] ON [dbo].[AO_Order_Details]([AP_Products_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  INDEX [IX_AO_Orders_AO_Suppliers_ID] ON [dbo].[AO_Orders]([AO_Suppliers_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  INDEX [IX_AO_Open_Orders] ON [dbo].[AO_Orders]([Date_Ordered], [Complete]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  INDEX [IX_AO_Statement_Details_Key] ON [dbo].[AO_Statement_Details]([AO_Statements_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  INDEX [IX_AO_Statements_Key] ON [dbo].[AO_Statements]([AW_Period_Procedures_ID], [FullName]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  INDEX [IX_AO_Supplier_Contracts_AP_Products_ID] ON [dbo].[AO_Supplier_Contracts]([AP_Products_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  INDEX [IX_AO_Supplier_Contracts_AP_Suppliers_ID] ON [dbo].[AO_Supplier_Contracts]([AO_Suppliers_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  INDEX [IX_AO_Supplier_Product_Discounts_AP_Products_ID] ON [dbo].[AO_Supplier_Product_Discounts]([AP_Products_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  INDEX [IX_AO_Transactions_AO_GRV_ID] ON [dbo].[AO_Transactions]([AO_GRV_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
    setuser
    --Defaults XXX
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AO_Enterprise_Ageing_Temp].[Date_Captured]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AO_Enterprise_Ageing_Temp].[User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AO_Enterprise_Ageing_Temp].[AW_User_Companies_ID]'
    
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Enterprise_Ageing_Temp].[120Days]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Enterprise_Ageing_Temp].[150Days]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Enterprise_Ageing_Temp].[180+Days]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Enterprise_Ageing_Temp].[30Days]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Enterprise_Ageing_Temp].[60Days]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Enterprise_Ageing_Temp].[90Days]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Enterprise_Ageing_Temp].[Account_Balance]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Enterprise_Ageing_Temp].[Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Enterprise_Ageing_Temp].[Current]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Enterprise_Ageing_Temp].[Payment]'
    
    setuser

    
    setuser
    --Defaults XXX
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AO_Enterprise_Supplier_Ageing].[CompanyID]'

    
    setuser

    
    setuser
    --Defaults XXX
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AO_GRV].[AO_Suppliers_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AO_GRV].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AO_GRV].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_GRV].[Net_Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_GRV].[Other_Discount_Total]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_GRV].[Rebate_Discount_Total]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AO_GRV].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_GRV].[Total_Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_GRV].[Total_Tax_Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_GRV].[Trade_Discount_Total]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AO_GRV].[User_ID]'

    
    setuser

    
    setuser
    --Defaults XXX
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AO_GRV_Details].[AB_Accounts_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AO_GRV_Details].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AO_GRV_Details].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_GRV_Details].[Net_Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_GRV_Details].[Other_Discount_Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_GRV_Details].[Qty]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_GRV_Details].[Rebate_Discount_Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AO_GRV_Details].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AO_GRV_Details].[Sys_AW_Tax_Codes_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_GRV_Details].[Tax_Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_GRV_Details].[Total_Cost]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_GRV_Details].[Trade_Discount_Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_GRV_Details].[Unit_Price]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AO_GRV_Details].[User_ID]'

    
    setuser

    
    setuser
	--Defaults XXX    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AO_Order_Candidates].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AO_Order_Candidates].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates].[Last_Cost]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AO_Order_Candidates].[Order_Date]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates].[Originator]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates].[Qty]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates].[Ready]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates].[Reviews]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AO_Order_Candidates].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AO_Order_Candidates].[User_ID]'

    
    setuser

    
    setuser
	--Defaults XXX    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AO_Order_Candidates_Temp].[AO_Suppliers_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AO_Order_Candidates_Temp].[AW_User_Companies_ID]'

    --Computed
    --EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates_Temp].[Cost]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AO_Order_Candidates_Temp].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates_Temp].[Job_Reserved]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates_Temp].[Max_Order_Qty]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates_Temp].[Min_Order_Qty]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates_Temp].[Min_Stock_Level]'

    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AO_Order_Candidates_Temp].[Notes]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates_Temp].[On_Hand]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates_Temp].[Order_Item]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates_Temp].[Order_Qty]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates_Temp].[Outstanding_Order_Qty]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates_Temp].[Pending_Order_Qty]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates_Temp].[Sales_Order_Reserved]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates_Temp].[Selling]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AO_Order_Candidates_Temp].[Service_Level]'

    --Computed
	--EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates_Temp].[Total_Cost]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Candidates_Temp].[Trade_Discount]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AO_Order_Candidates_Temp].[User_ID]'

    
    setuser

    
    setuser
	--Defaults XXX    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AO_Order_Details].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Details].[Back_Order_Qty]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AO_Order_Details].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Details].[Free_Qty]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Details].[Lead_Time]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Details].[Net_Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Details].[Order_Qty]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Details].[Other_Discount_Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AO_Order_Details].[Other_Discount_Formula_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Details].[Other_Discount_Percentage]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Details].[Rebate_Discount_Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Details].[Rebate_Discount_Percentage]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AO_Order_Details].[Rebate_Formula_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Details].[Received_Qty]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AO_Order_Details].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AO_Order_Details].[Sys_AW_Tax_Codes_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Details].[Tax_Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Details].[Total_Cost]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Details].[Trade_Discount_Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AO_Order_Details].[Trade_Discount_Formula_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Details].[Trade_Discount_Percentage]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Order_Details].[Unit_Price]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AO_Order_Details].[User_ID]'

    
    setuser

    
    setuser
	--Defaults XXX    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Orders].[Admin_Fee]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AO_Orders].[AO_Suppliers_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AO_Orders].[AW_Remote_Access_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AO_Orders].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Orders].[Complete]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Orders].[Confirmation]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AO_Orders].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Orders].[Invoice_Total]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Orders].[Net_Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Orders].[Order_Total]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Orders].[Other_Discount_Total]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Orders].[Rebate_Discount_Total]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AO_Orders].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Orders].[Tax_Total]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Orders].[Trade_Discount_Total]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AO_Orders].[User_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Orders].[Version]'

    
    setuser

    
    setuser
	--Defaults XXX    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AO_Remittances_Temp].[Date_Captured]'

    
    setuser

    
    setuser
    --Defaults XXX
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AO_Statements].[Date_Captured]'

    
    setuser

    
    setuser
	--Defaults XXX    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AO_Supplier_Contracts].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AO_Supplier_Contracts].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Supplier_Contracts].[Packs_Contract_Price]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Supplier_Contracts].[Packs_Contract_Qty]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Supplier_Contracts].[Packs_Purchased]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AO_Supplier_Contracts].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AO_Supplier_Contracts].[User_ID]'

    
    setuser

    
    setuser
	--Defaults XXX    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AO_Supplier_Product_Discounts].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AO_Supplier_Product_Discounts].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AO_Supplier_Product_Discounts].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AO_Supplier_Product_Discounts].[User_ID]'

    
    setuser

    
    setuser
	--Defaults XXX    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Transaction_Payments].[Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AO_Transaction_Payments].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AO_Transaction_Payments].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AO_Transaction_Payments].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AO_Transaction_Payments].[Tran_Ref_No]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AO_Transaction_Payments].[User_ID]'

    
    setuser

    
    setuser
	--Defaults XXX    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AO_Transactions].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AO_Transactions].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Transactions].[Net_Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Transactions].[Other_Discount_Total]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Transactions].[Payment_Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Transactions].[Rebate_Discount_Total]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Transactions].[Remittance_Balance]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Transactions].[Settlement_Discount]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AO_Transactions].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Transactions].[To_Be_Paid]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Transactions].[To_Be_Paid_Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Transactions].[Total_Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Transactions].[Total_Tax_Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Transactions].[Trade_Discount_Total]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AO_Transactions].[User_ID]'

    
    setuser

    
    setuser
	--Defaults XXX    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AO_Transactions_Log].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AO_Transactions_Log].[Date_Captured]'

    
    setuser

    
    setuser
	--Defaults XXX    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AO_Transactions_Transactions].[Amount]'

    
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AO_Transactions_Transactions].[AW_User_Companies_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AO_Transactions_Transactions].[Date_Captured]'

    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AO_Transactions_Transactions].[Slu_AW_Active_ID]'

    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AO_Transactions_Transactions].[Tran_Ref_No]'

    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AO_Transactions_Transactions].[User_ID]'

    
    setuser

    
    ALTER TABLE [dbo].[AO_Order_Details] ADD 
    	CONSTRAINT [FK_AO_Order_Items_AO_Orders] FOREIGN KEY 
    	(
    		[AO_Orders_ID]
    	) REFERENCES [dbo].[AO_Orders] (
    		[AO_Orders_ID]
    	)

    
    ALTER TABLE [dbo].[AO_Transactions] ADD 
    	CONSTRAINT [FK_AO_Purchase_Transactions_Lup_AW_Transaction_Types] FOREIGN KEY 
    	(
    		[Sys_AW_Transaction_Types_ID]
    	) REFERENCES [dbo].[Sys_AW_Transaction_Types] (
    		[Sys_AW_Transaction_Types_ID]
    	)

    SET @ReturnValue = 1

END

RETURN @ReturnValue
GO

--16 sp_AW_9920
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AW_9920]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AW_9920]
GO
-------------------------------------------------------------------------------
--Description   :sp_AW_9920
--Purpose       :Wipe all GENERAL LEDGER Transaction tables
--              :
--Parameters    :
--Date          :2001/10/14
--Authors       :TB
--MODS          :
--2004.5.5      :10/11/11 - Refreshed with latest table defs - 2004.5.5
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AW_9920]

AS

SET NOCOUNT ON

DECLARE @ReturnValue bit

SET @ReturnValue = 0

BEGIN

    --------------------------------------------------------------------------------
    --Clear GL Account Balances

    UPDATE AB_Accounts
    SET AB_Account_Balance = 0,
        Opening_Balance = 0,
        Opening_Date = NULL,
        Opening_Month = 0,
        Opening_Year = 0
    --------------------------------------------------------------------------------
    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_AB_Cash_Book_Transaction_Details_AB_Cash_Book_Transactions]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
    ALTER TABLE [dbo].[AB_Cash_Book_Transaction_Details] DROP CONSTRAINT FK_AB_Cash_Book_Transaction_Details_AB_Cash_Book_Transactions

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_AB_Journal_Details_AB_Journals]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
    ALTER TABLE [dbo].[AB_Journal_Details] DROP CONSTRAINT FK_AB_Journal_Details_AB_Journals

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_AB_Recurring_Details_AB_Recurring]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
    ALTER TABLE [dbo].[AB_Recurring_Details] DROP CONSTRAINT FK_AB_Recurring_Details_AB_Recurring

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Budgets]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Budgets]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Cash_Book_Batches]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Cash_Book_Batches]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Cash_Book_IBS_Detail]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Cash_Book_IBS_Detail]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Cash_Book_IBS_Detail_Splits]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Cash_Book_IBS_Detail_Splits]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Cash_Book_IBS_Header]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Cash_Book_IBS_Header]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Cash_Book_IBS_Map]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Cash_Book_IBS_Map]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Cash_Book_IBS_Map_Splits]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Cash_Book_IBS_Map_Splits]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Cash_Book_IBS_Notes]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Cash_Book_IBS_Notes]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Cash_Book_Transaction_Details]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Cash_Book_Transaction_Details]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Cash_Book_Transactions]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Cash_Book_Transactions]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Cash_Flow_Forecast_Temp]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Cash_Flow_Forecast_Temp]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Cash_Inflow_Projections]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Cash_Inflow_Projections]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Cash_Outflow_Projections]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Cash_Outflow_Projections]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Enterprise_Balance_Sheet]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Enterprise_Balance_Sheet]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Enterprise_Income_Statement]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Enterprise_Income_Statement]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Enterprise_Management_Accounts]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Enterprise_Management_Accounts]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Enterprise_Trial_Balance]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Enterprise_Trial_Balance]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_GL_Transactions]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_GL_Transactions]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Journal_Details]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Journal_Details]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Journals]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Journals]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Recurring]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Recurring]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AB_Recurring_Details]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AB_Recurring_Details]


    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AW_Period_Procedures]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AW_Period_Procedures]


    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AW_Period_Procedures_Deleted]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AW_Period_Procedures_Deleted]

    
    CREATE TABLE [dbo].[AB_Budgets] (
    	[AB_Budgets_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AB_Accounts_ID] [int] NOT NULL ,
    	[Slu_AW_Years_ID] [int] NOT NULL ,
    	[Slu_AW_Months_ID] [tinyint] NOT NULL ,
    	[Budget_Amount] [money] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AB_Cash_Book_Batches] (
    	[AB_Cash_Book_Batches_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AW_Company_Banks_ID] [int] NULL ,
    	[Sys_AB_Transaction_Types_ID] [tinyint] NULL ,
    	[Slu_AW_Months_ID] [tinyint] NULL ,
    	[Slu_AW_Years_ID] [smallint] NULL ,
    	[Transaction_Date] [datetime] NULL ,
    	[Ref_No] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Amount] [money] NULL ,
    	[AB_Accounts_ID] [int] NULL ,
    	[Sys_AW_Tax_Methods_ID] [tinyint] NULL ,
    	[Split_Amount] [money] NULL ,
    	[VAT_Amount] [money] NULL ,
    	[Net_Amount] [money] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AB_Cash_Book_IBS_Detail] (
    	[AB_Cash_Book_IBS_Detail_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AB_Cash_Book_IBS_Header_ID] [int] NOT NULL ,
    	[Post] [bit] NOT NULL ,
    	[Sys_AB_Transaction_Types_ID] [tinyint] NOT NULL ,
    	[Transaction_Date] [datetime] NOT NULL ,
    	[Ref_No] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
    	[AB_Accounts_ID] [int] NOT NULL ,
    	[Sys_AW_Tax_Methods_ID] [tinyint] NOT NULL ,
    	[Post_Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Amount] [money] NOT NULL ,
    	[Tax_Amount] [money] NOT NULL ,
    	[Net_Amount] [money] NOT NULL ,
    	[Comments] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Bank_Description] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AB_Cash_Book_IBS_Detail_Splits] (
    	[AB_Cash_Book_IBS_Detail_Splits_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AB_Cash_Book_IBS_Header_ID] [int] NOT NULL ,
    	[AB_Cash_Book_IBS_Detail_ID] [int] NOT NULL ,
    	[AB_Accounts_ID] [int] NOT NULL ,
    	[Sys_AW_Tax_Methods_ID] [tinyint] NOT NULL ,
    	[Amount] [money] NOT NULL ,
    	[Tax_Amount] [money] NOT NULL ,
    	[Net_Amount] [money] NOT NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AB_Cash_Book_IBS_Header] (
    	[AB_Cash_Book_IBS_Header_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AW_Company_Banks_ID] [int] NOT NULL ,
    	[Posting_Type] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Slu_AW_Banks_ID] [smallint] NOT NULL ,
    	[Date_Posted] [datetime] NOT NULL ,
    	[Start_Date] [datetime] NOT NULL ,
    	[End_Date] [datetime] NOT NULL ,
    	[Slu_AW_Months_ID] [tinyint] NOT NULL ,
    	[Slu_AW_Years_ID] [smallint] NOT NULL ,
    	[Import_Filename] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Auto_Recon] [tinyint] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AB_Cash_Book_IBS_Map] (
    	[AB_Cash_Book_IBS_Map_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AW_Company_Banks_ID] [int] NULL ,
    	[Post] [bit] NULL ,
    	[Sys_AB_Transaction_Types_ID] [tinyint] NULL ,
    	[Map_1] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Map_2] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Map_3] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[AB_Accounts_ID] [int] NULL ,
    	[Sys_AW_Tax_Methods_ID] [tinyint] NULL ,
    	[Bank_Description] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Comments] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AB_Cash_Book_IBS_Map_Splits] (
    	[AB_Cash_Book_IBS_Map_Splits_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AW_Company_Banks_ID] [int] NULL ,
    	[AB_Cash_Book_IBS_Map_ID] [int] NOT NULL ,
    	[AB_Accounts_ID] [int] NULL ,
    	[Sys_AW_Tax_Methods_ID] [tinyint] NULL ,
    	[Amount] [money] NULL ,
    	[Tax_Amount] [money] NULL ,
    	[Net_Amount] [money] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AB_Cash_Book_IBS_Notes] (
    	[AB_Cash_Book_IBS_Notes_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Note] [varchar] (500) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AB_Cash_Book_Transaction_Details] (
    	[AB_Cash_Book_Transaction_Details_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AB_Cash_Book_Transactions_ID] [int] NULL ,
    	[AB_Accounts_ID] [int] NULL ,
    	[Sys_AW_Tax_Methods_ID] [tinyint] NULL ,
    	[Amount] [money] NULL ,
    	[Sys_AW_Tax_Codes_ID] [tinyint] NULL ,
    	[Tax_Amount] [money] NULL ,
    	[Net_Amount] [money] NULL ,
    	[Comments] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AB_Cash_Book_Transactions] (
    	[AB_Cash_Book_Transactions_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AW_Company_Banks_ID] [int] NULL ,
    	[Sys_AB_Transaction_Types_ID] [tinyint] NULL ,
    	[Transaction_Date] [datetime] NULL ,
    	[Slu_AW_Months_ID] [tinyint] NULL ,
    	[Slu_AW_Years_ID] [smallint] NULL ,
    	[Reference_No] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Transaction_Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Amount] [money] NULL ,
    	[Recon_Amount] [money] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AB_Cash_Flow_Forecast_Temp] (
    	[AB_Cash_Flow_Forecast_Temp_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[N1] [tinyint] NULL ,
    	[M1] [bigint] NULL ,
    	[M2] [bigint] NULL ,
    	[M3] [bigint] NULL ,
    	[M4] [bigint] NULL ,
    	[M5] [bigint] NULL ,
    	[M6] [bigint] NULL ,
    	[T1] [bigint] NULL ,
    	[RowTypeID] [tinyint] NULL ,
    	[StartDate] [datetime] NULL ,
    	[AW_User_Companies_ID] [int] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AB_Cash_Inflow_Projections] (
    	[AB_Cash_Inflow_Projections_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AW_Company_Banks_ID] [int] NULL ,
    	[Post] [bit] NULL ,
    	[Inflow_Date] [datetime] NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Sys_AW_Tax_Methods_ID] [tinyint] NULL ,
    	[Amount] [money] NULL ,
    	[Tax_Amount] [money] NULL ,
    	[Net_Amount] [money] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AB_Cash_Outflow_Projections] (
    	[AB_Cash_Outflow_Projections_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AW_Company_Banks_ID] [int] NULL ,
    	[Post] [bit] NULL ,
    	[Outflow_Date] [datetime] NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Sys_AW_Tax_Methods_ID] [tinyint] NULL ,
    	[Amount] [money] NULL ,
    	[Tax_Amount] [money] NULL ,
    	[Net_Amount] [money] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AB_Enterprise_Balance_Sheet] (
    	[AB_Enterprise_Balance_Sheet_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Sys_AB_B1_ID] [int] NULL ,
    	[Sys_AB_B2_ID] [int] NULL ,
    	[Sys_AB_B3_ID] [int] NULL ,
    	[Account_Number] [varchar] (16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Category] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Level1] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Level2] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Level3] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Account] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Total] [money] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AB_Enterprise_Income_Statement] (
    	[AB_Enterprise_Income_Statement_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Sys_AB_I1_ID] [int] NULL ,
    	[Sys_AB_I2_ID] [int] NULL ,
    	[Sys_AB_I3_ID] [int] NULL ,
    	[Sys_AB_I4_ID] [int] NULL ,
    	[Account_Number] [varchar] (16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Category] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Level1] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Level2] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Level3] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Level4] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Account] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Total] [money] NULL ,
    	[TCRUST] [money] NULL ,
    	[TCSTEEL] [money] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AB_Enterprise_Management_Accounts] (
    	[AB_Enterprise_Management_Accounts_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Sys_AB_I1_ID] [int] NULL ,
    	[Sys_AB_I2_ID] [int] NULL ,
    	[Sys_AB_I3_ID] [int] NULL ,
    	[Sys_AB_I4_ID] [int] NULL ,
    	[Sys_AB_I5_ID] [int] NULL ,
    	[Account_Number] [varchar] (16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Category] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Level1] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Level2] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Level3] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Level4] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Level5] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Account] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Total] [money] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AB_Enterprise_Trial_Balance] (
    	[AB_Enterprise_Trial_Balance_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Account_Number] [varchar] (16) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Category] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Divisions] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Groups] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Total] [money] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AB_GL_Transactions] (
    	[AB_GL_Transactions_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Sys_AB_Transaction_Types_ID] [tinyint] NULL ,
    	[AB_Accounts_ID] [int] NULL ,
    	[AB_Transaction_Date] [datetime] NULL ,
    	[AB_Source_Ref] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Slu_AW_Months_ID] [int] NULL ,
    	[Slu_AW_Years_ID] [int] NULL ,
    	[AB_Transaction_Ref] [int] NULL ,
    	[AB_Transaction_Amount] [money] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AB_Journal_Details] (
    	[AB_Journal_Details_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AB_Journals_ID] [int] NULL ,
    	[AB_Accounts_ID] [int] NULL ,
    	[Amount] [money] NULL ,
    	[Notes] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AB_Journals] (
    	[AB_Journals_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Journal_Date] [datetime] NULL ,
    	[Journal_Reference] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Journal_Narration] [varchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Slu_AW_Months_ID] [int] NULL ,
    	[Slu_AW_Years_ID] [int] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AB_Recurring] (
    	[AB_Recurring_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Recurring_Date] [datetime] NULL ,
    	[Recurring_Reference] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Recurring_Narration] [varchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Slu_AW_Months_ID] [int] NULL ,
    	[Slu_AW_Years_ID] [int] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AB_Recurring_Details] (
    	[AB_Recurring_Details_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AB_Recurring_ID] [int] NULL ,
    	[AB_Accounts_ID] [int] NULL ,
    	[Amount] [money] NULL ,
    	[Notes] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]


	CREATE TABLE [dbo].[AW_Period_Procedures](
		[AW_Period_Procedures_ID] [int] IDENTITY(1,1) NOT NULL,
		[Sys_AW_Period_Procedure_Types_ID] [int] NULL,
		[Description] [varchar](500) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
		[Month] [tinyint] NULL,
		[Year] [smallint] NULL,
		[Month_End_Date] [datetime] NULL,
		[Year_End_Date] [datetime] NULL,
		[Stock_Valuation] [money] NULL,
		[Date_Captured] [smalldatetime] NULL,
		[User_ID] [int] NULL,
		[AW_User_Companies_ID] [int] NULL,
		[Touched] [timestamp] NULL,
		[Slu_AW_Active_ID] [tinyint] NULL
	) ON [PRIMARY]		


	CREATE TABLE [dbo].[AW_Period_Procedures_Deleted](
		[AW_Period_Procedures_Deleted_ID] [int] IDENTITY(1,1) NOT NULL,
		[AW_Period_Procedures_ID] [int] NULL,
		[Sys_AW_Period_Procedure_Types_ID] [int] NULL,
		[Description] [varchar](500) NULL,
		[Month_ID] [tinyint] NULL,
		[Year_ID] [smallint] NULL,
		[Month_End_Date] [datetime] NULL,
		[Year_End_Date] [datetime] NULL,
		[Stock_Valuation] [money] NULL,
		[Date_Captured] [datetime] NULL,
		[User_ID] [int] NULL,
		[AW_User_Companies_ID] [int] NULL
	) ON [PRIMARY]		
		
		
	ALTER TABLE [dbo].[AW_Period_Procedures_Deleted] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AW_Period_Procedures_Deleted] PRIMARY KEY  CLUSTERED 
    	(
    		[AW_Period_Procedures_Deleted_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

			
    ALTER TABLE [dbo].[AW_Period_Procedures] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AW_Period_Procedures] PRIMARY KEY  CLUSTERED 
    	(
    		[AW_Period_Procedures_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AB_Budgets] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AB_Budgets] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_Budgets_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AB_Cash_Book_Batches] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AB_Cash_Book_Batches] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_Cash_Book_Batches_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AB_Cash_Book_IBS_Detail] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AB_Cash_Book_IBS_Detail] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_Cash_Book_IBS_Detail_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AB_Cash_Book_IBS_Detail_Splits] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AB_Cash_Book_IBS_Detail_Splits] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_Cash_Book_IBS_Detail_Splits_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AB_Cash_Book_IBS_Header] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AB_Cash_Book_IBS_Header] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_Cash_Book_IBS_Header_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AB_Cash_Book_IBS_Map] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AB_Cash_Book_IBS_Map] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_Cash_Book_IBS_Map_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AB_Cash_Book_IBS_Map_Splits] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AB_Cash_Book_IBS_Map_Splits] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_Cash_Book_IBS_Map_Splits_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AB_Cash_Book_IBS_Notes] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AB_Cash_Book_IBS_Notes] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_Cash_Book_IBS_Notes_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AB_Cash_Book_Transaction_Details] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AB_Cash_Book_Transaction_Details] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_Cash_Book_Transaction_Details_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AB_Cash_Book_Transactions] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AB_Cash_Book_Transactions] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_Cash_Book_Transactions_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AB_Cash_Inflow_Projections] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AB_Cash_Inflow_Projections] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_Cash_Inflow_Projections_ID]
    	)  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AB_Cash_Outflow_Projections] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AB_Cash_Outflow_Projections] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_Cash_Outflow_Projections_ID]
    	)  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AB_Enterprise_Balance_Sheet] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AB_Enterprise_Balance_Sheet] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_Enterprise_Balance_Sheet_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AB_Enterprise_Income_Statement] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AB_Enterprise_Income_Statement] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_Enterprise_Income_Statement_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AB_Enterprise_Management_Accounts] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AB_Enterprise_Management_Accounts] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_Enterprise_Management_Accounts_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AB_Enterprise_Trial_Balance] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AB_Enterprise_Trial_Balance] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_Enterprise_Trial_Balance_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AB_GL_Transactions] WITH NOCHECK ADD 
    	CONSTRAINT [PK_GL_Transactions] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_GL_Transactions_ID]
    	) WITH  FILLFACTOR = 80  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AB_Journal_Details] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AB_Journal_Details] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_Journal_Details_ID]
    	) WITH  FILLFACTOR = 80  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AB_Journals] WITH NOCHECK ADD 
    	CONSTRAINT [PK_GL_Journals] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_Journals_ID]
    	) WITH  FILLFACTOR = 80  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AB_Recurring] WITH NOCHECK ADD 
    	CONSTRAINT [PK_GL_Recurring] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_Recurring_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AB_Recurring_Details] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AB_Recurring_Details] PRIMARY KEY  CLUSTERED 
    	(
    		[AB_Recurring_Details_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
     CREATE  CLUSTERED  INDEX [CI_AB_Cash_Flow_Forecast_Temp] ON [dbo].[AB_Cash_Flow_Forecast_Temp]([N1], [RowTypeID], [Description]) ON [PRIMARY]

    
     CREATE  INDEX [IX_Cash_Book_IBS_Detail] ON [dbo].[AB_Cash_Book_IBS_Detail]([Transaction_Date], [Bank_Description], [Amount], [Slu_AW_Active_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  INDEX [IX_Cash_Book_IBS_Detail] ON [dbo].[AB_Cash_Book_IBS_Detail_Splits]([AB_Cash_Book_IBS_Header_ID], [AB_Cash_Book_IBS_Detail_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  INDEX [IX_AB_Cash_Book_IBS_Map_Splits] ON [dbo].[AB_Cash_Book_IBS_Map_Splits]([AW_Company_Banks_ID], [AB_Cash_Book_IBS_Map_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  UNIQUE  INDEX [IX_AB_Cash_Flow_Forecast_Temp] ON [dbo].[AB_Cash_Flow_Forecast_Temp]([AB_Cash_Flow_Forecast_Temp_ID]) ON [PRIMARY]

    
    setuser
   
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Budgets].[Budget_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Budgets].[Date_Captured]'
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Budgets].[User_ID]'
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Budgets].[AW_User_Companies_ID]'
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Budgets].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Book_Batches].[Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Book_Batches].[Net_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Current_Month]', N'[AB_Cash_Book_Batches].[Slu_AW_Months_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Current_Year]', N'[AB_Cash_Book_Batches].[Slu_AW_Years_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Book_Batches].[Split_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Book_Batches].[VAT_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Cash_Book_Batches].[Date_Captured]'
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Cash_Book_Batches].[User_ID]'
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Cash_Book_Batches].[AW_User_Companies_ID]'
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Cash_Book_Batches].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Cash_Book_IBS_Detail].[AB_Accounts_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Book_IBS_Detail].[Amount]'
            
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AB_Cash_Book_IBS_Detail].[Bank_Description]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AB_Cash_Book_IBS_Detail].[Comments]'
            
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Book_IBS_Detail].[Net_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AB_Cash_Book_IBS_Detail].[Post_Description]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AB_Cash_Book_IBS_Detail].[Ref_No]'    
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Cash_Book_IBS_Detail].[Sys_AB_Transaction_Types_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Three]', N'[AB_Cash_Book_IBS_Detail].[Sys_AW_Tax_Methods_ID]'
   
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Book_IBS_Detail].[Tax_Amount]'
   
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Cash_Book_IBS_Detail].[Transaction_Date]'
    
	EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Cash_Book_IBS_Detail].[Date_Captured]'
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Cash_Book_IBS_Detail].[User_ID]'   
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Cash_Book_IBS_Detail].[AW_User_Companies_ID]'    
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Cash_Book_IBS_Detail].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Cash_Book_IBS_Detail_Splits].[AB_Accounts_ID]'

    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Book_IBS_Detail_Splits].[Amount]'
  
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Book_IBS_Detail_Splits].[Net_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Three]', N'[AB_Cash_Book_IBS_Detail_Splits].[Sys_AW_Tax_Methods_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Book_IBS_Detail_Splits].[Tax_Amount]'  

	EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Cash_Book_IBS_Detail_Splits].[Date_Captured]'
	EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Cash_Book_IBS_Detail_Splits].[User_ID]'
	EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Cash_Book_IBS_Detail_Splits].[AW_User_Companies_ID]'   
	EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Cash_Book_IBS_Detail_Splits].[Slu_AW_Active_ID]'   
    
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Cash_Book_IBS_Header].[Auto_Recon]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Cash_Book_IBS_Header].[AW_Company_Banks_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Cash_Book_IBS_Header].[Date_Posted]'
    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Cash_Book_IBS_Header].[End_Date]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AB_Cash_Book_IBS_Header].[Import_Filename]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AB_Cash_Book_IBS_Header].[Posting_Type]'
  
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Cash_Book_IBS_Header].[Slu_AW_Banks_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Current_Month]', N'[AB_Cash_Book_IBS_Header].[Slu_AW_Months_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Current_Year]', N'[AB_Cash_Book_IBS_Header].[Slu_AW_Years_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Cash_Book_IBS_Header].[Start_Date]'

    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Cash_Book_IBS_Header].[Date_Captured]'
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Cash_Book_IBS_Header].[User_ID]'
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Cash_Book_IBS_Header].[AW_User_Companies_ID]'
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Cash_Book_IBS_Header].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Cash_Book_IBS_Map].[AB_Accounts_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Cash_Book_IBS_Map].[AW_Company_Banks_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AB_Cash_Book_IBS_Map].[Bank_Description]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AB_Cash_Book_IBS_Map].[Comments]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AB_Cash_Book_IBS_Map].[Map_1]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AB_Cash_Book_IBS_Map].[Map_2]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AB_Cash_Book_IBS_Map].[Map_3]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Cash_Book_IBS_Map].[Sys_AB_Transaction_Types_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Three]', N'[AB_Cash_Book_IBS_Map].[Sys_AW_Tax_Methods_ID]'

    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Cash_Book_IBS_Map].[Date_Captured]'
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Cash_Book_IBS_Map].[User_ID]'
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Cash_Book_IBS_Map].[AW_User_Companies_ID]'
    
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Cash_Book_IBS_Map_Splits].[AB_Accounts_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Cash_Book_IBS_Map_Splits].[AW_Company_Banks_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Three]', N'[AB_Cash_Book_IBS_Map_Splits].[Sys_AW_Tax_Methods_ID]'

    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Cash_Book_IBS_Map_Splits].[Date_Captured]'
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Cash_Book_IBS_Map_Splits].[User_ID]'
	EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Cash_Book_IBS_Map_Splits].[AW_User_Companies_ID]'
    
    setuser

    
    setuser
       
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AB_Cash_Book_IBS_Notes].[Note]'

	EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Cash_Book_IBS_Notes].[Date_Captured]'    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Cash_Book_IBS_Notes].[User_ID]'
	EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Cash_Book_IBS_Notes].[AW_User_Companies_ID]'
    
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Cash_Book_Transaction_Details].[AB_Accounts_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Book_Transaction_Details].[Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Book_Transaction_Details].[Net_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Cash_Book_Transaction_Details].[Sys_AW_Tax_Codes_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Cash_Book_Transaction_Details].[Sys_AW_Tax_Methods_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Book_Transaction_Details].[Tax_Amount]'

    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Cash_Book_Transaction_Details].[Date_Captured]'
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Cash_Book_Transaction_Details].[User_ID]'
	EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Cash_Book_Transaction_Details].[AW_User_Companies_ID]'
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Cash_Book_Transaction_Details].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Book_Transactions].[Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Current_Month]', N'[AB_Cash_Book_Transactions].[Slu_AW_Months_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Current_Year]', N'[AB_Cash_Book_Transactions].[Slu_AW_Years_ID]'

    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Cash_Book_Transactions].[Date_Captured]'
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Cash_Book_Transactions].[User_ID]'
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Cash_Book_Transactions].[AW_User_Companies_ID]'
	EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Cash_Book_Transactions].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
       
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AB_Cash_Flow_Forecast_Temp].[Description]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Flow_Forecast_Temp].[M1]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Flow_Forecast_Temp].[M2]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Flow_Forecast_Temp].[M3]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Flow_Forecast_Temp].[M4]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Flow_Forecast_Temp].[M5]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Flow_Forecast_Temp].[M6]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Flow_Forecast_Temp].[N1]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Flow_Forecast_Temp].[RowTypeID]'
    
    EXEC sp_bindefault N'[dbo].[df_Todays_Date]', N'[AB_Cash_Flow_Forecast_Temp].[StartDate]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Flow_Forecast_Temp].[T1]'
    
	EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Cash_Flow_Forecast_Temp].[AW_User_Companies_ID]'
    
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Inflow_Projections].[Amount]'

    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Cash_Inflow_Projections].[AW_Company_Banks_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AB_Cash_Inflow_Projections].[Description]'
    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Cash_Inflow_Projections].[Inflow_Date]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Inflow_Projections].[Net_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Inflow_Projections].[Tax_Amount]'

    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Cash_Inflow_Projections].[Date_Captured]'
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Cash_Inflow_Projections].[User_ID]'
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Cash_Inflow_Projections].[AW_User_Companies_ID]'
	EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Cash_Inflow_Projections].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Outflow_Projections].[Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AB_Cash_Outflow_Projections].[AW_Company_Banks_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AB_Cash_Outflow_Projections].[Description]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Outflow_Projections].[Net_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Cash_Outflow_Projections].[Outflow_Date]'
   
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Cash_Outflow_Projections].[Tax_Amount]'

    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Cash_Outflow_Projections].[Date_Captured]'
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Cash_Outflow_Projections].[User_ID]'
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Cash_Outflow_Projections].[AW_User_Companies_ID]'
	EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Cash_Outflow_Projections].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_GL_Transactions].[AB_Transaction_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_GL_Transactions].[AB_Transaction_Ref]'
    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_GL_Transactions].[Date_Captured]'
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_GL_Transactions].[User_ID]'
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_GL_Transactions].[AW_User_Companies_ID]'
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_GL_Transactions].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Journal_Details].[Amount]'

    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Journal_Details].[Date_Captured]'
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Journal_Details].[User_ID]'
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Journal_Details].[AW_User_Companies_ID]'
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Journal_Details].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Journals].[Date_Captured]'
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Journals].[User_ID]'
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Journals].[AW_User_Companies_ID]'
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Journals].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Recurring].[Date_Captured]'   
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Recurring].[User_ID]'
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Recurring].[AW_User_Companies_ID]'
	EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Recurring].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AB_Recurring_Details].[Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AB_Recurring_Details].[Date_Captured]'
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AB_Recurring_Details].[User_ID]'
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AB_Recurring_Details].[AW_User_Companies_ID]'
	EXEC sp_bindefault N'[dbo].[df_Active]', N'[AB_Recurring_Details].[Slu_AW_Active_ID]'
    
    setuser

    
    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AW_Period_Procedures].[Date_Captured]'   
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AW_Period_Procedures].[User_ID]'
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AW_Period_Procedures].[AW_User_Companies_ID]'
	EXEC sp_bindefault N'[dbo].[df_Active]', N'[AW_Period_Procedures].[Slu_AW_Active_ID]'
    
    setuser

    
    ALTER TABLE [dbo].[AB_Cash_Book_Transaction_Details] ADD 
    	CONSTRAINT [FK_AB_Cash_Book_Transaction_Details_AB_Accounts] FOREIGN KEY 
    	(
    		[AB_Accounts_ID]
    	) REFERENCES [dbo].[AB_Accounts] (
    		[AB_Accounts_ID]
    	),
    	CONSTRAINT [FK_AB_Cash_Book_Transaction_Details_AB_Cash_Book_Transactions] FOREIGN KEY 
    	(
    		[AB_Cash_Book_Transactions_ID]
    	) REFERENCES [dbo].[AB_Cash_Book_Transactions] (
    		[AB_Cash_Book_Transactions_ID]
    	)

    
    ALTER TABLE [dbo].[AB_Cash_Book_Transactions] ADD 
    	CONSTRAINT [FK_AB_Cash_Book_Transactions_AW_Company_Banks] FOREIGN KEY 
    	(
    		[AW_Company_Banks_ID]
    	) REFERENCES [dbo].[AW_Company_Banks] (
    		[AW_Company_Banks_ID]
    	)

    
    ALTER TABLE [dbo].[AB_GL_Transactions] ADD 
    	CONSTRAINT [FK_AB_GL_Transactions_Lup_AB_Transaction_Types] FOREIGN KEY 
    	(
    		[Sys_AB_Transaction_Types_ID]
    	) REFERENCES [dbo].[Sys_AB_Transaction_Types] (
    		[Sys_AB_Transaction_Types_ID]
    	),
    	CONSTRAINT [FK_AB_Transactions_AB_Accounts] FOREIGN KEY 
    	(
    		[AB_Accounts_ID]
    	) REFERENCES [dbo].[AB_Accounts] (
    		[AB_Accounts_ID]
    	)

    
    ALTER TABLE [dbo].[AB_Journal_Details] ADD 
    	CONSTRAINT [FK_AB_Journal_Details_AB_Accounts] FOREIGN KEY 
    	(
    		[AB_Accounts_ID]
    	) REFERENCES [dbo].[AB_Accounts] (
    		[AB_Accounts_ID]
    	),
    	CONSTRAINT [FK_AB_Journal_Details_AB_Journals] FOREIGN KEY 
    	(
    		[AB_Journals_ID]
    	) REFERENCES [dbo].[AB_Journals] (
    		[AB_Journals_ID]
    	)

    
    ALTER TABLE [dbo].[AB_Recurring_Details] ADD 
    	CONSTRAINT [FK_AB_Recurring_Details_AB_Accounts] FOREIGN KEY 
    	(
    		[AB_Accounts_ID]
    	) REFERENCES [dbo].[AB_Accounts] (
    		[AB_Accounts_ID]
    	),
    	CONSTRAINT [FK_AB_Recurring_Details_AB_Recurring] FOREIGN KEY 
    	(
    		[AB_Recurring_ID]
    	) REFERENCES [dbo].[AB_Recurring] (
    		[AB_Recurring_ID]
    	)

    SET @ReturnValue = 1

END

RETURN @ReturnValue
GO

--17 sp_AW_9930
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AW_9930]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AW_9930]
GO
-------------------------------------------------------------------------------
--Description   :sp_AW_9930
--Purpose       :Wipe all TASKS Transaction tables
--              :
--Parameters    :
--Date          :2002/02/03
--Authors       :TB
--MODS          :
--2004.5.5      :10/11/11 - Refreshed with latest table defs - 2004.5.5
--2015.6.0      :2015-02-02 - Refreshed with latest table defs - 2015.6.0
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AW_9930]

AS

SET NOCOUNT ON

    DECLARE @ReturnValue bit

    SET @ReturnValue = 0

    BEGIN

        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AT_Tasks]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AT_Tasks]

        
        CREATE TABLE [dbo].[AT_Tasks] (
        	[AT_Tasks_ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[Start_Date] [datetime] NULL ,
        	[Date_Started] [datetime] NULL ,
        	[Date_Completed] [datetime] NULL ,
        	[Due_Date] [datetime] NULL ,
        	[Remind] [bit] NULL ,
        	[Actual_Work] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Task_Message] [varchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Actor1_ID] [int] NULL ,
        	[Actor2_ID] [int] NULL ,
        	[User2_ID] [int] NULL ,
        	[Subject_ObjectName] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Sys_AT_Subject_Type_ID] [tinyint] NULL ,
        	[Subject_ID] [int] NULL ,
        	[Sys_AT_Status_ID] [int] NULL ,
        	[Sys_AT_Notifications_ID] [tinyint] NULL ,
        	[Date_Captured] [datetime] NULL ,
        	[User_ID] [int] NULL ,
        	[AW_User_Companies_ID] [int] NOT NULL ,
        	[Touched] [timestamp] NULL ,
        	[Slu_AW_Active_ID] [tinyint] NULL 
        ) ON [PRIMARY]

        
        ALTER TABLE [dbo].[AT_Tasks] WITH NOCHECK ADD 
        	CONSTRAINT [PK_AW_Tasks] PRIMARY KEY  CLUSTERED 
        	(
        		[AT_Tasks_ID]
        	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

        
        setuser
        
        EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AT_Tasks].[Actual_Work]'
        
        EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AT_Tasks].[Remind]'
        
        EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AT_Tasks].[Subject_ID]'
        
        EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AT_Tasks].[Subject_ObjectName]'
        
        EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AT_Tasks].[Sys_AT_Notifications_ID]'
        
        EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AT_Tasks].[Sys_AT_Status_ID]'
        
        EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AT_Tasks].[Sys_AT_Subject_Type_ID]'
        
        EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AT_Tasks].[Task_Message]'

        EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AT_Tasks].[Date_Captured]'
        EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AT_Tasks].[User_ID]'
        EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AT_Tasks].[AW_User_Companies_ID]'
        EXEC sp_bindefault N'[dbo].[df_Active]', N'[AT_Tasks].[Slu_AW_Active_ID]'
        
        setuser
    
        SET @ReturnValue = 1
    
    END

RETURN @ReturnValue
GO

--18 sp_AW_9940
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AW_9940]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AW_9940]
GO
-------------------------------------------------------------------------------
--Description   : sp_AW_9940
--Purpose       : Wipe all PRODUCT Transaction tables
--Date          : 2002/02/11
--Authors       : TB
--MODS          :
--2004.5.5      :10/11/11 - Refreshed with latest table defs - 2004.5.5
--2015.6.0      :2015-02-02 - Refreshed with latest table defs - 2015.6.0
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AW_9940]

AS

SET NOCOUNT ON

DECLARE @ReturnValue bit
SET @ReturnValue = 0

BEGIN

    --First wipe the Test Data
    UPDATE AP_Products 
    SET Average_Cost = 0,
		On_Hand = 0,
		Sales_Order_Reserved = 0,
		Quote_Reserved = 0,
		Job_Reserved = 0,
		Last_Sale_Date = NULL,
		Service_Level = 1,
		Min_Stock_Level = 0,
		Min_Order_Qty = 0,
		Max_Order_Qty = 0,
		Levy_AP_Product_ID = 0

    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_AP_Promotion_Products_AP_Promotions]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
    ALTER TABLE [dbo].[AP_Promotion_Products] DROP CONSTRAINT FK_AP_Promotion_Products_AP_Promotions

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Bond_Stock_Log]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Bond_Stock_Log]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Enterprise_Slow_Moving_Stock]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Enterprise_Slow_Moving_Stock]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Enterprise_Stock]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Enterprise_Stock]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Enterprise_Stock_Filter]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Enterprise_Stock_Filter]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Enterprise_Stock_Replenish_Max]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Enterprise_Stock_Replenish_Max]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Enterprise_Stock_Valuation]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Enterprise_Stock_Valuation]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Inventory_Adjustments]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Inventory_Adjustments]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Inventory_Valuations]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Inventory_Valuations]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Product_Selling_Prices]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Product_Selling_Prices]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Products_History]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Products_History]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Products_Inventory]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Products_Inventory]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Products_Stock_Takes]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Products_Stock_Takes]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Promotion_Products]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Promotion_Products]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Promotions]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Promotions]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Stock_Exchange]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Stock_Exchange]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Stock_Take_Procedures]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Stock_Take_Procedures]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Stock_Transfer_Details]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Stock_Transfer_Details]

    
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Stock_Transfer_Log]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Stock_Transfer_Log]


    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Products_Audit]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[AP_Products_Audit]
    
    CREATE TABLE [dbo].[AP_Bond_Stock_Log] (
    	[AP_Bond_Stock_Log_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[File_Type] [varchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Status] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[File_Location] [varchar] (250) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Computer] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[FTP_Login_URL] [varchar] (250) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[FTP_User_Name] [varchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[FTP_Password] [varchar] (250) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[FTP_Folder] [varchar] (200) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[File_Date] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[File_Time] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Row_CNT] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Enterprise_Slow_Moving_Stock] (
    	[AP_Enterprise_Slow_Moving_Stock_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Product_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Pack_Size] [decimal](9, 3) NULL ,
    	[Total] [decimal](12, 3) NULL ,
    	[Filter] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Enterprise_Stock] (
    	[AP_Enterprise_Stock_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Product_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Pack_Size] [decimal](9, 3) NULL ,
    	[Total] [decimal](12, 3) NULL ,
    	[Filter] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Enterprise_Stock_Filter] (
    	[AP_Enterprise_Stock_Filter_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Product_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Pack_Size] [decimal](9, 3) NULL ,
    	[Total] [decimal](12, 3) NULL ,
    	[Filter] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Enterprise_Stock_Replenish_Max] (
    	[AP_Enterprise_Stock_Replenish_Max_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Product_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Pack_Size] [decimal](9, 3) NULL ,
    	[Total] [decimal](12, 3) NULL ,
    	[Filter] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Enterprise_Stock_Valuation] (
    	[AP_Enterprise_Stock_Valuation_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Product_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Pack_Size] [decimal](9, 3) NULL ,
    	[Total] [money] NULL ,
    	[Filter] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Inventory_Adjustments] (
    	[AP_Inventory_Adjustments_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AP_Products_ID] [int] NULL ,
    	[Sys_AP_Adjustment_Types_ID] [tinyint] NULL ,
    	[Previous_Last_Cost] [money] NOT NULL ,
    	[Previous_Average_Cost] [money] NULL ,
    	[Previous_On_Hand] [decimal](9, 3) NULL ,
    	[Previous_Job_Reserved] [decimal](9, 3) NULL ,
    	[Previous_Sales_Order_Reserved] [decimal](9, 3) NULL ,
    	[Previous_Quote_Reserved] [decimal](9, 3) NULL ,
    	[New_Last_Cost] [money] NULL ,
    	[New_Average_Cost] [money] NULL ,
    	[New_On_Hand] [decimal](9, 3) NULL ,
    	[New_Job_Reserved] [decimal](9, 3) NULL ,
    	[New_Sales_Order_Reserved] [decimal](9, 3) NULL ,
    	[New_Quote_Reserved] [decimal](9, 3) NULL ,
    	[Note] [varchar] (70) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Inventory_Valuations] (
    	[AP_Inventory_Valuations_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AW_Period_Procedures_ID] [int] NULL ,
    	[Lup_AP_Product_Departments_ID] [int] NULL ,
    	[Lup_AP_Product_Types_ID] [int] NULL ,
    	[Last_Cost] [money] NULL ,
    	[Average_Cost] [money] NULL ,
    	[Qty_On_Hand] [money] NULL ,
    	[Date_Captured] [smalldatetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [binary] (8) NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Product_Selling_Prices] (
    	[AP_Product_Selling_Prices_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AP_Products_ID] [int] NULL ,
    	[On_Hand] [decimal](9, 3) NULL ,
    	[Prev_Price1_Effective_Date] [datetime] NULL ,
    	[Prev_Price1_Price1] [money] NULL ,
    	[Prev_Price1_Price2] [money] NULL ,
    	[Prev_Price2_Effective_Date] [datetime] NULL ,
    	[Prev_Price2_Price1] [money] NULL ,
    	[Prev_Price2_Price2] [money] NULL ,
    	[New_Price1_Effective_Date] [datetime] NULL ,
    	[New_Price1_Price1] [money] NULL ,
    	[New_Price1_Price2] [money] NULL ,
    	[New_Price2_Effective_Date] [datetime] NULL ,
    	[New_Price2_Price1] [money] NULL ,
    	[New_Price2_Price2] [money] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Products_History] (
    	[AP_Products_History_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AP_Products_ID] [int] NULL ,
    	[AW_Period_Procedures_ID] [int] NULL ,
    	[Cost] [money] NULL ,
    	[Average_Cost] [money] NULL ,
    	[Standard_Cost] [money] NULL ,
    	[Qty] [decimal](9, 3) NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL 
    ) ON [PRIMARY]

 
    CREATE TABLE [dbo].[AP_Products_Inventory] (
    	[AP_Products_Inventory_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AP_Products_Static_ID] [int] NOT NULL ,
    	[Lup_AP_Product_Locations_ID] [int] NOT NULL ,
    	[On_Hand] [decimal](9, 3) NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[Date_Updated] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Products_Stock_Takes] (
    	[AP_Products_Stock_Takes_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AP_Stock_Take_Procedures_ID] [int] NULL ,
    	[AP_Products_ID] [int] NULL ,
    	[Count1] [decimal](9, 3) NULL ,
    	[Count2] [decimal](9, 3) NULL ,
    	[Count3] [decimal](9, 3) NULL ,
    	[Total_Count] [decimal](12, 3) NULL ,
    	[Unit_Cost] [money] NULL ,
    	[On_Hand] [decimal](9, 3) NULL ,
    	[Variance] [decimal](12, 3) NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Promotion_Products] (
    	[AP_Promotion_Products_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AP_Promotions_ID] [int] NULL ,
    	[AP_Products_ID] [int] NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Product_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Start_Date] [datetime] NULL ,
    	[End_Date] [datetime] NULL ,
    	[Slu_AW_Credit_Terms_ID] [tinyint] NULL ,
    	[Selling_Price] [money] NULL ,
    	[Qty_Projected_Sales] [decimal](9, 3) NULL ,
    	[Qty_Cutoff] [decimal](9, 3) NULL ,
    	[Qty_Sold] [decimal](9, 3) NULL ,
    	[Max_Per_Customer] [decimal](9, 3) NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NOT NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Promotions] (
    	[AP_Promotions_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Start_Date] [datetime] NULL ,
    	[End_Date] [datetime] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Stock_Exchange] (
    	[AP_Stock_Exchange_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AW_Remote_Access_ID] [int] NULL ,
    	[NodeName] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[AP_Products_ID] [int] NOT NULL ,
    	[Product_Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Product_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[On_Hand] [decimal](9, 3) NULL ,
    	[On_Order] [decimal](9, 3) NULL ,
    	[Last_Cost] [money] NULL ,
    	[Average_Cost] [money] NULL ,
    	[Count_Date] [datetime] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Stock_Take_Procedures] (
    	[AP_Stock_Take_Procedures_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[Description] [varchar] (500) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Procedure_Date] [datetime] NULL ,
    	[Slu_AW_Months_ID] [tinyint] NULL ,
    	[Slu_AW_Years_ID] [int] NULL ,
    	[Stock_Valuation] [money] NULL ,
    	[AB_Journals_ID] [int] NULL ,
    	[Stock_Adjustment_Total] [money] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Stock_Transfer_Details] (
    	[AP_Stock_Transfer_Details_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AC_Customers_ID] [int] NULL ,
    	[AP_Products_ID] [int] NULL ,
    	[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Product_Code] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Quantity] [decimal](9, 3) NULL ,
    	[Back_Order] [decimal](9, 3) NULL ,
    	[Original_Price] [money] NULL ,
    	[Unit_Price] [money] NULL ,
    	[Discount_Amount] [money] NULL ,
    	[Amount] [money] NULL ,
    	[Tax_Rate] [decimal](9, 3) NULL ,
    	[Tax_Amount] [money] NULL ,
    	[Extended_Amount] [money] NULL ,
    	[Unit_Cost] [money] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL ,
    	[Slu_AW_Active_ID] [tinyint] NULL 
    ) ON [PRIMARY]

    
    CREATE TABLE [dbo].[AP_Stock_Transfer_Log] (
    	[AP_Stock_Transfer_Log_ID] [int] IDENTITY (1, 1) NOT NULL ,
    	[AS_Transactions_ID] [int] NULL ,
    	[AC_Customers_ID] [int] NULL ,
    	[AP_Products_ID] [int] NULL ,
    	[AB_GL_Transactions_ID] [int] NULL ,
    	[AB_Transaction_Ref] [int] NULL ,
    	[AB_Source_Ref] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    	[Transaction_Date] [datetime] NULL ,
    	[Quantity] [decimal](12, 3) NULL ,
    	[Original_Price] [money] NULL ,
    	[Unit_Cost] [money] NULL ,
    	[Unit_Price] [money] NULL ,
    	[Discount_Amount] [money] NULL ,
    	[Amount] [money] NULL ,
    	[Tax_Amount] [money] NULL ,
    	[Extended_Amount] [money] NOT NULL ,
    	[AO_GRV_ID] [int] NULL ,
    	[Date_Received] [datetime] NULL ,
    	[SIT_User_ID] [int] NULL ,
    	[Date_Captured] [datetime] NULL ,
    	[TRF_User_ID] [int] NULL ,
    	[AW_User_Companies_ID] [int] NOT NULL ,
    	[Touched] [timestamp] NULL 
    ) ON [PRIMARY]

    
	CREATE TABLE [dbo].[AP_Products_Audit] (
		[AP_Products_Audit_ID] [int] IDENTITY(1,1) NOT NULL,
		[Record_Action] [varchar](50) NULL,
		[Action_Date] [datetime] NULL,
		[AP_Products_ID] [int] NOT NULL,
		[Field] [varchar](50) NULL,
		[Prev_Value] [varchar](50) NULL,
		[New_Value] [varchar](50) NULL,		
		[User_ID] [int] NULL
	) ON [PRIMARY]

    
    ALTER TABLE [dbo].[AP_Bond_Stock_Log] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AP_Bond_Stock_Log] PRIMARY KEY  CLUSTERED 
    	(
    		[AP_Bond_Stock_Log_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AP_Inventory_Adjustments] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AP_Inventory_Adjustments] PRIMARY KEY  CLUSTERED 
    	(
    		[AP_Inventory_Adjustments_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AP_Inventory_Valuations] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AP_Inventory_Valuations] PRIMARY KEY  CLUSTERED 
    	(
    		[AP_Inventory_Valuations_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AP_Products_History] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AP_Products_History] PRIMARY KEY  CLUSTERED 
    	(
    		[AP_Products_History_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AP_Products_Inventory] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AP_Products_Inventory] PRIMARY KEY  CLUSTERED 
    	(
    		[AP_Products_Inventory_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AP_Products_Stock_Takes] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AP_Products_Stock_Takes] PRIMARY KEY  CLUSTERED 
    	(
    		[AP_Products_Stock_Takes_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AP_Promotions] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AP_Promotions] PRIMARY KEY  CLUSTERED 
    	(
    		[AP_Promotions_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AP_Stock_Exchange] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AP_Stock_Exchange] PRIMARY KEY  CLUSTERED 
    	(
    		[AP_Stock_Exchange_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AP_Stock_Take_Procedures] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AP_Stock_Take_Procedures] PRIMARY KEY  CLUSTERED 
    	(
    		[AP_Stock_Take_Procedures_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AP_Stock_Transfer_Log] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AP_Stock_Transfer_Log] PRIMARY KEY  CLUSTERED 
    	(
    		[AP_Stock_Transfer_Log_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    ALTER TABLE [dbo].[AP_Products_Audit] WITH NOCHECK ADD 
    	CONSTRAINT [PK_AP_Products_Audit] PRIMARY KEY  CLUSTERED 
    	(
    		[AP_Products_Audit_ID]
    	) WITH  FILLFACTOR = 80  ON [PRIMARY] 
    
        
     CREATE  CLUSTERED  INDEX [IX_AP_Enterprise_Slow_Moving_Stock_Search] ON [dbo].[AP_Enterprise_Slow_Moving_Stock]([Filter], [Product_Code], [Pack_Size]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [IX_AP_Enterprise_Stock_Search] ON [dbo].[AP_Enterprise_Stock]([Filter], [Product_Code], [Pack_Size]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [IX_AP_Enterprise_Stock_Filter_Search] ON [dbo].[AP_Enterprise_Stock_Filter]([Filter], [Product_Code], [Pack_Size]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [IX_AP_Enterprise_Stock_Replenish_Max_Search] ON [dbo].[AP_Enterprise_Stock_Replenish_Max]([Filter], [Product_Code], [Pack_Size]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [IX_AP_Enterprise_Stock_Valuation_Search] ON [dbo].[AP_Enterprise_Stock_Valuation]([Filter], [Product_Code], [Pack_Size]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [CI_AP_Product_Selling_Prices] ON [dbo].[AP_Product_Selling_Prices]([AP_Products_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [IX_AP_Promotion_Products_AP_Products_ID] ON [dbo].[AP_Promotion_Products]([AP_Products_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  CLUSTERED  INDEX [CI_AP_Stock_Transfer_Details] ON [dbo].[AP_Stock_Transfer_Details]([AC_Customers_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
    ALTER TABLE [dbo].[AP_Enterprise_Slow_Moving_Stock] ADD 
    	CONSTRAINT [PK_AP_Enterprise_Slow_Moving_Stock] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AP_Enterprise_Slow_Moving_Stock_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AP_Enterprise_Stock] ADD 
    	CONSTRAINT [PK_AP_Enterprise_Stock] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AP_Enterprise_Stock_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AP_Enterprise_Stock_Filter] ADD 
    	CONSTRAINT [PK_AP_Enterprise_Stock_Filter] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AP_Enterprise_Stock_Filter_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AP_Enterprise_Stock_Replenish_Max] ADD 
    	CONSTRAINT [PK_AP_Enterprise_Stock_Replenish_Max] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AP_Enterprise_Stock_Replenish_Max_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
    ALTER TABLE [dbo].[AP_Enterprise_Stock_Valuation] ADD 
    	CONSTRAINT [PK_AP_Enterprise_Stock_Valuation] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AP_Enterprise_Stock_Valuation_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
     CREATE  INDEX [IX_AP_Inventory_Adjustments_AP_Products_ID] ON [dbo].[AP_Inventory_Adjustments]([AP_Products_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
    ALTER TABLE [dbo].[AP_Product_Selling_Prices] ADD 
    	CONSTRAINT [PK_AP_Product_Selling_Prices] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AP_Product_Selling_Prices_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
     CREATE  INDEX [IX_AP_Products_History_AP_Products_ID] ON [dbo].[AP_Products_History]([AP_Products_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Products_Inventory_AP_Products_Static_ID] ON [dbo].[AP_Products_Inventory]([AP_Products_Static_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Products_Inventory_Date_Updated] ON [dbo].[AP_Products_Inventory]([Date_Updated]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Products_Stock_Takes_AP_Products_ID] ON [dbo].[AP_Products_Stock_Takes]([AP_Products_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
    ALTER TABLE [dbo].[AP_Promotion_Products] ADD 
    	CONSTRAINT [PK_AP_Promotion_Products] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AP_Promotion_Products_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
     CREATE  INDEX [IX_AP_Promotion_Products_AP_Promotions] ON [dbo].[AP_Promotion_Products]([AP_Promotions_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  INDEX [IDX_Product_Code_NodeName] ON [dbo].[AP_Stock_Exchange]([Product_Code], [NodeName]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
     CREATE  INDEX [IX_AP_Stock_Exchange_AP_Products_ID] ON [dbo].[AP_Stock_Exchange]([AP_Products_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

    
    ALTER TABLE [dbo].[AP_Stock_Transfer_Details] ADD 
    	CONSTRAINT [PK_AP_Stock_Transfer_Details] PRIMARY KEY  NONCLUSTERED 
    	(
    		[AP_Stock_Transfer_Details_ID]
    	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

    
	CREATE  INDEX [IX_AP_Stock_Transfer_Details_AP_Products_ID] ON [dbo].[AP_Stock_Transfer_Details]([AP_Products_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]
    
	CREATE  INDEX [IDX_AP_Stock_Transfer_Log_AS_Transactions_ID] ON [dbo].[AP_Stock_Transfer_Log]([AS_Transactions_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

	CREATE  INDEX [IX_AP_Products_Audit_AP_Products_ID] ON [dbo].[AP_Products_Audit]([AP_Products_ID]) WITH  FILLFACTOR = 80 ON [PRIMARY]
    
    
    setuser     
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AP_Bond_Stock_Log].[Computer]'        
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AP_Bond_Stock_Log].[File_Date]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AP_Bond_Stock_Log].[File_Location]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AP_Bond_Stock_Log].[File_Time]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AP_Bond_Stock_Log].[File_Type]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AP_Bond_Stock_Log].[FTP_Folder]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AP_Bond_Stock_Log].[FTP_Login_URL]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AP_Bond_Stock_Log].[FTP_Password]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AP_Bond_Stock_Log].[FTP_User_Name]'
    
    EXEC sp_bindefault N'[dbo].[df_Nullstring]', N'[AP_Bond_Stock_Log].[Row_CNT]'
    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Bond_Stock_Log].[Date_Captured]'
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Bond_Stock_Log].[User_ID]'
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Bond_Stock_Log].[AW_User_Companies_ID]'
    
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Enterprise_Slow_Moving_Stock].[Pack_Size]'
    
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Enterprise_Stock].[Pack_Size]'
    
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Enterprise_Stock_Filter].[Pack_Size]'
    
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Enterprise_Stock_Valuation].[Pack_Size]'
    
    setuser

    
    setuser        
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Adjustments].[New_Average_Cost]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Adjustments].[New_Job_Reserved]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Adjustments].[New_Last_Cost]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Adjustments].[New_On_Hand]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Adjustments].[New_Quote_Reserved]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Adjustments].[New_Sales_Order_Reserved]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Adjustments].[Previous_Average_Cost]'

    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Adjustments].[Previous_Job_Reserved]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Adjustments].[Previous_Last_Cost]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Adjustments].[Previous_On_Hand]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Adjustments].[Previous_Quote_Reserved]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Adjustments].[Previous_Sales_Order_Reserved]'        
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Inventory_Adjustments].[Sys_AP_Adjustment_Types_ID]'

    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Inventory_Adjustments].[Date_Captured]'
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Inventory_Adjustments].[User_ID]'
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Inventory_Adjustments].[AW_User_Companies_ID]'
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AP_Inventory_Adjustments].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Valuations].[Average_Cost]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Valuations].[Last_Cost]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Inventory_Valuations].[Qty_On_Hand]'
    
	EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Inventory_Valuations].[Date_Captured]'
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Inventory_Valuations].[User_ID]'
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Inventory_Valuations].[AW_User_Companies_ID]'
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AP_Inventory_Valuations].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
        
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Product_Selling_Prices].[New_Price1_Effective_Date]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Product_Selling_Prices].[New_Price1_Price1]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Product_Selling_Prices].[New_Price1_Price2]'
    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Product_Selling_Prices].[New_Price2_Effective_Date]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Product_Selling_Prices].[New_Price2_Price1]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Product_Selling_Prices].[New_Price2_Price2]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Product_Selling_Prices].[On_Hand]'
    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Product_Selling_Prices].[Prev_Price1_Effective_Date]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Product_Selling_Prices].[Prev_Price1_Price1]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Product_Selling_Prices].[Prev_Price1_Price2]'
    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Product_Selling_Prices].[Prev_Price2_Effective_Date]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Product_Selling_Prices].[Prev_Price2_Price1]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Product_Selling_Prices].[Prev_Price2_Price2]'                
    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Product_Selling_Prices].[Date_Captured]'    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Product_Selling_Prices].[User_ID]'
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Product_Selling_Prices].[AW_User_Companies_ID]'
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AP_Product_Selling_Prices].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_History].[Average_Cost]'        
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_History].[Cost]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_History].[Qty]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_History].[Standard_Cost]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Products_History].[User_ID]'
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Products_History].[AW_User_Companies_ID]'
    
    setuser

    
    setuser            
        
    EXEC sp_bindefault N'[dbo].[df_Date_Updated]', N'[AP_Products_Inventory].[Date_Updated]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products_Inventory].[Lup_AP_Product_Locations_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Inventory].[On_Hand]'    
    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Products_Inventory].[Date_Captured]'
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Products_Inventory].[User_ID]'
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Products_Inventory].[AW_User_Companies_ID]'
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AP_Products_Inventory].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
            
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Stock_Takes].[Count1]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Stock_Takes].[Count2]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Stock_Takes].[Count3]'      
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Stock_Takes].[On_Hand]'        
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Stock_Takes].[Total_Count]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Stock_Takes].[Unit_Cost]'        
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Stock_Takes].[Variance]'
    
	EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Products_Stock_Takes].[Date_Captured]'
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Products_Stock_Takes].[User_ID]'
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Products_Stock_Takes].[AW_User_Companies_ID]'
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AP_Products_Stock_Takes].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
                    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Promotion_Products].[Max_Per_Customer]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Promotion_Products].[Qty_Cutoff]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Promotion_Products].[Qty_Projected_Sales]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Promotion_Products].[Qty_Sold]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Promotion_Products].[Selling_Price]'
            
    EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Promotion_Products].[Slu_AW_Credit_Terms_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Promotion_Products].[Date_Captured]'
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Promotion_Products].[User_ID]'
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Promotion_Products].[AW_User_Companies_ID]'
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AP_Promotion_Products].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser        
    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Promotions].[Date_Captured]'            
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Promotions].[User_ID]'
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Promotions].[AW_User_Companies_ID]'
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AP_Promotions].[Slu_AW_Active_ID]'
    
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Exchange].[Average_Cost]'                
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Exchange].[Last_Cost]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Exchange].[On_Hand]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Exchange].[On_Order]'

    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Stock_Exchange].[Date_Captured]'
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Stock_Exchange].[User_ID]'
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Stock_Exchange].[AW_User_Companies_ID]'
    
    setuser

    
    setuser        
                    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Take_Procedures].[Stock_Valuation]'

    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Stock_Take_Procedures].[Date_Captured]'
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Stock_Take_Procedures].[User_ID]'
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Stock_Take_Procedures].[AW_User_Companies_ID]'
    EXEC sp_bindefault N'[dbo].[df_Active]', N'[AP_Stock_Take_Procedures].[Slu_AW_Active_ID]'
   
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Transfer_Details].[Amount]'    
        
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Transfer_Details].[Back_Order]'
            
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Transfer_Details].[Discount_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Transfer_Details].[Extended_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Transfer_Details].[Original_Price]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Transfer_Details].[Quantity]'        
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Transfer_Details].[Tax_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Transfer_Details].[Tax_Rate]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Transfer_Details].[Unit_Cost]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Transfer_Details].[Unit_Price]'        
	    
	EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Stock_Transfer_Details].[Date_Captured]'
	EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Stock_Transfer_Details].[User_ID]'
	EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Stock_Transfer_Details].[AW_User_Companies_ID]'
	EXEC sp_bindefault N'[dbo].[df_Active]', N'[AP_Stock_Transfer_Details].[Slu_AW_Active_ID]'    
	
    setuser

    
    setuser
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Transfer_Log].[Amount]'               
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Transfer_Log].[Discount_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Transfer_Log].[Extended_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Transfer_Log].[Original_Price]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Transfer_Log].[Quantity]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Transfer_Log].[Tax_Amount]'
    
    EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Stock_Transfer_Log].[Transaction_Date]'
    
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Stock_Transfer_Log].[TRF_User_ID]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Transfer_Log].[Unit_Cost]'
    
    EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Stock_Transfer_Log].[Unit_Price]'
    
    EXEC sp_bindefault N'[dbo].[df_Date_Updated]', N'[AP_Stock_Transfer_Log].[Date_Captured]'
    EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Stock_Transfer_Log].[AW_User_Companies_ID]'
    
    setuser

    
	setuser
       
    EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Products_Audit].[User_ID]'
    
    setuser
        
    ALTER TABLE [dbo].[AP_Promotion_Products] ADD 
    	CONSTRAINT [FK_AP_Promotion_Products_AP_Promotions] FOREIGN KEY 
    	(
    		[AP_Promotions_ID]
    	) REFERENCES [dbo].[AP_Promotions] (
    		[AP_Promotions_ID]
    	)
  
    SET @ReturnValue = 1
    
END

RETURN @ReturnValue

SET NOCOUNT OFF
GO

--19 sp_AW_9970
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AW_9970]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AW_9970]
GO
-------------------------------------------------------------------------------
--Description   : sp_AW_9970
--Purpose       : Wipe all FACTORY Transaction tables
--Date          : 2011/05/15 (2004.5.1)
--Authors       : TB
--MODS          :
--2004.5.5      :10/11/11 - Refreshed with latest table defs - 2004.5.5
--2015.6.0      :2015-02-02 - Refreshed with latest table defs - 2015.6.0
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AW_9970]

AS

SET NOCOUNT ON

DECLARE @ReturnValue bit

SET @ReturnValue = 0

    BEGIN
    
        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AF_Job_Tickets]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AF_Job_Tickets]    

        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AF_Job_Tickets_Deleted]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AF_Job_Tickets_Deleted]

        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AF_Waybills]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AF_Waybills]

        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AF_Waybills_Deleted]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AF_Waybills_Deleted]

        
        CREATE TABLE [dbo].[AF_Job_Tickets] (
        	[AF_Job_Tickets_ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[Post] [bit] NULL ,
        	[Job_No] [int] NULL ,
        	[Job_Date] [datetime] NULL ,
        	[AC_Customers_ID] [int] NULL ,
        	[Order_No] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[AP_Products_ID] [int] NULL ,
        	[Lup_AP_Product_Manufacturers_ID] [int] NULL ,
        	[Serial_No] [varchar] (13) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Lup_AF_Instructions_ID] [smallint] NULL ,
        	[Job_User_ID] [int] NULL ,
        	[AF_Waybills_ID] [int] NULL ,
        	[AO_Suppliers_ID] [int] NULL ,
        	[Waybill_Date] [datetime] NULL ,
        	[Waybill_User_ID] [int] NULL ,
        	[AO_GRV_ID] [int] NULL ,
        	[GRV_Date] [datetime] NULL ,
        	[Invoice_No] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Retread_Cost] [money] NULL ,
        	[Repair_Cost] [money] NULL ,
        	[Other_Cost] [money] NULL ,
        	[AP_Repair_Products_ID] [int] NULL ,
        	[AP_Other_Products_ID] [int] NULL ,
        	[Lup_AP_Fail_Reasons_ID] [smallint] NULL ,
        	[GRV_User_ID] [int] NULL ,
        	[AS_Transactions_ID] [int] NULL ,
        	[Billing_Date] [datetime] NULL ,
        	[Billing_No] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Retread_Price] [money] NULL ,
        	[Repair_Price] [money] NULL ,
        	[Other_Price] [money] NULL ,
        	[Amount] [money] NULL ,
        	[Tax] [money] NULL ,
        	[Total] [money] NULL ,
        	[Comment] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
        	[Billing_User_ID] [int] NULL ,
        	[AP_Inventory_Adjustments_ID] [int] NULL ,
        	[Adjustment_Date] [datetime] NULL ,
        	[AP_Stock_Products_ID] [int] NULL ,
        	[Casing_Credit] [money] NULL ,
        	[Stock_Cost] [money] NULL ,
        	[Adjustment_User_ID] [int] NULL ,
        	[Date_Captured] [datetime] NULL ,
        	[AW_User_Companies_ID] [int] NOT NULL ,
        	[Touched] [timestamp] NULL ,
        	[Slu_AW_Active_ID] [tinyint] NULL 
        ) ON [PRIMARY]
    
        
        CREATE TABLE [dbo].[AF_Waybills] (
        	[AF_Waybills_ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[AO_Suppliers_ID] [int] NULL ,
        	[Waybill_Date] [datetime] NULL ,
        	[Date_Captured] [datetime] NULL ,
        	[User_ID] [int] NULL ,
        	[AW_User_Companies_ID] [int] NULL ,
        	[Touched] [timestamp] NULL ,
        	[Slu_AW_Active_ID] [tinyint] NULL 
        ) ON [PRIMARY]
    
   
	CREATE TABLE [dbo].[AF_Job_Tickets_Deleted](
		[AF_Job_Tickets_ID] [int] NULL,
		[Post] [bit] NULL,
		[Job_No] [int] NULL,
		[Job_Date] [datetime] NULL,
		[AC_Customers_ID] [int] NULL,
		[Order_No] [varchar](20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
		[AP_Products_ID] [int] NULL,
		[Lup_AP_Product_Manufacturers_ID] [int] NULL,
		[Serial_No] [varchar](13) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
		[Lup_AF_Instructions_ID] [smallint] NULL,
		[Job_User_ID] [int] NULL,
		[AF_Waybills_ID] [int] NULL,
		[AO_Suppliers_ID] [int] NULL,
		[Waybill_Date] [datetime] NULL,
		[Waybill_User_ID] [int] NULL,
		[AO_GRV_ID] [int] NULL,
		[GRV_Date] [datetime] NULL,
		[Invoice_No] [varchar](20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
		[Retread_Cost] [money] NULL,
		[Repair_Cost] [money] NULL,
		[Other_Cost] [money] NULL,
		[AP_Repair_Products_ID] [int] NULL,
		[AP_Other_Products_ID] [int] NULL,
		[Lup_AP_Fail_Reasons_ID] [smallint] NULL,
		[GRV_User_ID] [int] NULL,
		[AS_Transactions_ID] [int] NULL,
		[Billing_Date] [datetime] NULL,
		[Billing_No] [varchar](20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
		[Retread_Price] [money] NULL,
		[Repair_Price] [money] NULL,
		[Other_Price] [money] NULL,
		[Amount] [money] NULL,
		[Tax] [money] NULL,
		[Total] [money] NULL,
		[Comment] [varchar](20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
		[Billing_User_ID] [int] NULL,
		[AP_Inventory_Adjustments_ID] [int] NULL,
		[Adjustment_Date] [datetime] NULL,
		[AP_Stock_Products_ID] [int] NULL,
		[Casing_Credit] [money] NULL,
		[Stock_Cost] [money] NULL,
		[Adjustment_User_ID] [int] NULL,
		[Date_Captured] [datetime] NULL,
		[AW_User_Companies_ID] [int] NOT NULL,
		[Slu_AW_Active_ID] [tinyint] NULL,
		[Action_Date] [datetime] NULL,
		[Action_User_ID] [int] NULL
	) ON [PRIMARY]

	CREATE TABLE [dbo].[AF_Waybills_Deleted](
		[AF_Waybills_ID] [int] NULL,
		[AO_Suppliers_ID] [int] NULL,
		[Waybill_Date] [datetime] NULL,
		[Date_Captured] [datetime] NULL,
		[User_ID] [int] NULL,
		[AW_User_Companies_ID] [int] NULL,
		[Slu_AW_Active_ID] [tinyint] NULL,
		[Action_Date] [datetime] NULL,
		[Action_User_ID] [int] NULL
	) ON [PRIMARY]


        ALTER TABLE [dbo].[AF_Job_Tickets] WITH NOCHECK ADD 
        	CONSTRAINT [PK_AF_Job_Tickets] PRIMARY KEY  CLUSTERED 
        	(
        		[AF_Job_Tickets_ID]
        	) WITH  FILLFACTOR = 90  ON [PRIMARY] 
    
        
        ALTER TABLE [dbo].[AF_Waybills] WITH NOCHECK ADD 
        	CONSTRAINT [PK_AF_Waybills] PRIMARY KEY  CLUSTERED 
        	(
        		[AF_Waybills_ID]
        	) WITH  FILLFACTOR = 90  ON [PRIMARY] 
    
        
         CREATE  INDEX [IX_AF_Job_Tickets_Factory_ID] ON [dbo].[AF_Job_Tickets]([AO_Suppliers_ID]) ON [PRIMARY]
    
        
         CREATE  INDEX [IX_AF_Job_Tickets_Job_No] ON [dbo].[AF_Job_Tickets]([Job_No]) ON [PRIMARY]
    
        
         CREATE  INDEX [IX_AF_Job_Tickets_Customer_ID] ON [dbo].[AF_Job_Tickets]([AC_Customers_ID]) ON [PRIMARY]
    
        
         CREATE  INDEX [IX_AF_Job_Tickets_Waybill_No] ON [dbo].[AF_Job_Tickets]([AF_Waybills_ID]) ON [PRIMARY]
    
        
         CREATE  INDEX [IX_AF_Job_Tickets_Invoice_No] ON [dbo].[AF_Job_Tickets]([Invoice_No]) ON [PRIMARY]
    
        
         CREATE  INDEX [IX_AF_Job_Tickets_Billing_No] ON [dbo].[AF_Job_Tickets]([Billing_No]) ON [PRIMARY]
    
        
         CREATE  INDEX [IX_AF_Job_Tickets_GRV_ID] ON [dbo].[AF_Job_Tickets]([AO_GRV_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]
    
        
         CREATE  INDEX [IX_AF_Job_Tickets_Product_ID] ON [dbo].[AF_Job_Tickets]([AP_Products_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]
    
        
         CREATE  INDEX [IX_AF_Job_Tickets_AS_Transactions_ID] ON [dbo].[AF_Job_Tickets]([AS_Transactions_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]
    
        
         CREATE  INDEX [IX_AF_Waybills_AO_Suppliers_ID] ON [dbo].[AF_Waybills]([AO_Suppliers_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]
    
        
        setuser
        
        EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AF_Job_Tickets].[Lup_AP_Fail_Reasons_ID]'    
        
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AF_Job_Tickets].[Post]'
    
		EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AF_Job_Tickets].[Date_Captured]'
        EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AF_Job_Tickets].[AW_User_Companies_ID]'
        EXEC sp_bindefault N'[dbo].[df_Active]', N'[AF_Job_Tickets].[Slu_AW_Active_ID]'
            
        setuser
    
        
        setuser    
        
        EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AF_Waybills].[Date_Captured]'
        EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AF_Waybills].[User_ID]'
        EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AF_Waybills].[AW_User_Companies_ID]'
		EXEC sp_bindefault N'[dbo].[df_Active]', N'[AF_Waybills].[Slu_AW_Active_ID]'
        
        setuser
    
        
        SET @ReturnValue = 1
        
    END

RETURN @ReturnValue

SET NOCOUNT OFF
GO

--20 sp_AW_9950
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AW_9950]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AW_9950]
GO
-------------------------------------------------------------------------------
--Description   : sp_AW_9950
--Purpose       : Clear all System Transaction Number tables
--              :
--Parameters    :
--Date          : 2002/02/11
--Authors       : TB
--2004.5.5      :10/11/11 - Refreshed with latest table defs - 2004.5.5
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AW_9950]

AS

SET NOCOUNT ON

DECLARE @ReturnValue bit

SET @ReturnValue = 0

BEGIN

    UPDATE Sys_AB_Transaction_Numbers
    SET Last_Number = 0

    UPDATE Sys_AW_Transaction_Numbers
    SET Last_Number = 0

    SET @ReturnValue = 1
    
END

RETURN @ReturnValue

SET NOCOUNT OFF
GO

--21 sp_AW_9980
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AW_9980]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AW_9980]
GO
-------------------------------------------------------------------------------
--Description   :sp_AW_9980
--Purpose       :RE-LINK PRODUCTS & SUPPLIERS (AP_Products_Suppliers)
--              :
--Parameters    :
--Date          :2002/08/02
--Authors       :TB
--MODS          :
--2004.5.5      :10/11/11 - Refreshed with latest table defs - 2004.5.5
-------------------------------------------------------------------------------

CREATE  PROCEDURE [dbo].[sp_AW_9980]

AS

SET NOCOUNT ON

    DECLARE @ReturnValue bit
    SET @ReturnValue = 0

    BEGIN

        if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[AP_Products_Suppliers]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        drop table [dbo].[AP_Products_Suppliers]

        
        CREATE TABLE [dbo].[AP_Products_Suppliers] (
        	[AP_Products_Suppliers_ID] [int] IDENTITY (1, 1) NOT NULL ,
        	[AP_Products_ID] [int] NULL ,
        	[AO_Suppliers_ID] [int] NULL ,
        	[Lead_Time] [smallint] NULL ,
        	[Trade_Disc_Perc] [decimal](5, 2) NULL ,
        	[Trade_Disc_Date] [datetime] NULL ,
        	[Start_Date] [datetime] NULL ,
        	[AW_Trade_Discount_Formula_ID] [smallint] NULL ,
        	[AW_Rebate_Discount_Formula_ID] [smallint] NULL ,
        	[Date_Captured] [datetime] NULL ,
        	[User_ID] [int] NULL ,
        	[AW_User_Companies_ID] [int] NULL ,
        	[Touched] [timestamp] NULL ,
        	[Slu_AW_Active_ID] [int] NULL 
        ) ON [PRIMARY]

        
         CREATE  CLUSTERED  INDEX [IX_AP_Products_Suppliers_AP_Products_ID] ON [dbo].[AP_Products_Suppliers]([AP_Products_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

        
        ALTER TABLE [dbo].[AP_Products_Suppliers] ADD 
        	CONSTRAINT [PK_AP_Products_Suppliers] PRIMARY KEY  NONCLUSTERED 
        	(
        		[AP_Products_Suppliers_ID]
        	) WITH  FILLFACTOR = 90  ON [PRIMARY] 

        
         CREATE  INDEX [IX_AP_Products_Suppliers_AO_Suppliers_ID] ON [dbo].[AP_Products_Suppliers]([AO_Suppliers_ID]) WITH  FILLFACTOR = 90 ON [PRIMARY]

        
        setuser
        
        EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products_Suppliers].[AW_Rebate_Discount_Formula_ID]'
        
        EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products_Suppliers].[AW_Trade_Discount_Formula_ID]'
                                   
        EXEC sp_bindefault N'[dbo].[df_Numeric_One]', N'[AP_Products_Suppliers].[Lead_Time]'
                       
        EXEC sp_bindefault N'[dbo].[df_Numeric_Zero]', N'[AP_Products_Suppliers].[Trade_Disc_Perc]'
        
        EXEC sp_bindefault N'[dbo].[df_Date_Captured]', N'[AP_Products_Suppliers].[Date_Captured]'
		EXEC sp_bindefault N'[dbo].[df_User_ID]', N'[AP_Products_Suppliers].[User_ID]'
        EXEC sp_bindefault N'[dbo].[df_User_Companies]', N'[AP_Products_Suppliers].[AW_User_Companies_ID]'
        EXEC sp_bindefault N'[dbo].[df_Active]', N'[AP_Products_Suppliers].[Slu_AW_Active_ID]'        
        
        setuser
    
    
        ------------------------------------------------------------------------------------
        --INSERT AP_Products_Suppliers
        ------------------------------------------------------------------------------------
        INSERT AP_Products_Suppliers
            (
        	AP_Products_ID,
        	AO_Suppliers_ID,
        --	Lead_Time,    --IS NOW A DEFAULT OF 1
        	Start_Date
            )
        SELECT
            ap_products_id,
            Default_Supplier_ID,
        --  1,
            getdate()
        FROM ap_products
        WHERE Default_Supplier_ID IS NOT NULL


        SET @ReturnValue = 1
        
    END

RETURN @ReturnValue

SET NOCOUNT OFF
GO

--22 sp_AS_Transactions_Address_Update
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_Transactions_Address_Update]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_Transactions_Address_Update]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_Transactions_Address_Update
--Purpose       :Updates address details used on Invoices
--Functionality :Links Address details to an invoice
--Date          :2013-07-09
--Authors       :RL
------------------------------------------------------------------------------- 
CREATE Procedure [dbo].[sp_AS_Transactions_Address_Update]
    (    	    	
    	@AS_Transactions_Address_Detail_ID int,
    	@Inv_Customer_Name varchar(100),
		@Inv_Address1 varchar(40),
		@Inv_Address2 varchar(40),
		@Inv_City varchar(30),
		@Inv_Code varchar(10),
		@Inv_Tax_Number	varchar(16),
		@Delivery_Address varchar(40),
		@Delivery_Suburb varchar(40),
		@Delivery_City varchar(30),
		@Delivery_Post_Code varchar(10),
		@User_ID	int
    )
AS 

	SET NOCOUNT ON
    
	DECLARE 
    	@AW_YesNo_Delivery_Address int,
    	@AW_YesNo_Invoice int

	SET @AW_YesNo_Delivery_Address = 0
	SET @AW_YesNo_Invoice = 0
		
	SET @Inv_Customer_Name = LTRIM(RTRIM(ISNULL(@Inv_Customer_Name,'')))
	SET @Inv_Address1 = LTRIM(RTRIM(ISNULL(@Inv_Address1,'')))
	SET @Inv_Address2 = LTRIM(RTRIM(ISNULL(@Inv_Address2,'')))
	SET @Inv_Code = LTRIM(RTRIM(ISNULL(@Inv_Code,'')))
	SET @Inv_City = LTRIM(RTRIM(ISNULL(@Inv_City,'')))
	SET @Inv_Tax_Number = LTRIM(RTRIM(ISNULL(@Inv_Tax_Number,'')))
	SET @Delivery_Address = LTRIM(RTRIM(ISNULL(@Delivery_Address,'')))
	SET @Delivery_Suburb = LTRIM(RTRIM(ISNULL(@Delivery_Suburb,'')))
	SET @Delivery_City = LTRIM(RTRIM(ISNULL(@Delivery_City,'')))
	SET @Delivery_Post_Code = LTRIM(RTRIM(ISNULL(@Delivery_Post_Code,'')))

	IF (
		@Inv_Customer_Name <> '' Or
		@Inv_Address1 <> '' Or
		@Inv_Address2 <> '' Or
		@Inv_Code <> '' Or
		@Inv_City <> '' Or
		@Inv_Tax_Number <> ''
		)
	BEGIN
		SET @AW_YesNo_Invoice = 1
	END

	IF (
		@Delivery_Address <> '' Or
		@Delivery_Suburb <> '' Or
		@Delivery_City <> '' Or
		@Delivery_Post_Code <> ''
		)
	BEGIN
		SET @AW_YesNo_Delivery_Address = 1
	END	
	
	IF (@AW_YesNo_Invoice = 0 AND @AW_YesNo_Delivery_Address = 0)
	BEGIN
		DELETE FROM AS_Transactions_Address_Detail WHERE AS_Transactions_Address_Detail_ID = @AS_Transactions_Address_Detail_ID
		DELETE FROM AS_Transactions_Address WHERE AS_Transactions_Address_Detail_ID = @AS_Transactions_Address_Detail_ID
	END
	ELSE
	BEGIN	 
		UPDATE AS_Transactions_Address_Detail
		SET
			Customer_Name = @Inv_Customer_Name,
			Inv_Address1 = @Inv_Address1,
			Inv_Address2 = @Inv_Address2,
			Inv_Code = @Inv_Code,
			Inv_City = @Inv_City,
			Tax_Number = @Inv_Tax_Number,
			Delivery_Address = @Delivery_Address,
			Delivery_Suburb = @Delivery_Suburb,
			Delivery_City = @Delivery_City,
			Delivery_Post_Code = @Delivery_Post_Code
		WHERE AS_Transactions_Address_Detail_ID = @AS_Transactions_Address_Detail_ID	  
	END
SET NOCOUNT ON
GO

--23 Sys_AW_Options_txtCSalesExclusions
--Insert txtCSalesExclusions - Used for Inclusion List
--txtCSalesExclusions
IF NOT EXISTS
(
	SELECT Sys_AW_Options_ID
	FROM Sys_AW_Options
	WHERE Control_Name = 'txtCSalesExclusions'
	AND Control_Index = 1
) 
BEGIN
	INSERT Sys_AW_Options
	(
		Control_Type,
		Control_Name,
		Control_Index,
		Control_Value,
		Date_Captured,
		User_ID,
		AW_User_Companies_ID
	)
	VALUES
	(
		'TextBox',
		'txtCSalesExclusions',
		1,
		'',
		Getdate(),
		1,
		1
	)
END
GO

--24 sp_AC_Insert_CBilling_Temp
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AC_Insert_CBilling_Temp]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AC_Insert_CBilling_Temp]
GO
------------------------------------------------------------------------------
--Description   :sp_AC_Insert_CBilling_Temp
--Functionality :INSERT daily UNSUBMITTED Centralised Sales transactions
--Parameters    :
--Date          :2005/09/29
--Authors       :TB
--MODS          :03/10/05 - Removed superfluous @ProviderID from WHERE filter
--              :           to enable setting DEFAULT provider in UI
--2004.2.8      :03/05/06 - Added input parameters to EXCLUDE Sales Cost Prices
--              :           and Truck and Tractor SALES data from submission
--2004.3.2      :22/09/06 - Added TRUNCATE all table varchar(50) fields to LEFT(48)
--              :01/11/06 - Added EXCLUDE Lubrication SALES data from submission
--2004.3.4      :21/02/07 - Replaced @chkTruckSales tinyint input parameter with
--              :           @ExclusionsFilter varchar(250) and append to query
--              :24/03/07 - Removed all customer details from submission file
--              :           EXCEPT if FLEET company
--2004.3.5      :16/05/07 - Added FILTER in WHERE clause to EXCLUDE INTER-BRANCH SALES
--              :           to other Customer Group FRANCHISEES in the Bridgestone Retail
--              :           stable by inserting 'bsretail' in the Head_Office field
--              :           of the BRANCH in the Customer Catalog
--2004.3.7      :15/08/07 - Added leading and trailing quotes to Product/Manuf code
--2004.4.7      :18/09/09 - Added Merchant No in 'special_instr'  and replaced 'branch_name'
--              :           with Trading Name as per Denise van Gent new specs
--R.L	2015-03-12	:Added Inclusion List
-------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[sp_AC_Insert_CBilling_Temp]
    (
        @chkSalesCost tinyint,
        @chkExcludeInterBranch tinyint,
        @ExclusionsFilter varchar(8000),
        @InclusionFilter varchar(8000),
        @StartDayEndDate datetime,
        @EndDayEndDate datetime,
        @CompanyID int
    )
AS

SET NOCOUNT ON

    DECLARE @sql				varchar(8000),
            @RetCode			tinyint,
            @No_Days			int,
            @Temp_No_Days		Varchar(20)

    SET @RetCode = 0
    SET @No_Days = 14

    SELECT TOP 1 @Temp_No_Days = ISNULL(Control_Value, 14)
    FROM Sys_AW_Options
    WHERE Control_Type = 'TextBox' AND
          Control_Name = 'txtCBillingDays'
          
	SET @Temp_No_Days = Replace(@Temp_No_Days,',','')	
	IF @Temp_No_Days = ''
		SET @Temp_No_Days = '14'
	
	IF ISNUMERIC(@Temp_No_Days) = 1
		SET @No_Days = @Temp_No_Days
	
	IF ISNUMERIC(@Temp_No_Days) = 0
		SET @No_Days = 14
          
    Set @StartDayEndDate = DateAdd(d,(@No_Days*-1),@StartDayEndDate)
    
    --Select @StartDayEndDate

    SET @sql = ' INSERT AS_Transactions_CBilling_Temp '
    SET @sql = @sql + ' ( '
    SET @sql = @sql + 'AS_Transactions_ID, '
    SET @sql = @sql + 'Lup_AS_CBilling_Providers_ID, '
    SET @sql = @sql + 'cat_code, '
    SET @sql = @sql + 'drs_acc, '
    SET @sql = @sql + 'trs_ref, '
    SET @sql = @sql + 'trs_date, '
    SET @sql = @sql + 'qty, '
    SET @sql = @sql + 'amount, '
    SET @sql = @sql + 'gls_acc, '
    SET @sql = @sql + 'narr, '
    SET @sql = @sql + 'stock_group, '
    SET @sql = @sql + 'drs_apply, '
    SET @sql = @sql + 'sys_code, '
    SET @sql = @sql + 'updated, '
    SET @sql = @sql + 'interfaced, '
    SET @sql = @sql + 'drs_age_month, '
    SET @sql = @sql + 'stock_code, '
    SET @sql = @sql + 'area, '
    SET @sql = @sql + 'drs_alpha, '
    SET @sql = @sql + 'branch, '
    SET @sql = @sql + 'vat_amount, '
    SET @sql = @sql + 'cost_amount, '
    SET @sql = @sql + 'rep_comm, '
    SET @sql = @sql + 'process_type, '
    SET @sql = @sql + 'rep_code, '
    SET @sql = @sql + 'acct_type, '
    SET @sql = @sql + 'disc_amnt, '
    SET @sql = @sql + 'std_sell_price, '
    SET @sql = @sql + 'drs_trs_code, '
    SET @sql = @sql + 'trs_type, '
    SET @sql = @sql + 'acc_month, '
    SET @sql = @sql + 'acc_year, '
    SET @sql = @sql + 'con_acct_no, '
    SET @sql = @sql + 'zz_int01, '
    SET @sql = @sql + 'cntno, '
    SET @sql = @sql + 'line_disc1, '
    SET @sql = @sql + 'line_disc2, '
    SET @sql = @sql + 'stock_sell1, '
    SET @sql = @sql + 'no_of_deals, '
    SET @sql = @sql + 'zz_date01, '
    SET @sql = @sql + 'zz_date02, '
    SET @sql = @sql + 'zz_date03, '
    SET @sql = @sql + 'special_instr, '
    SET @sql = @sql + 'deals_flag, '
    SET @sql = @sql + 'deals_number, '
    SET @sql = @sql + 'vat_exempt_member, '
    SET @sql = @sql + 'cmonth, '
    SET @sql = @sql + 'cyear, '
    SET @sql = @sql + 'rep_call_status, '
    SET @sql = @sql + 'drsdiv_code, '
    SET @sql = @sql + 'crs_acc, '
    SET @sql = @sql + 'creation_date, '
    SET @sql = @sql + 'creation_time, '
    SET @sql = @sql + 'creation_userid, '
    SET @sql = @sql + 'creation_proc, '
    SET @sql = @sql + 'item_number, '
    SET @sql = @sql + 'rep_code2, '
    SET @sql = @sql + 'qty2, '
    SET @sql = @sql + 'deposit_amount, '
    SET @sql = @sql + 'job_number, '
    SET @sql = @sql + 'line_disc_amnt, '
    SET @sql = @sql + 'carhire_cntno, '
    SET @sql = @sql + 'currency, '
    SET @sql = @sql + 'exch_rate, '
    SET @sql = @sql + 'cyear_month, '
    SET @sql = @sql + 'zz_date04, '
    SET @sql = @sql + 'zz_date05, '
    SET @sql = @sql + 'zz_int02, '
    SET @sql = @sql + 'zz_int03, '
    SET @sql = @sql + 'zz_int04, '
    SET @sql = @sql + 'zz_int05, '
    SET @sql = @sql + 'zz_dec01, '
    SET @sql = @sql + 'zz_dec02, '
    SET @sql = @sql + 'zz_dec03, '
    SET @sql = @sql + 'zz_dec04, '
    SET @sql = @sql + 'zz_dec05, '
    SET @sql = @sql + 'zz_log01, '
    SET @sql = @sql + 'zz_log02, '
    SET @sql = @sql + 'zz_log03, '
    SET @sql = @sql + 'zz_log04, '
    SET @sql = @sql + 'zz_log05, '
    SET @sql = @sql + 'zz_log06, '
    SET @sql = @sql + 'zz_log07, '
    SET @sql = @sql + 'zz_char01, '
    SET @sql = @sql + 'zz_char02, '
    SET @sql = @sql + 'zz_char03, '
    SET @sql = @sql + 'zz_char04, '
    SET @sql = @sql + 'zz_char05, '
    SET @sql = @sql + 'key_glstrs, '
    SET @sql = @sql + 'key_history, '
    SET @sql = @sql + 'dumped, '
    SET @sql = @sql + 'company_name, '
    SET @sql = @sql + 'branch_name, '
    SET @sql = @sql + 'drs_name, '
    SET @sql = @sql + 'crs_name, '
    SET @sql = @sql + 'prd_grp_descr, '
    SET @sql = @sql + 'stk_descry, '
    SET @sql = @sql + 'status_ind, '
    SET @sql = @sql + 'customer_ref, '
    SET @sql = @sql + 'comments1, '
    SET @sql = @sql + 'comments2, '
    SET @sql = @sql + 'comments3, '
    SET @sql = @sql + 'comments4, '
    SET @sql = @sql + 'comments5, '
    SET @sql = @sql + 'comments6, '
    SET @sql = @sql + 'comments7, '
    SET @sql = @sql + 'comments8, '
    SET @sql = @sql + 'database_id, '
    SET @sql = @sql + 'system_id, '
    SET @sql = @sql + 'vat_reg_no, '
    SET @sql = @sql + 'email, '
    SET @sql = @sql + 'customer_cell_number, '
    SET @sql = @sql + 'customer_email_address, '
    SET @sql = @sql + 'Date_Captured, '
    SET @sql = @sql + 'User_ID, '
    SET @sql = @sql + 'AW_User_Companies_ID, '
    SET @sql = @sql + 'Slu_AW_Active_ID '
    SET @sql = @sql + ' ) '

    SET @sql = @sql + ' SELECT '
    SET @sql = @sql + ' t.AS_Transactions_ID, '
    SET @sql = @sql + ' cb.Lup_AS_CBilling_Providers_ID, '
    SET @sql = @sql + ' CASE WHEN t.Sys_AW_Transaction_Types_ID = 3 '
    SET @sql = @sql + ' THEN ''"'' + ''IN'' + ''"'' '
    SET @sql = @sql + ' WHEN t.Sys_AW_Transaction_Types_ID = 4 '
    SET @sql = @sql + ' THEN ''"'' + ''CR'' + ''"'' '
    SET @sql = @sql + ' ELSE ''"'' + ''IN'' + ''"'' '
    SET @sql = @sql + ' END, '                                                        --cat_code
    SET @sql = @sql + ' ''"'' + ''SPIRAL'' + ''"'', '
    SET @sql = @sql + ' ''"'' + ISNULL(t.Transaction_Number, '''') + ''"'', '         --trs_ref
    SET @sql = @sql + ' t.Transaction_Date, '                                         --trs_date
    SET @sql = @sql + ' d.Quantity, '                                                 --qty
    SET @sql = @sql + ' ISNULL(d.Extended_Amount, 0) - ISNULL(d.Tax_Amount, 0), '     --amount,
    SET @sql = @sql + ' ''"'' + ''N/A'' + ''"'', '
    SET @sql = @sql + ' ''"'' + LEFT(ISNULL(p.Description, ''''), 48) + ''"'', '      --narr,
    SET @sql = @sql + ' ''"'' + LEFT(ISNULL(pt.Description, ''''), 48) + ''"'', '     --stock_group
    SET @sql = @sql + ' ''"'' + ISNULL(t.Transaction_Number, '''') + ''"'', '         --drs_apply
    SET @sql = @sql + ' ''"'' + ''SPI'' + ''"'', '
    SET @sql = @sql + ' ''no'', '
    SET @sql = @sql + ' ''no'', '
    SET @sql = @sql + ' 1, '                                                          --drs_age_month

--     SET @sql = @sql + ' CASE WHEN p.Manufacturer_Code IS NULL OR RTRIM(LTRIM(p.Manufacturer_Code)) = ''"'' + ''''   '
--     SET @sql = @sql + ' THEN p.Product_Code '
--     SET @sql = @sql + ' ELSE p.Manufacturer_Code '
--     SET @sql = @sql + ' END, '                                                        --stock_code
    SET @sql = @sql + ' CASE WHEN ISNULL(p.Manufacturer_Code, '''') = '''' '
    SET @sql = @sql + ' THEN ''"'' + ISNULL(p.Product_Code, '''') + ''"'' '
    SET @sql = @sql + ' ELSE ''"'' + ISNULL(p.Manufacturer_Code, '''') + ''"'' '
    SET @sql = @sql + ' END, '                                                        --stock_code

    SET @sql = @sql + ' ''"'' + ''N/A'' + ''"'', '
    SET @sql = @sql + ' ''"'' + ISNULL(c.Customer_Number, '''') + ''"'', '            --drs_alpha
    SET @sql = @sql + ' ''"'' + ISNULL(uc.Network_Identity_Number, '''') + ''"'', '   --branch
    SET @sql = @sql + ' d.Tax_Amount, '                                               --vat_amount
    
    --> Product Cost Price data = 0
    IF @chkSalesCost = 0
    BEGIN
        SET @sql = @sql + ' 0, '
    END
    ELSE
    BEGIN    
        SET @sql = @sql + ' ROUND(ISNULL(d.Unit_Cost, 0) * ISNULL(d.Quantity, 0), 2), '    --cost_amount,
    END
    
    SET @sql = @sql + ' 0, '                                                         --rep_comm
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --process_type
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --rep_code
    SET @sql = @sql + ' ''"'' + ''N/A'' + ''"'','
    SET @sql = @sql + ' d.Discount_Amount, '                                         --disc_amnt
    SET @sql = @sql + ' d.Original_Price, '                                          --std_sell_price
    SET @sql = @sql + ' ''"'' + ''100'' + ''"'', '                                   --drs_trs_code
    SET @sql = @sql + ' 1, '                                                         --trs_type
    SET @sql = @sql + ' CONVERT(smallint, DATEPART(month, t.Transaction_Date)), '    --acc_month,
    SET @sql = @sql + ' CONVERT(smallint, DATEPART(year, t.Transaction_Date)), '     --acc_year
    
    --     SET @sql = @sql + ' ''"'' + ISNULL(c.Customer_Number, '''') + ''"'', '           --on_acct_no
    SET @sql = @sql + ' CASE WHEN c.Sys_AC_Account_Types_ID = 4 '
    SET @sql = @sql + ' THEN ''"'' + ISNULL(c.Customer_Number, '''') + ''"'' '
    SET @sql = @sql + ' ELSE ''"'' + ''"'' '
    SET @sql = @sql + ' END, ' 
    
    SET @sql = @sql + ' 1, '                                                         --zz_int01
    SET @sql = @sql + ' 1, '                                                         --cntno
    SET @sql = @sql + ' CASE WHEN (d.Unit_Price * d.Quantity) <> 0 '
    
    --     SET @sql = @sql + ' THEN CONVERT(money, ABS(ROUND( (((d.Discount_Amount) / (d.Unit_Price * d.Quantity)) * 100), 2)) ) '
    SET @sql = @sql + ' THEN ABS(ROUND(CONVERT(money, ((d.Discount_Amount / (d.Unit_Price * d.Quantity)) * 100)), 2)) '
    
    SET @sql = @sql + ' ELSE 0.00 '
    SET @sql = @sql + ' END, '                                                       --line_disc1
    SET @sql = @sql + ' 0, '                                                         --line_disc2
    SET @sql = @sql + ' 0, '                                                         --stock_sell1
    SET @sql = @sql + ' 0, '                                                         --no_of_deals
    SET @sql = @sql + ' ''1970/01/01'', '                                            --zz_date01
    SET @sql = @sql + ' ''1970/01/01'', '                                            --zz_date02
    SET @sql = @sql + ' ''1970/01/01'', '                                            --zz_date03


--    SET @sql = @sql + ' ''"'' + ''"'', '                                             --special_instr
    SET @sql = @sql + ' ''"'' + LEFT(ISNULL(c.Old_Customer_Number, ''''), 10) + ''"'', '        --special_instr


    SET @sql = @sql + ' ''"'' + ''"'', '                                             --deals_flag
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --deals_number
    SET @sql = @sql + ' ''no'', '
    SET @sql = @sql + ' CONVERT(smallint, DATEPART(month, t.Transaction_Date)), '    --cmonth,
    SET @sql = @sql + ' CONVERT(smallint, DATEPART(year, t.Transaction_Date)), '     --cyear
    SET @sql = @sql + ' ''no'', '
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --drsdiv_code,
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --crs_acc,
    SET @sql = @sql + ' ''1970/01/01'', '                                            --creation_date,
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --creation_time,
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --creation_userid,
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --creation_proc,
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --item_number,
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --rep_code2,
    SET @sql = @sql + '  0 , '                                                       --qty2,
    SET @sql = @sql + '  0 , '                                                       --deposit_amount,
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --job_number,
    SET @sql = @sql + '  0 , '                                                       --line_disc_amnt,
    SET @sql = @sql + '  0 , '                                                       --carhire_cntno,
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --currency,
    SET @sql = @sql + '  0 , '                                                       --exch_rate,
    SET @sql = @sql + '  0 , '                                                       --cyear_month,
    SET @sql = @sql + ' ''1970/01/01'', '                                            --zz_date04,
    SET @sql = @sql + ' ''1970/01/01'', '                                            --zz_date05,
    SET @sql = @sql + '  0 , '                                                       --zz_int02,
    SET @sql = @sql + '  0 , '                                                       --zz_int03,
    SET @sql = @sql + '  0 , '                                                       --zz_int04,
    SET @sql = @sql + '  0 , '                                                       --zz_int05,
    SET @sql = @sql + '  0 , '                                                       --zz_dec01,
    SET @sql = @sql + '  0 , '                                                       --zz_dec02,
    SET @sql = @sql + '  0 , '                                                       --zz_dec03,
    SET @sql = @sql + '  0 , '                                                       --zz_dec04,
    SET @sql = @sql + '  0 , '                                                       --zz_dec05,
    SET @sql = @sql + ' ''no'', '
    SET @sql = @sql + ' ''no'', '
    SET @sql = @sql + ' ''no'', '
    SET @sql = @sql + ' ''no'', '
    SET @sql = @sql + ' ''no'', '
    SET @sql = @sql + ' ''no'', '
    SET @sql = @sql + ' ''no'', '
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --zz_char01,
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --zz_char02,
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --zz_char03,
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --zz_char04,
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --zz_char05,
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --key_glstrs,
    SET @sql = @sql + ' ''"'' + ''"'', '                                             --key_history,
    SET @sql = @sql + ' ''no'', '
    SET @sql = @sql + ' ''"'' + LEFT(ISNULL(uc.Company_Name, ''''), 48) + ''"'', '             --company_name


--    SET @sql = @sql + ' ''"'' + LEFT(ISNULL(uc.Company_Name, ''''), 48) + ''"'', '             --branch_name
    SET @sql = @sql + ' ''"'' + LEFT(ISNULL(uc.Company_Trading_Name, ''''), 48) + ''"'', '             --branch_name

   
    --     SET @sql = @sql + ' ''"'' + LEFT(ISNULL(c.Surname, ''''), 48) + ''"'', '                   --drs_name,
    SET @sql = @sql + ' CASE WHEN c.Sys_AC_Account_Types_ID = 4 '
    SET @sql = @sql + ' THEN ''"'' + LEFT(ISNULL(c.Surname, ''''), 48) + ''"'' '
    SET @sql = @sql + ' ELSE ''"'' + ''"'' '
    SET @sql = @sql + ' END, ' 
    
    SET @sql = @sql + ' ''"'' + ''"'', '                                                       --crs_name,
    SET @sql = @sql + ' ''"'' + LEFT(ISNULL(pt.Description, ''''), 48) + ''"'', '              --prd_grp_descr,
    SET @sql = @sql + ' ''"'' + LEFT(ISNULL(p.Description, ''''), 48) + ''"'', '               --stk_descry,
    SET @sql = @sql + ' ''"'' + ''NE'' + ''"'', '
    SET @sql = @sql + ' ''"'' + LEFT(ISNULL(cb.Registration_No, ''''), 48) + ''"'', '          --customer_ref,
    
    --     SET @sql = @sql + ' ''"'' + LEFT(ISNULL(c.Surname, ''''), 48) + ''"'', '                   --comments1,
    SET @sql = @sql + ' CASE WHEN c.Sys_AC_Account_Types_ID = 4 '
    SET @sql = @sql + ' THEN ''"'' + LEFT(ISNULL(c.Surname, ''''), 48) + ''"'' '
    SET @sql = @sql + ' ELSE ''"'' + ''"'' '
    SET @sql = @sql + ' END, ' 
    
    --     SET @sql = @sql + ' ''"'' + LEFT(ISNULL(c.Delivery_Address, ''''), 48) + ''"'', '          --comments2,
    SET @sql = @sql + ' CASE WHEN c.Sys_AC_Account_Types_ID = 4 '
    SET @sql = @sql + ' THEN ''"'' + LEFT(ISNULL(c.Delivery_Address, ''''), 48) + ''"'' '
    SET @sql = @sql + ' ELSE ''"'' + ''"'' '
    SET @sql = @sql + ' END, ' 
    
    --     SET @sql = @sql + ' ''"'' + LEFT(ISNULL(c.Delivery_Suburb, ''''), 48) + ''"'', '           --comments3,
    SET @sql = @sql + ' CASE WHEN c.Sys_AC_Account_Types_ID = 4 '
    SET @sql = @sql + ' THEN ''"'' + LEFT(ISNULL(c.Delivery_Suburb, ''''), 48) + ''"'' '
    SET @sql = @sql + ' ELSE ''"'' + ''"'' '
    SET @sql = @sql + ' END, ' 
    
    --     SET @sql = @sql + ' ''"'' + LEFT(ISNULL(c.Delivery_City, ''''), 48) + ''"'', '             --comments4,
    SET @sql = @sql + ' CASE WHEN c.Sys_AC_Account_Types_ID = 4 '
    SET @sql = @sql + ' THEN ''"'' + LEFT(ISNULL(c.Delivery_City, ''''), 48) + ''"'' '
    SET @sql = @sql + ' ELSE ''"'' + ''"'' '
    SET @sql = @sql + ' END, ' 
    
    SET @sql = @sql + ' ''"'' + LEFT(ISNULL(cb.Authorization_No, ''''), 48) + ''"'', '         --comments5,
    SET @sql = @sql + ' ''"'' + LEFT(ISNULL(cb.Odometer_Reading, ''''), 48) + ''"'', '         --comments6,
    SET @sql = @sql + ' ''"'' + LEFT(ISNULL(cb.Engine_No, ''''), 48) + ''"'', '                --comments7,
    SET @sql = @sql + ' ''"'' + LEFT(ISNULL(cb.Model_Year, '''') + ISNULL('' '' + cb.Make, '''') + ISNULL('' '' + cb.Model, ''''), 48) + ''"'', '          --comments8,
    SET @sql = @sql + ' ''"'' + ''SPIRAL'' + ''"'', '
    SET @sql = @sql + ' ''"'' + LEFT(ISNULL(uc.Network_Identity_Number, ''''), 48) + ''"'', '  --system_id,
    SET @sql = @sql + ' ''"'' + LEFT(ISNULL(c.Tax_Number, ''''), 48) + ''"'', '                --vat_reg_no,
    
    --     SET @sql = @sql + ' ''"'' + LEFT(ISNULL(uc.E_Mail, ''''), 48) + ''"'', '                   --email,
    SET @sql = @sql + ' CASE WHEN c.Sys_AC_Account_Types_ID = 4 '
    SET @sql = @sql + ' THEN ''"'' + LEFT(ISNULL(uc.E_Mail, ''''), 48) + ''"'' '
    SET @sql = @sql + ' ELSE ''"'' + ''"'' '
    SET @sql = @sql + ' END, ' 
    
    SET @sql = @sql + ' ''"'' + LEFT(ISNULL(c.Cell_No, ''''), 48) + ''"'', '                   --customer_cell_number,
    
    --     SET @sql = @sql + ' ''"'' + LEFT(ISNULL(c.Home_Email, ''''), 48) + ''"'', '                --customer_email_address,
    SET @sql = @sql + ' CASE WHEN c.Sys_AC_Account_Types_ID = 4 '
    SET @sql = @sql + ' THEN ''"'' + LEFT(ISNULL(c.Home_Email, ''''), 48) + ''"'' '
    SET @sql = @sql + ' ELSE ''"'' + ''"'' '
    SET @sql = @sql + ' END, ' 
    
    SET @sql = @sql + ' t.Date_Captured, '
    SET @sql = @sql + ' t.User_ID, '
    SET @sql = @sql + ' t.AW_User_Companies_ID, '
    SET @sql = @sql + ' t.Slu_AW_Active_ID '
    
    SET @sql = @sql + ' FROM AS_Transactions t '
    SET @sql = @sql + '    INNER JOIN AS_Transaction_Details d '
    SET @sql = @sql + ' ON t.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '    LEFT JOIN AS_Transactions_CBilling cb '
    SET @sql = @sql + ' ON t.AS_Transactions_ID = cb.AS_Transactions_ID '
    SET @sql = @sql + '    INNER JOIN AP_Products p '
    SET @sql = @sql + ' ON d.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + '    INNER JOIN Lup_AP_Product_Types pt '
    SET @sql = @sql + ' ON p.Lup_AP_Product_Types_ID = pt.Lup_AP_Product_Types_ID '
    SET @sql = @sql + '    INNER JOIN AC_Customers c '
    SET @sql = @sql + ' ON t.AC_Customers_ID = c.AC_Customers_ID '
    SET @sql = @sql + '    INNER JOIN AW_User_Companies uc '
    SET @sql = @sql + ' ON t.AW_User_Companies_ID = uc.AW_User_Companies_ID '
    SET @sql = @sql + '    INNER JOIN Lup_AP_Product_Departments pd '
    SET @sql = @sql + ' ON p.Lup_AP_Product_Departments_ID = pd.Lup_AP_Product_Departments_ID '
    SET @sql = @sql + '    INNER JOIN Lup_AP_Product_Groups pg '
    SET @sql = @sql + ' ON p.Lup_AP_Product_Groups_ID = pg.Lup_AP_Product_Groups_ID '
    SET @sql = @sql + '    INNER JOIN Lup_AP_Product_Manufacturers pm '
    SET @sql = @sql + ' ON p.Lup_AP_Product_Manufacturers_ID = pm.Lup_AP_Product_Manufacturers_ID '
    
    SET @sql = @sql + ' WHERE t.AW_User_Companies_ID = ' + CONVERT(varchar(30), @CompanyID) + ' AND '

    IF @chkExcludeInterBranch = 1
        BEGIN
            SET @sql = @sql + '       ISNULL(LOWER(RTRIM(LTRIM(c.Head_Office))), '''') <> ''bsretail'' AND '
        END

    SET @sql = @sql + '      (t.Sys_AW_Transaction_Types_ID = 3 OR '
    SET @sql = @sql + '       t.Sys_AW_Transaction_Types_ID = 4) AND '
    SET @sql = @sql + '       t.Day_End >= ''' + CONVERT(varchar(30), @StartDayEndDate) + ''' AND '
    SET @sql = @sql + '       t.Day_End <= ''' + CONVERT(varchar(30), @EndDayEndDate ) + ''' '

-- Exclusions List
    SET @sql = @sql + CONVERT(varchar(8000), @ExclusionsFilter)  
    
-- Inclusions List
    SET @sql = @sql + CONVERT(varchar(8000), @InclusionFilter)  

    SET @sql = @sql + 'ORDER BY t.AS_Transactions_ID '

IF LEN(@sql) >= 8000
    BEGIN
        SET @RetCode = 1

        RETURN @RetCode
    END

EXEC (@sql)
--Select @sql
SET @RetCode = 2

RETURN @RetCode
GO

--25 sp_RPT_AS_DayEnd_Export_Sales
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_RPT_AS_DayEnd_Export_Sales]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_RPT_AS_DayEnd_Export_Sales]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_RPT_AS_DayEnd_Export_Sales
--Purpose       :Sales from Starting DayEnd date to Ending DayEnd date
--Functionality :by EXPORT CUSTOMER by Filter
--Date          :2011/03/08
--Authors       :TB
--MODS:         :
--RL	V6.1	2015-02-19	:Removed Customer Account Type Check. Does not make sense???
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_RPT_AS_DayEnd_Export_Sales]
    (
        @Filter varchar(30),
        @DayEndFromDate datetime,
        @DayEndToDate datetime,
        @CompanyID int
    )
AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000),
            @Tax_Rate decimal(5,2),
            @TaxRate varchar(30)

-- SET @Filter = 'Department'
-- SET @CompanyID = 1
-- SET @DayEndFromDate = '2002-10-01 17:27:00'
-- SET @DayEndToDate = '2002-10-31 19:44:00'


------------------------------------------------------------------------------
    --> Get the STANDARD VAT rate
------------------------------------------------------------------------------
    SELECT @Tax_Rate = Tax_Rate
    FROM Sys_AW_Tax_Codes
    WHERE Tax_Code = 'S'

    IF @Tax_Rate = 0 OR @Tax_Rate IS NULL
        SET @Tax_Rate = 14

--    SET @Tax_Rate = @Tax_Rate / 100

    SET @TaxRate = CONVERT(varchar(30), @Tax_Rate)
------------------------------------------------------------------------------


    SET @sql = ' SELECT '

    SET @sql = @sql + ' c.AC_Customers_ID AS [CustomerID], '
    SET @sql = @sql + ' ISNULL(c.Surname, '''') + '' '' + '
    SET @sql = @sql + ' ISNULL(c.Firstnames, '''') '
    SET @sql = @sql + ' + '' ('' + CONVERT(varchar(10), c.AC_Customers_ID) + '')'' AS [Customer], '


    IF @Filter = 'Type'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Types_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Filter = 'Groups'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Groups_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Filter = 'Department'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Departments_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Filter = 'Supplier'
        SET @sql = @sql +
            ' o.AO_Suppliers_ID AS [HeaderID], ' +
            ' ISNULL(o.[Supplier_Name], '''') AS [Filter], '
    ELSE
    IF @Filter = 'Manufacturer'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Manufacturers_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Filter = 'Location'
        SET @sql = @sql +
            ' o.Lup_AP_Product_Locations_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Filter = 'Sales Area'
        SET @sql = @sql +
            ' o.Lup_AC_Sales_Areas_ID AS [HeaderID], ' +
            ' ISNULL(o.[Description], '''') AS [Filter], '
    ELSE
    IF @Filter = 'Cashier'
        SET @sql = @sql +
            ' o.AW_Users_ID AS [HeaderID], ' +
            ' ISNULL(o.[UserName], '''') AS [Filter], '


    SET @sql = @sql + ' h.Transaction_Date AS [TranDate], '
    SET @sql = @sql + ' tt.[Description] AS [TranType], '
    SET @sql = @sql + ' h.Transaction_Number AS [TranNo], '
    SET @sql = @sql + ' h.Customer_Reference AS [CustRef], '
    SET @sql = @sql + ' h.Comment AS [ShortComment], '
    SET @sql = @sql + ' p.[Description] AS [Product], '
    SET @sql = @sql + ' tc.[Description] AS [TaxCode], '
    SET @sql = @sql + ' tc.Tax_Rate AS [TaxRate], '

    SET @sql = @sql + ' CONVERT(money, d.Quantity) AS [Qty], '
--    SET @sql = @sql + ' CONVERT(money, d.Unit_Price * d.Quantity) AS [Selling], '
    SET @sql = @sql + ' ISNULL(CONVERT(money, d.Unit_Price), 0) AS [Selling], '
    SET @sql = @sql + ' CONVERT(money, d.Discount_Amount) AS [Discount], '
    SET @sql = @sql + ' CONVERT(money, d.Extended_Amount - d.Tax_Amount) AS [NetSales], '
    SET @sql = @sql + ' CONVERT(money, d.Tax_Amount) AS [Tax], '
    SET @sql = @sql + ' CONVERT(money, d.Extended_Amount) AS [Total], '

    SET @sql = @sql + ' CONVERT(money, d.Unit_Cost * d.Quantity) AS [Cost], '
    SET @sql = @sql + ' CONVERT(money, (d.Extended_Amount - d.Tax_Amount) - (d.Quantity * d.Unit_Cost)) AS [GP], '
    SET @sql = @sql + ' CASE WHEN dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money,((dbo.fn_AS_Calc_Act_GP(d.Extended_Amount, d.Tax_Amount, d.Quantity, d.Unit_Cost)) / dbo.fn_AS_Calc_Act_Sales_Value(d.Extended_Amount, d.Tax_Amount) * 100)) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Act GP%], '
    SET @sql = @sql + ' CASE WHEN dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity) <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money,((dbo.fn_AS_Calc_Std_GP(d.Original_Price, d.Unit_Cost, d.Quantity)) / dbo.fn_AS_Calc_Std_Sales_Value(d.Original_Price, d.Quantity) * 100)) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Std GP%], '

    SET @sql = @sql + ' CONVERT(money, (d.Unit_Price - d.Original_Price) * d.Quantity) AS [Price Adj], '
    SET @sql = @sql + ' CONVERT(money, d.Discount_Amount - d.Original_Discount) AS [Disc Adj], '

    SET @sql = @sql + ' CASE WHEN d.Quantity <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money, (d.Unit_Cost * d.Quantity) / d.Quantity) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Ave Cost], '

    SET @sql = @sql + ' CASE WHEN d.Quantity <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money, (d.Unit_Price * d.Quantity) / d.Quantity) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Ave Sell], '
    
    SET @sql = @sql + ' CASE WHEN d.Quantity <> 0 '
    SET @sql = @sql + '      THEN CONVERT(money, (d.Discount_Amount) / d.Quantity) '
    SET @sql = @sql + '      ELSE 0.00 '
    SET @sql = @sql + '      END AS [Ave Disc], '

    SET @sql = @sql + ' u.UserName AS [User] '
    
    SET @sql = @sql + ' FROM AS_Transaction_Details d '
    SET @sql = @sql + '      INNER JOIN AS_Transactions h '
    SET @sql = @sql + '          ON h.AS_Transactions_ID = d.AS_Transactions_ID '
    SET @sql = @sql + '      INNER JOIN AP_Products p '
    SET @sql = @sql + '          ON d.AP_Products_ID = p.AP_Products_ID '
    SET @sql = @sql + '      INNER JOIN AC_Customers c '
    SET @sql = @sql + '          ON c.AC_Customers_ID = h.AC_Customers_ID '
    SET @sql = @sql + '      LEFT JOIN Sys_AW_Transaction_Types tt '
    SET @sql = @sql + '          ON h.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID '
    SET @sql = @sql + '      LEFT JOIN AW_Users u '
    SET @sql = @sql + '          ON h.User_ID = u.AW_Users_ID '
    SET @sql = @sql + '      LEFT JOIN Sys_AW_Tax_Codes tc '
    SET @sql = @sql + '          ON c.Sys_AW_Tax_Codes_ID = tc.Sys_AW_Tax_Codes_ID '

    IF @Filter = 'Type'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Types o ' +
            '        ON p.Lup_AP_Product_Types_ID = o.Lup_AP_Product_Types_ID '
    ELSE
    IF @Filter = 'Groups'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Groups o ' +
            '        ON p.Lup_AP_Product_Groups_ID = o.Lup_AP_Product_Groups_ID '
    ELSE
    IF @Filter = 'Department'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Departments o ' +
            '        ON p.Lup_AP_Product_Departments_ID = o.Lup_AP_Product_Departments_ID '
    ELSE
    IF @Filter = 'Supplier'
        SET @sql = @sql +
            '    LEFT JOIN AO_Suppliers o ' +
            '        ON p.Default_Supplier_ID = o.AO_Suppliers_ID '
    ELSE
    IF @Filter = 'Manufacturer'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Manufacturers o ' +
            '        ON p.Lup_AP_Product_Manufacturers_ID = o.Lup_AP_Product_Manufacturers_ID '
    ELSE
    IF @Filter = 'Location'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AP_Product_Locations o ' +
            '        ON p.Lup_AP_Product_Locations_ID = o.Lup_AP_Product_Locations_ID '
    ELSE
    IF @Filter = 'Sales Area'
        SET @sql = @sql +
            '    LEFT JOIN Lup_AC_Sales_Areas o ' +
            '        ON c.Lup_AC_Sales_Areas_ID = o.Lup_AC_Sales_Areas_ID '
    ELSE
    IF @Filter = 'Cashier'
        SET @sql = @sql +
            '    LEFT JOIN AW_Users o ' +
            '        ON h.Lup_AS_Cashiers_ID = o.AW_Users_ID '

    SET @sql = @sql +
        ' WHERE d.AW_User_Companies_ID = ' + CONVERT(varchar(10), @CompanyID) + ' AND ' +
        '      (h.Day_End >= ''' + CONVERT(varchar(30), @DayEndFromDate) + ''' AND ' +
        '       h.Day_End <= ''' + CONVERT(varchar(30), @DayEndToDate) + ''') AND ' +
        '      (h.Sys_AW_Transaction_Types_ID = 3 OR ' +
        '       h.Sys_AW_Transaction_Types_ID = 4)  ' 
      --  '       c.Sys_AC_Account_Types_ID = 7 ' Export WTF????

    SET @sql = @sql + ' ORDER BY [Customer], [Filter], [TranDate] '

--PRINT @sql

EXEC (@sql)
GO

--26 sp_AS_CSales_Submission_INS_SEL
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_CSales_Submission_INS_SEL]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_CSales_Submission_INS_SEL]
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_CSales_Submission_INS_SEL
--Purpose       :Select Sales Submission Data For Insurance
--Parameters    :
--Date          :2014-09-23
--Authors       :RL
--Version       :6.1
--MODS          :
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_CSales_Submission_INS_SEL]
(
	@ExclusionsFilter	varchar(8000),
	@InclusionFilter	varchar(8000),
	@StartDayEndDate	datetime,
	@EndDayEndDate		datetime,
	@CompanyID			int
)
AS

SET NOCOUNT ON

Declare	@No_Days			Int,
		@Temp_No_Days		Varchar(20),
		@sql				Varchar(8000)

    SELECT 
		TOP 1 @Temp_No_Days = ISNULL(Control_Value, 14)
    FROM 
		Sys_AW_Options
    WHERE 
		Control_Type = 'TextBox' AND
        Control_Name = 'txtCBillingDays'

	SET @Temp_No_Days = Replace(@Temp_No_Days,',','')	
	IF @Temp_No_Days = ''
		SET @Temp_No_Days = '14'
	
	IF ISNUMERIC(@Temp_No_Days) = 1
		SET @No_Days = @Temp_No_Days
	
	IF ISNUMERIC(@Temp_No_Days) = 0
		SET @No_Days = 14

	Set @StartDayEndDate = DateAdd(d,(@No_Days*-1),@StartDayEndDate)

	SET @sql = '       SELECT '
	SET @sql = @sql + '	p.Product_Code As [Product Code], '
	SET @sql = @sql + '	p.[Description] As [Product Description], '
	SET @sql = @sql + '	pm.[Description] As [Manufacturer], '	
	SET @sql = @sql + ' pt.[Description] As [Product Type], '
	SET @sql = @sql + ' pg.[Description] As [ProductGroup], '
	SET @sql = @sql + '	pd.[Description] As [Product Department], '
	SET @sql = @sql + '	CONVERT(Varchar(10),t.Transaction_Date,111) AS [Transaction Date], '
	SET @sql = @sql + '	t.Transaction_Number AS [Transaction No], '
	SET @sql = @sql + '	d.Extended_Amount AS [Amount], '
	SET @sql = @sql + '	d.Quantity AS [Quantity], '
	SET @sql = @sql + '	CASE IsNull(t.Sys_AW_Transaction_Types_ID,0) '		--Transaction Rep
	SET @sql = @sql + '	WHEN 3 THEN ''' + 'INV' +  ''' '
	SET @sql = @sql + '	WHEN 4 THEN ''' + 'CRN' +  ''' '
	SET @sql = @sql + '	ELSE ''' + 'UNK' +  ''' '
	SET @sql = @sql + '	END As [Transaction Type], '	
	SET @sql = @sql + '	c.Surname AS [Customer Name] '	
	SET @sql = @sql + 'FROM AC_Customers c '
	SET @sql = @sql + '	INNER JOIN AS_Transactions t '
	SET @sql = @sql + '		ON c.AC_Customers_ID = t.AC_Customers_ID '
	SET @sql = @sql + '	INNER JOIN AS_Transaction_Details d '
	SET @sql = @sql + '		ON t.AS_Transactions_ID = d.AS_Transactions_ID '
	SET @sql = @sql + '	INNER JOIN AP_Products p '
	SET @sql = @sql + '		ON p.AP_Products_ID = d.AP_Products_ID '
    SET @sql = @sql + '	INNER JOIN Lup_AP_Product_Departments pd '
    SET @sql = @sql + '		ON p.Lup_AP_Product_Departments_ID = pd.Lup_AP_Product_Departments_ID '
    SET @sql = @sql + '	INNER JOIN Lup_AP_Product_Groups pg ' 
    SET @sql = @sql + '		ON p.Lup_AP_Product_Groups_ID = pg.Lup_AP_Product_Groups_ID '
    SET @sql = @sql + '	INNER JOIN Lup_AP_Product_Manufacturers pm '
    SET @sql = @sql + '		ON p.Lup_AP_Product_Manufacturers_ID = pm.Lup_AP_Product_Manufacturers_ID '
    SET @sql = @sql + '	INNER JOIN Lup_AP_Product_Types pt '
    SET @sql = @sql + '		ON p.Lup_AP_Product_Types_ID = pt.Lup_AP_Product_Types_ID '

   	SET @sql = @sql + ' WHERE '
	SET @sql = @sql + ' t.AW_User_Companies_ID = ' + CONVERT(varchar(30), @CompanyID) + ' AND '   	
    SET @sql = @sql + '	(t.Sys_AW_Transaction_Types_ID = 3 OR '
	SET @sql = @sql + '  t.Sys_AW_Transaction_Types_ID = 4) AND '
    SET @sql = @sql + '	t.Slu_AW_Active_ID = 1 AND '
    SET @sql = @sql + '	ISNULL(t.Total_Amount,0) <> 0 AND '
	SET @sql = @sql + '	ISNULL(d.Extended_Amount,0) <> 0 AND '
	SET @sql = @sql + '	d.Slu_AW_Active_ID = 1 AND '
	SET @sql = @sql + '	p.Slu_AW_YesNo_Non_Stock_Item = 0 AND'    
    SET @sql = @sql + ' t.Day_End >= ''' + CONVERT(varchar(30), @StartDayEndDate) + ''' AND '
    SET @sql = @sql + ' t.Day_End <= ''' + CONVERT(varchar(30), @EndDayEndDate ) + ''' '

	--Exclusions List
    SET @sql = @sql + CONVERT(varchar(8000), @ExclusionsFilter)  
    
	--Inclusions List
    SET @sql = @sql + CONVERT(varchar(8000), @InclusionFilter)  
    
    SET @sql = @sql + 'ORDER BY t.Transaction_Date '    
    
--Select @sql
	Exec (@sql)


SET NOCOUNT OFF
GO

--27 sp_AS_CSales_Submission_REW_SEL
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_CSales_Submission_REW_SEL]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_CSales_Submission_REW_SEL]
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_CSales_Submission_REW_SEL
--Purpose       :Select Sales Submission Data For Rewards
--Parameters    :
--Date          :2014-09-23
--Authors       :RL
--Version       :6.1
--MODS          :
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_CSales_Submission_REW_SEL]
(
	@ExclusionsFilter	varchar(8000),
	@InclusionFilter	varchar(8000),
	@StartDayEndDate	datetime,
	@EndDayEndDate		datetime,
	@CompanyID			int
)
AS

SET NOCOUNT ON

Declare	@No_Days			Int,
		@Temp_No_Days		Varchar(20),
		@sql				Varchar(8000)

    SELECT 
		TOP 1 @Temp_No_Days = ISNULL(Control_Value, 14)
    FROM 
		Sys_AW_Options
    WHERE 
		Control_Type = 'TextBox' AND
        Control_Name = 'txtCBillingDays'

	SET @Temp_No_Days = Replace(@Temp_No_Days,',','')	
	IF @Temp_No_Days = ''
		SET @Temp_No_Days = '14'
	
	IF ISNUMERIC(@Temp_No_Days) = 1
		SET @No_Days = @Temp_No_Days
	
	IF ISNUMERIC(@Temp_No_Days) = 0
		SET @No_Days = 14

	Set @StartDayEndDate = DateAdd(d,(@No_Days*-1),@StartDayEndDate)

	SET @sql = '       SELECT '
	SET @sql = @sql + '	p.Product_Code As [Product Code], '
	SET @sql = @sql + '	p.[Description] As [Product Description], '
	SET @sql = @sql + '	pm.[Description] As [Manufacturer], '	
	SET @sql = @sql + ' pt.[Description] As [Product Type], '
	SET @sql = @sql + ' pg.[Description] As [ProductGroup], '
	SET @sql = @sql + '	pd.[Description] As [Product Department], '
	SET @sql = @sql + '	CONVERT(Varchar(10),t.Transaction_Date,111) AS [Transaction Date], '
	SET @sql = @sql + '	t.Transaction_Number AS [Transaction No], '
	SET @sql = @sql + '	d.Extended_Amount AS [Amount], '
	SET @sql = @sql + '	d.Quantity AS [Quantity], '
	SET @sql = @sql + '	CASE IsNull(t.Sys_AW_Transaction_Types_ID,0) '		--Transaction Rep
	SET @sql = @sql + '	WHEN 3 THEN ''' + 'INV' +  ''' '
	SET @sql = @sql + '	WHEN 4 THEN ''' + 'CRN' +  ''' '
	SET @sql = @sql + '	ELSE ''' + 'UNK' +  ''' '
	SET @sql = @sql + '	END As [Transaction Type], '	
	SET @sql = @sql + '	CASE IsNull(t.Lup_AS_Reps_ID,0) '					--Transaction Rep
	SET @sql = @sql + '	WHEN 0 THEN ''' + '<UNKNOWN>' +  ''' '   
	SET @sql = @sql + '	ELSE IsNull(r.[Description],'''') '	
	SET @sql = @sql + '	END '
	SET @sql = @sql + 'FROM AC_Customers c '
	SET @sql = @sql + '	INNER JOIN AS_Transactions t '
	SET @sql = @sql + '		ON c.AC_Customers_ID = t.AC_Customers_ID '
	SET @sql = @sql + '	INNER JOIN AS_Transaction_Details d '
	SET @sql = @sql + '		ON t.AS_Transactions_ID = d.AS_Transactions_ID '
	SET @sql = @sql + '	INNER JOIN AP_Products p '
	SET @sql = @sql + '		ON p.AP_Products_ID = d.AP_Products_ID '
    SET @sql = @sql + '	INNER JOIN Lup_AP_Product_Departments pd '
    SET @sql = @sql + '		ON p.Lup_AP_Product_Departments_ID = pd.Lup_AP_Product_Departments_ID '
    SET @sql = @sql + '	INNER JOIN Lup_AP_Product_Groups pg ' 
    SET @sql = @sql + '		ON p.Lup_AP_Product_Groups_ID = pg.Lup_AP_Product_Groups_ID '
    SET @sql = @sql + '	INNER JOIN Lup_AP_Product_Manufacturers pm '
    SET @sql = @sql + '		ON p.Lup_AP_Product_Manufacturers_ID = pm.Lup_AP_Product_Manufacturers_ID '
    SET @sql = @sql + '	INNER JOIN Lup_AP_Product_Types pt '
    SET @sql = @sql + '		ON p.Lup_AP_Product_Types_ID = pt.Lup_AP_Product_Types_ID '
	SET @sql = @sql + '	LEFT OUTER JOIN Lup_AS_Reps r '
	SET @sql = @sql + '		ON t.Lup_AS_Reps_ID = r.Lup_AS_Reps_ID '

   	SET @sql = @sql + ' WHERE '
	SET @sql = @sql + ' t.AW_User_Companies_ID = ' + CONVERT(varchar(30), @CompanyID) + ' AND '   	
    SET @sql = @sql + '	(t.Sys_AW_Transaction_Types_ID = 3 OR '
	SET @sql = @sql + '  t.Sys_AW_Transaction_Types_ID = 4) AND '
    SET @sql = @sql + '	t.Slu_AW_Active_ID = 1 AND '
    SET @sql = @sql + '	ISNULL(t.Total_Amount,0) <> 0 AND '
	SET @sql = @sql + '	ISNULL(d.Extended_Amount,0) <> 0 AND '
	SET @sql = @sql + '	d.Slu_AW_Active_ID = 1 AND '
	SET @sql = @sql + '	p.Slu_AW_YesNo_Non_Stock_Item = 0 AND'    
    SET @sql = @sql + ' t.Day_End >= ''' + CONVERT(varchar(30), @StartDayEndDate) + ''' AND '
    SET @sql = @sql + ' t.Day_End <= ''' + CONVERT(varchar(30), @EndDayEndDate ) + ''' '

	--Exclusions List
    SET @sql = @sql + CONVERT(varchar(8000), @ExclusionsFilter)  
    
	--Inclusions List
    SET @sql = @sql + CONVERT(varchar(8000), @InclusionFilter)  
    
    SET @sql = @sql + 'ORDER BY t.Transaction_Date '    
    
--Select @sql
	Exec (@sql)


SET NOCOUNT OFF
GO

--28 sp_AS_POS_Customers_InvDel
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_POS_Customers_InvDel]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_POS_Customers_InvDel]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_POS_Customers_InvDel
--Purpose       :POS Customer Invoice and Delivery Address Details
--Date          :2013/08/08
--Authors       :RL
--RL	V6.1	:2015-03-13 - Fixed - If Firstname was blank it still displayed the /
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_POS_Customers_InvDel]
	(    
    	 @AC_Customer_ID int
	)
AS

SET NOCOUNT ON

    DECLARE @sql varchar(8000),
			@WhichAddress tinyint,
			@WhichName tinyint
	
	SET @WhichAddress = 0
	SET @WhichName = 0

    --> Get Print POSTAL or STREET Addres (0 = POSTAL, 1 = STREET)
	SELECT @WhichAddress = ISNULL(Control_Index, 0)
	FROM Sys_AW_Options
	WHERE Control_Type = 'OptionButton' AND
		Control_Name = 'optPOSPrintAddress' AND
		Control_Value = 'True'

	--> Get Which Name Format To Use
	SELECT TOP 1 @WhichName = ISNULL(Control_Value, '0')
	FROM Sys_AW_Options
	WHERE Control_Index = 0 AND
	Control_Type = 'CheckBox' AND
	Control_Name = 'chkPOSPrintTradeName'

    SET @sql = ' SELECT DISTINCT '        -- DISTINCT is NB NB

	IF @WhichName = 1
		BEGIN
		--RL V6.1 Fixed - If Firstname was blank it still displayed the /
		--SET @sql = @sql + ' RTRIM(LTRIM(a.Surname)) + ISNULL('', '' + A.Initials, '''') + '' / '' + IsNull(A.Firstnames,'''') AS [CurrentInvName], '
			SET @sql = @sql + ' 	CASE WHEN ISNULL(c.Initials,'''') = '''' '
			SET @sql = @sql + ' 	THEN '
			SET @sql = @sql + ' 		CASE WHEN ISNULL(c.Firstnames,'''') = '''' '
			SET @sql = @sql + ' 		THEN LTRIM(RTRIM(c.Surname)) '
			SET @sql = @sql + ' 		ELSE LTRIM(RTRIM(c.Surname)) + '' / '' + LTRIM(RTRIM(c.Firstnames)) '
			SET @sql = @sql + ' 		END '
			SET @sql = @sql + ' 	ELSE '
			SET @sql = @sql + ' 		CASE WHEN ISNULL(c.Firstnames,'''') = '''' '
			SET @sql = @sql + ' 		THEN LTRIM(RTRIM(c.Surname)) + '', '' + LTRIM(RTRIM(c.Initials)) '
			SET @sql = @sql + ' 		ELSE LTRIM(RTRIM(c.Surname)) + '', '' + LTRIM(RTRIM(c.Initials)) + '' / '' + LTRIM(RTRIM(c.Firstnames)) '
			SET @sql = @sql + ' 		END '
			SET @sql = @sql + ' 	END AS [CurrentInvName], '
		END	
	ELSE
		BEGIN
		--RL V6.1 Fixed - If Firstname was blank it still displayed the /
		--SET @sql = @sql + ' RTRIM(LTRIM(A.Surname)) + ISNULL('', '' + A.Initials, '''') AS [CurrentInvName], '	
			SET @sql = @sql + ' 	CASE WHEN ISNULL(c.Initials,'''') = '''' '
			SET @sql = @sql + ' 	THEN LTRIM(RTRIM(c.Surname)) '
			SET @sql = @sql + ' 	ELSE LTRIM(RTRIM(c.Surname)) + '', '' + LTRIM(RTRIM(c.Initials)) '
			SET @sql = @sql + ' 	END AS [CurrentInvName], '
	END
	
	IF @WhichAddress = 0
		BEGIN
			SET @sql = @sql + ' ISNULL(c.Post_Box, '''') AS [CurrentInvAddress1], '
			SET @sql = @sql + ' ISNULL(c.Post_Office, '''') AS [CurrentInvAddress2], '
			SET @sql = @sql + ' ISNULL(c.City, '''') AS [CurrentInvCity], '
			SET @sql = @sql + ' ISNULL(c.Post_Code, '''') AS [CurrentInvPostCode], '
		END	
	ELSE
		BEGIN
			SET @sql = @sql + ' ISNULL(c.Street_Address, '''') AS [CurrentInvAddress1], '
			SET @sql = @sql + ' ISNULL(c.Suburb, '''') AS [CurrentInvAddress2], '
			SET @sql = @sql + ' ISNULL(c.City, '''') AS [CurrentInvCity], '
			SET @sql = @sql + ' ISNULL(c.Street_Post_Code, '''') AS [CurrentInvPostCode], '	
		END
		
    SET @sql = @sql + ' ISNULL(c.Tax_Number, '''') AS [TaxNumber], '
	SET @sql = @sql + ' ISNULL(c.Delivery_Address, '''') AS [CurrentDeliverAddress], '
	SET @sql = @sql + ' ISNULL(c.Delivery_Suburb, '''') AS [CurrentDeliverSuburb], '
	SET @sql = @sql + ' ISNULL(c.Delivery_City, '''') AS [CurrentDeliverCity], '
	SET @sql = @sql + ' ISNULL(c.Delivery_Post_Code, '''') AS [CurrentDeliverPostCode] '

    SET @sql = @sql + ' FROM AC_Customers c '    
    SET @sql = @sql + ' WHERE c.AC_Customers_ID = ' + CONVERT(varchar(10), @AC_Customer_ID) + ' '
    
EXEC (@sql)

SET NOCOUNT OFF
GO

--29 sp_AS_Reverse_Payment_Component_Count
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_Reverse_Payment_Component_Count]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_Reverse_Payment_Component_Count]
GO
------------------------------------------------------------------------------
--Description   :sp_AS_Reverse_Payment_Component_Count
--Purpose       :Select COUNT of Customer Payment Source Transactions components
--Funtionality  :
--Date          :2005/06/07
--Authors       :TB
--MODS          :
--RL	V6.1	:2015-03-13 - Removed the check to see if payment has been allocated
--				 Why would you not be bale to reverse a payment that has not been allocated????
------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AS_Reverse_Payment_Component_Count]
    (
        @TranID int,
        @CompanyID int,
        @TranCount int OUTPUT
    )

AS

SET NOCOUNT ON

    SELECT @TranCount = 1

    --SELECT @TranCount = count(*)
    --FROM AS_Transactions_Transactions st
    --    LEFT JOIN AS_Transactions t
    --        ON st.Destination_AS_Transactions_ID = t.AS_Transactions_ID
    --    LEFT JOIN AC_Customers c
    --        ON t.AC_Customers_ID = c.AC_Customers_ID
    --    LEFT OUTER JOIN Sys_AW_Transaction_Types tt
    --        ON t.Sys_AW_Transaction_Types_ID = tt.Sys_AW_Transaction_Types_ID
    
    --WHERE st.AW_User_Companies_ID = @CompanyID AND
    --      st.Destination_AS_Transactions_ID = @TranID

SET NOCOUNT OFF
GO

--30 sp_AB_Reverse_General_Journal
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AB_Reverse_General_Journal]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AB_Reverse_General_Journal]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AB_Reverse_General_Journal
--Purpose       :Reverse ONE General Journal
--Functionality :Insert REVERSAL GL Journal for the SAME JOURNAL TYPEID and
--              :Posts Reversal GL Transactions
--Date          :2009/03/10
--Authors       :TB
--MODS          :
--RL	V6.1	:2015-03-13 Fixed AB_Journals.Journal_Reference is a Varchar field 
-------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[sp_AB_Reverse_General_Journal]
    (
        @JournalID int,
        @MonthID int,
        @YearID int,
    	@UserID int,
    	@CompanyID int
    )

AS

SET NOCOUNT ON

    DECLARE @JnlID int,
            @JnlDate datetime,
            @JnlShortDate varchar(20),
            @JnlRef varchar(30),
            @JnlNarration varchar(200),
            @JnlMonthID int,
            @JnlYearID int,
            @ReversalNarration varchar(300),
            @GLNarration varchar(50),
            @ReversalDate datetime,
            @JNLHeaderID int,
            @NextGLTranID int,
            @GLAccountID int,
            @Amount money,
            @Notes varchar(50),
            @ReversalAmount money,
            @InsertGLTran bit,
            @GLSourceRef varchar(20),
            @JNLTypeID tinyint,
            @ReturnValue int
            

    SET @ReversalDate = getdate()
    SET @InsertGLTran = 0              --0 = DO NOT insert a GL Transaction in JNL Details
    SET @NextGLTranID = 0
    SET @ReturnValue = 0


    BEGIN

        ---------------------------------------------------------------------
        --> Get the Journal values
        ---------------------------------------------------------------------
        SELECT @JnlID = AB_Journals_ID,
               @JnlDate = Journal_Date,
               @JnlShortDate = LEFT(CONVERT(CHAR(10), Journal_Date, 121), 10),
               @JnlRef = Journal_Reference,
               @JnlNarration = Journal_Narration,
               @JnlMonthID = Slu_AW_Months_ID,
               @JnlYearID = Slu_AW_Years_ID
        FROM AB_Journals
        WHERE AW_User_Companies_ID = @CompanyID AND
              AB_Journals_ID = @JournalID


        SET @GLNarration = 'REVERSAL of Journal ' + 
                            LTRIM(RTRIM(@JnlRef)) +
                            ' dated ' +
                            @JnlShortDate

        SET @GLNarration = LEFT(@GLNarration, 50)

        SET @ReversalNarration = LEFT(@GLNarration  + ' - ' + @JnlNarration, 200)


        ---------------------------------------------------------------------
        --> Get the Journal TypeID (Sys_AB_Transaction_Types_ID)
        ---------------------------------------------------------------------
        SELECT @JNLTypeID = Sys_AB_Transaction_Types_ID
        FROM AB_GL_Transactions
        WHERE AW_User_Companies_ID = @CompanyID AND
              Slu_AW_Months_ID = @JnlMonthID AND
              Slu_AW_Years_ID = @JnlYearID AND
              CONVERT(CHAR(19), AB_Transaction_Date) = CONVERT(CHAR(19), @JnlDate) AND
             --RL V6.1 AB_Journals.Journal_Reference is a Varchar field 
             --(AB_Transaction_Ref = CONVERT(int, @JnlRef) OR
             (CONVERT(VARCHAR(30),AB_Transaction_Ref) = @JnlRef OR             
              AB_Transaction_Ref = CONVERT(int, @JnlID))

        SET @JNLTypeID = ISNULL(@JNLTypeID, 0)

        IF @JNLTypeID = 0
            BEGIN
                SET @JNLTypeID = 15
            END


        ---------------------------------------------------------------------
        --> Create JOURNAL HEADER for REVERSAL Journal
        ---------------------------------------------------------------------
        EXEC @NextGLTranID = sp_AB_Next_Transaction_Number
                15,
                @CompanyID

		EXEC @JNLHeaderID = sp_AB_Insert_Journal_Header
                @ReversalDate,
                @NextGLTranID,
                @ReversalNarration,
                @MonthID,
                @YearID,
                @UserID,
                @CompanyID


        ------------------------------------------------------------
        --> INSERT Reversal DETAIL items
        ------------------------------------------------------------
    	DECLARE Reversal_Cursor CURSOR FOR
            (
                SELECT AB_Accounts_ID,
                       Amount,
                       Notes
                FROM AB_Journal_Details
                WHERE AW_User_Companies_ID = @CompanyID AND
                      AB_Journals_ID = @JournalID
            )

    	OPEN Reversal_Cursor

        	FETCH NEXT FROM Reversal_Cursor 
        	INTO
                @GLAccountID,
                @Amount,
                @Notes

        	WHILE @@FETCH_STATUS = 0
        	BEGIN

                SET @ReversalAmount = @Amount * -1
                SET @GLSourceRef = CONVERT(varchar(20), @JNLHeaderID)

                --> INSERT JOURNAL DETAIL
                EXEC sp_AB_Insert_Journal_Detail
                        @JNLHeaderID,
                        @GLAccountID,
                        @ReversalAmount,
                        @Notes,
                        @UserID,
                        @CompanyID,
                        @InsertGLTran


                --> INSERT GL TRANSACTION
                EXEC sp_AB_Insert_GL_Transactions
                        @GLNarration,
                        @JNLTypeID,
                        @GLAccountID,
                        @ReversalDate,
                        @GLSourceRef,
                        @MonthID,
                        @YearID,
                        @NextGLTranID,
                        @ReversalAmount,
                        @UserID,
                        @CompanyID


            	FETCH NEXT FROM Reversal_Cursor 
            	INTO
                    @GLAccountID,
                    @Amount,
                    @Notes

        	END

    	CLOSE Reversal_Cursor

    	DEALLOCATE Reversal_Cursor


        SET @ReturnValue = @JNLHeaderID

    END



RETURN @ReturnValue


SET NOCOUNT OFF
GO

--31 sp_AS_Transactions_Address_Insert
IF  EXISTS (SELECT * 
            FROM dbo.sysobjects 
            WHERE id = OBJECT_ID(N'[dbo].[sp_AS_Transactions_Address_Insert]') 
            AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_AS_Transactions_Address_Insert]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------
--Description   :sp_AS_Transactions_Address_Insert
--Purpose       :Keeps a record of address details used on Invoices
--Functionality :Links Address details to an invoice
--Date          :2013-01-02
--Authors       :RL
--Mod			:RL 2013-08-27 Swapped @Company_ID And @AC_Customers_ID
------------------------------------------------------------------------------- 
CREATE Procedure [dbo].[sp_AS_Transactions_Address_Insert]
    (	@AC_Customers_ID	int,	--RL 2013-08-27 Swapped @Company_ID And @AC_Customers_ID	
		@Company_ID	int,			--In POS code, Customer is sent through first
    	@AS_Transactions_ID int,
    	@Inv_Customer_Name varchar(100),
		@Inv_Address1 varchar(40),
		@Inv_Address2 varchar(40),
		@Inv_City varchar(30),
		@Inv_Code varchar(10),
		@Inv_Tax_Number	varchar(16),
		@Delivery_Address varchar(40),
		@Delivery_Suburb varchar(40),
		@Delivery_City varchar(30),
		@Delivery_Post_Code varchar(10),
		@User_ID	int
    )
AS 

	SET NOCOUNT ON
    
	DECLARE 
		@AS_Transactions_Address_Detail_ID	int,
    	@AW_YesNo_Delivery_Address int,
    	@AW_YesNo_Invoice int

--    SELECT 
--		@AC_Customers_ID = AC_Customers_ID,
--		@User_ID = User_ID,
--		@Company_ID = AW_User_Companies_ID
--	FROM AS_Transactions
--	WHERE AS_Transactions_ID = @AS_Transactions_ID

	SET @AW_YesNo_Delivery_Address = 0
	SET @AW_YesNo_Invoice = 0
	SET @AS_Transactions_Address_Detail_ID = 0
		
	SET @Inv_Customer_Name = LTRIM(RTRIM(ISNULL(@Inv_Customer_Name,'')))
	SET @Inv_Address1 = LTRIM(RTRIM(ISNULL(@Inv_Address1,'')))
	SET @Inv_Address2 = LTRIM(RTRIM(ISNULL(@Inv_Address2,'')))
	SET @Inv_Code = LTRIM(RTRIM(ISNULL(@Inv_Code,'')))
	SET @Inv_City = LTRIM(RTRIM(ISNULL(@Inv_City,'')))
	SET @Inv_Tax_Number = LTRIM(RTRIM(ISNULL(@Inv_Tax_Number,'')))
	SET @Delivery_Address = LTRIM(RTRIM(ISNULL(@Delivery_Address,'')))
	SET @Delivery_Suburb = LTRIM(RTRIM(ISNULL(@Delivery_Suburb,'')))
	SET @Delivery_City = LTRIM(RTRIM(ISNULL(@Delivery_City,'')))
	SET @Delivery_Post_Code = LTRIM(RTRIM(ISNULL(@Delivery_Post_Code,'')))

	IF (
		@Delivery_Address <> '' Or
		@Delivery_Suburb <> '' Or
		@Delivery_City <> '' Or
		@Delivery_Post_Code <> ''
		)
	BEGIN
		SET @AW_YesNo_Delivery_Address = 1
	END	

	IF (
		@Inv_Customer_Name <> '' Or
		@Inv_Address1 <> '' Or
		@Inv_Address2 <> '' Or
		@Inv_Code <> '' Or
		@Inv_City <> '' Or
		@Inv_Tax_Number <> ''
		)
	BEGIN
		SET @AW_YesNo_Invoice = 1
	END
		 

	SELECT @AS_Transactions_Address_Detail_ID = AS_Transactions_Address_Detail_ID
	FROM AS_Transactions_Address_Detail
	WHERE AC_Customers_ID = @AC_Customers_ID AND
		  Customer_Name = @Inv_Customer_Name AND
		  Inv_Address1 = @Inv_Address1 AND
		  Inv_Address2 = @Inv_Address2 AND
		  Inv_Code = @Inv_Code AND
		  Inv_City = @Inv_City AND
		  Tax_Number = @Inv_Tax_Number AND
		  Delivery_Address = @Delivery_Address AND
		  Delivery_Suburb = @Delivery_Suburb AND
		  Delivery_City = @Delivery_City AND
		  Delivery_Post_Code = @Delivery_Post_Code

	IF @AS_Transactions_Address_Detail_ID = 0
	BEGIN
		INSERT INTO AS_Transactions_Address_Detail
			(
				AC_Customers_ID, 
				Customer_Name,
				Inv_Address1, 
				Inv_Address2, 
				Inv_Code, 
				Inv_City, 
				Tax_Number,
				Delivery_Address, 
				Delivery_Suburb, 
				Delivery_City, 
				Delivery_Post_Code, 
				Date_Captured, 
				User_ID, 
				AW_User_Companies_ID,
				AW_YesNo_Delivery_Address,
				AW_YesNo_Invoice
			)
		VALUES
			(
				@AC_Customers_ID,
				@Inv_Customer_Name,
				@Inv_Address1,
				@Inv_Address2,
				@Inv_Code,
				@Inv_City,
				@Inv_Tax_Number,
				@Delivery_Address,
				@Delivery_Suburb,
				@Delivery_City,
				@Delivery_Post_Code,
				GETDATE(),
				@User_ID,
    			@Company_ID,
    			@AW_YesNo_Delivery_Address,
    			@AW_YesNo_Invoice
			)
			
		SELECT @AS_Transactions_Address_Detail_ID = Scope_Identity()
		
		INSERT INTO AS_Transactions_Address
			(
				AS_Transactions_ID, 
				AS_Transactions_Address_Detail_ID, 
				Date_Captured, 
				User_ID, 
				AW_User_Companies_ID
			)
		VALUES
			(
				@AS_Transactions_ID,
				@AS_Transactions_Address_Detail_ID,
				GETDATE(),
				@User_ID,
    			@Company_ID
			)	
	END
	ELSE
	BEGIN
		INSERT INTO AS_Transactions_Address
			(
				AS_Transactions_ID, 
				AS_Transactions_Address_Detail_ID, 
				Date_Captured, 
				User_ID, 
				AW_User_Companies_ID
			)
		VALUES
			(
				@AS_Transactions_ID,
				@AS_Transactions_Address_Detail_ID,
				GETDATE(),
				@User_ID,
    			@Company_ID
			)		
	END
SET NOCOUNT OFF	
GO

--32 AS_Transactions_Address_Detail Alter Customer Name Width
--Column width used to be 50
ALTER TABLE AS_Transactions_Address_Detail ALTER  COLUMN Customer_Name Varchar(100) NULL
GO




--XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
--XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
---------------------------------------------------------------------------------
-- Updating Table AA_Release
---------------------------------------------------------------------------------
IF NOT EXISTS
    (
        SELECT AA_Release_ID
        FROM AA_Release
        WHERE Release = '2015.6.1'
    )
    BEGIN
        INSERT AA_Release
            (
                Release,
                Updated_by			  
            )
        VALUES
            (
                '2015.6.1',
                'Download'
            )
    END
ELSE
    BEGIN
        UPDATE AA_Release
        SET Updated_by = 'Download',
            Date_Updated = getdate()
        WHERE Release = '2015.6.1'
    END   
    
GO    





